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 03f5044eb7..0c1df4d142 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", diff --git a/Cargo.toml b/Cargo.toml index 35be6fd24b..1af59ddfe4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,14 +11,14 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "14d5dbb50c317b8747a9cf9eb35ab8a22515f137" } # craft-update: app-specific pretend versions apply to startup and manual checks. @@ -147,14 +147,12 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -# The PDF writer takes craft-libs#417 (CMYK, gray and spot colors keep their exact inks); the other -# craft-libs crates stay at 92d392cf. craft-pdf's sources are the same at both revisions. -krilla = { git = "https://github.com/storytold/craft-libs", rev = "fb08be5fa19eee8d37e624397fcdc96df6035e92" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } 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..bce1cab0c4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Color Effects add-on's Find Nearest Swatch; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). @@ -214,6 +215,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. | diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 60e8a0234d..bc75f09cf1 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -884,7 +884,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..eb7bd8865e 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1316,6 +1316,42 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() { } } +/// A symbol instance at the root of an opacity mask is filtered like one among the children: when +/// its symbol draws a brushed stroke the mask goes (it would run the brush again from inside the +/// mask, without end), and a mask whose root symbol is plain stays. +#[test] +fn pieces_leave_out_a_mask_whose_root_draws_a_brushed_stroke() { + use vectorcraft_doc::{OpacityMask, Symbol}; + let mut doc = Document::new(100.0, 100.0); + let mut brushed = rect_art(10.0, 4.0); + brushed.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("s".into()), ..stroke(1.0) })); + for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed)] { + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art) }); + } + let instance = |symbol: &str| Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let masked = |symbol: &str| { + let mut n = rect_art(10.0, 4.0); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(instance(symbol), true))); + n + }; + let art = Node::group(NodeId(0), [masked("plain"), masked("brushed")].map(std::sync::Arc::new).into()); + let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) }; + let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 100.0, 0.0), &stroke(1.0)); + assert!(!out.is_empty()); + for piece in &out { + let roots: Vec> = piece + .children() + .unwrap() + .iter() + .map(|c| match c.extras().mask.as_ref().map(|m| &m.art.kind) { + Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.as_str()), + _ => None, + }) + .collect(); + assert_eq!(roots, [Some("plain"), None], "the plain mask stays and the brushed one goes"); + } +} + /// Anchors a brushed stroke emitted, which is what the output budget counts. fn anchors(nodes: &[Node]) -> usize { nodes diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 6857c2a175..ee14e81f5c 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,8 @@ const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are const XREFS: &str = "blocks referencing other drawings (external references) are left out"; const TOO_MANY: &str = "the drawing has more than 2,000,000 objects: the rest are left out"; const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points: the rest are left out"; +const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid"; +const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out"; /// What a block's art takes from the insert that places it: its colour, lineweight, linetype /// and opacity where the art says "by block", and its layer for art on layer 0. @@ -71,6 +82,9 @@ pub(crate) struct Build<'d, 'a> { visits: usize, /// Path elements made so far. elements: usize, + /// Dash lengths and text bytes kept so far. + dash_values: usize, + text_bytes: usize, warnings: Vec, } @@ -128,6 +142,8 @@ impl<'d, 'a> Build<'d, 'a> { nodes: 0, visits: 0, elements: 0, + dash_values: 0, + text_bytes: 0, warnings: vec![], } } @@ -138,6 +154,20 @@ impl<'d, 'a> Build<'d, 'a> { } } + /// Take `bytes` of text from [`MAX_TEXT_BYTES`]; false (with a warning) when they don't fit. + fn charge_text(&mut self, bytes: usize) -> bool { + match self.text_bytes.checked_add(bytes).filter(|t| *t <= MAX_TEXT_BYTES) { + Some(t) => { + self.text_bytes = t; + true + } + None => { + self.warn(TOO_MUCH_TEXT); + false + } + } + } + /// Import `layout`; `natural` and `ratio` are points per drawing unit in the drawing's own /// unit and at the scale asked for (fitting computes its own). pub fn run(mut self, layout: &LayoutDef, natural: f64, ratio: f64) -> Result<(Document, Vec), String> { @@ -484,9 +514,15 @@ impl<'d, 'a> Build<'d, 'a> { if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut() && let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale) { - s.dash = Some(dash); - if dots { - s.cap = LineCap::Round; + match self.dash_values.checked_add(dash.pattern.len()).filter(|n| *n <= MAX_DASH_VALUES) { + Some(n) => { + self.dash_values = n; + s.dash = Some(dash); + if dots { + s.cap = LineCap::Round; + } + } + None => self.warn(TOO_MANY_DASHES), } } ap @@ -527,10 +563,15 @@ impl<'d, 'a> Build<'d, 'a> { if !(s > 1e-12 && s.is_finite()) { return None; } - let family = t.family.clone().or_else(|| self.d.styles.get(&t.style).filter(|f| !f.is_empty()).cloned()); + let d = self.d; + let family = t.family.as_deref().or_else(|| d.styles.get(&t.style).map(String::as_str).filter(|f| !f.is_empty())); + let family = family.filter(|f| f.len() <= MAX_FAMILY_BYTES); + if !self.charge_text(t.text.len().saturating_add(family.map_or(0, str::len))) { + return None; + } let default = CharStyle::default(); let style = CharStyle { - font_family: family.unwrap_or(default.font_family.clone()), + font_family: family.map_or_else(|| default.font_family.clone(), str::to_string), size: t.height / CAP_HEIGHT * s, h_scale: t.width * 100.0, leading: t.leading.map(|l| l * s), @@ -558,6 +599,13 @@ impl<'d, 'a> Build<'d, 'a> { for cell in &ins.cells { let node = match &symbol { Some(name) => { + if self.nodes >= MAX_NODES { + self.warn(TOO_MANY); + break; + } + if !self.charge_text(name.len()) { + break; + } let xf = map * *cell * self.symbol_map.inverse(); self.nodes += 1; Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf })) @@ -581,14 +629,19 @@ impl<'d, 'a> Build<'d, 'a> { /// The art of block `name` drawn by `map`, as one object. fn art(&mut self, name: &str, map: Affine, inh: &Inherit, depth: u32) -> Option { - self.visits += 1; - if self.visits > MAX_VISITS { - if self.visits == MAX_VISITS + 1 { - self.warn(TOO_MANY); - } + if self.visits >= MAX_VISITS { + self.warn(TOO_MANY); return None; } - let items = self.block(name)?; + let items = self.block(name); + // Each placement looks at every item of the block, drawn or not (art on a hidden layer + // makes nothing, so the node budget doesn't bound it). + self.visits = self.visits.saturating_add(1 + items.as_ref().map_or(0, |i| i.len())); + if self.visits > MAX_VISITS { + self.warn(TOO_MANY); + return None; + } + let items = items?; if !self.enter(name, depth) { return None; } diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 6bd3d1c106..978505ddf3 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -1177,3 +1177,101 @@ fn many_array_inserts_of_a_missing_block_stay_bounded() { assert!(total <= 2_000_000 + 3000, "total cells materialised: {total}"); assert!(conv.warnings.iter().any(|w| w.contains("array inserts")), "{:?}", conv.warnings); } + +#[test] +fn dashed_lines_past_the_dash_budget_are_drawn_solid() { + // 600 lines of a two-length linetype: 1,200 dash lengths, past the 1,000 tests import with. + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + let line = [(0, "LINE"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]; + let e: Vec<(i32, &str)> = (0..600).flat_map(|_| line).collect(); + let r = open(&drawing(&[], &tables, &[], &e), &points()); + let (mut dashed, mut solid, mut kept) = (0, 0, 0); + r.document.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + match n.appearance.stroke().and_then(|s| s.dash.as_ref()) { + Some(d) => { + dashed += 1; + kept += d.pattern.len(); + } + None => solid += 1, + } + } + }); + assert_eq!(dashed + solid, 600); + assert!(dashed > 0 && solid > 0, "{dashed} dashed, {solid} solid"); + assert!(kept <= 1_000, "{kept} dash lengths kept"); + assert!(r.warnings.iter().any(|w| w.contains("drawn solid")), "{:?}", r.warnings); +} + +/// The bytes of text in the document's text objects. +fn text_bytes(doc: &Document) -> usize { + let mut bytes = 0; + doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + bytes += t.runs.iter().map(|r| r.text.len()).sum::(); + } + }); + bytes +} + +#[test] +fn text_copied_into_array_cells_stops_at_the_text_budget() { + // 1,000 characters of text in an anonymous block placed 10 × 10: 100 KB of copies, past the + // 64 KB tests import with. + let long = "x".repeat(1000); + let blocks = + [(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0"), (0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, long.as_str()), (0, "ENDBLK")]; + let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "1"), (45, "1")]; + let r = open(&drawing(&[], &[], &blocks, &insert), &points()); + let bytes = text_bytes(&r.document); + assert!(bytes > 0, "some copies are kept"); + assert!(bytes <= 64 << 10, "{bytes} bytes of text"); + assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings); +} + +#[test] +fn a_text_style_naming_an_overlong_font_family_takes_the_default() { + let family = "F".repeat(10_000); + let tables = [(0, "TABLE"), (2, "STYLE"), (0, "STYLE"), (2, "Big"), (3, "x.ttf"), (1001, "ACAD"), (1000, family.as_str()), (0, "ENDTAB")]; + let e = [(0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, "Hi"), (7, "Big")]; + let doc = open(&drawing(&[], &tables, &[], &e), &points()).document; + let mut families = vec![]; + doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + families.extend(t.runs.iter().map(|r| r.style.font_family.clone())); + } + }); + assert_eq!(families, [vectorcraft_doc::CharStyle::default().font_family]); +} + +#[test] +fn symbol_instances_of_a_long_block_name_stop_at_the_text_budget() { + // A 1,000-byte block name placed 10 × 10: each instance keeps its own copy of the name. + let name = "N".repeat(1000); + let blocks = [(0, "BLOCK"), (2, name.as_str()), (10, "0"), (20, "0"), (0, "LINE"), (10, "0"), (20, "0"), (11, "1"), (21, "0"), (0, "ENDBLK")]; + let insert = [(0, "INSERT"), (2, name.as_str()), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "2"), (45, "2")]; + let r = open(&drawing(&[], &[], &blocks, &insert), &points()); + let mut instances = 0; + r.document.walk(|n| { + if let NodeKind::SymbolInstance { .. } = n.kind { + instances += 1; + } + }); + assert!(instances > 0 && instances < 100, "{instances} instances"); + assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings); +} + +#[test] +fn arrays_of_blocks_of_hidden_art_stop_at_the_work_budget() { + // 500 lines on a hidden layer in an anonymous block placed 50 × 50: they make nothing, but + // each placement looks at all of them (1,250,000 items, past the 1,000,000 tests import with). + let tables = [(0, "TABLE"), (2, "LAYER"), (0, "LAYER"), (2, "Off"), (70, "0"), (62, "-1"), (0, "ENDTAB")]; + let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")]; + for _ in 0..500 { + blocks.extend([(0, "LINE"), (8, "Off"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + } + blocks.push((0, "ENDBLK")); + let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "50"), (71, "50"), (44, "1"), (45, "1")]; + let r = open(&drawing(&[], &tables, &blocks, &insert), &points()); + assert!(r.warnings.iter().any(|w| w.contains("more than")), "{:?}", r.warnings); +} 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/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/hit.rs b/crates/doc/src/hit.rs index d20c1ffe4e..573d8fec43 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 => { 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/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/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/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/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 8d9fe0b3fd..8e4c57d065 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -125,6 +125,8 @@ pub struct Flavour { /// Longest side (px) of the PNG Copy offers: larger art is scaled down to fit. const COPY_PNG_SIDE: f64 = 4096.0; +/// The smallest scale (pixels a point) the PNG encoder renders at. +const MIN_COPY_PNG_SCALE: f64 = 0.01; /// Most bytes of text `clipboard.importText` takes. const MAX_TEXT: usize = 1 << 20; /// Most bytes of images the SVG markup may embed and still go out as plain text. A paste reads the @@ -293,7 +295,8 @@ impl Clipboard { /// What Copy offers other apps, best first, with Include SVG Code (`svg`) and On Copy: PDF /// (`pdf`) as given (see `clipboard.flavours`). A [`Flavour`] that can't be made (art too large - /// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side. + /// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side, and + /// left out when even [`MIN_COPY_PNG_SCALE`] can't bring it that small. pub fn flavours(&self, svg: bool, pdf: bool) -> Vec { self.flavours_with_warnings(svg, pdf).0 } @@ -320,7 +323,14 @@ impl Clipboard { PDF => self.pdf().inspect_err(|e| log::warn!("clipboard PDF: {e}")).ok().flatten().map(&mut keep), _ => { let side = self.bounds().map_or(1.0, |b| b.width().max(b.height())); - let scale = (COPY_PNG_SIDE / side).clamp(0.01, 1.0); + let scale = (COPY_PNG_SIDE / side).min(1.0); + // The encoder renders at no fewer than MIN_COPY_PNG_SCALE pixels a point: art + // too large to fit COPY_PNG_SIDE at that scale gets no PNG, rather than one + // of up to a gigabyte of pixels. + if scale < MIN_COPY_PNG_SCALE { + log::warn!("clipboard PNG: art {side} pt across is too large to copy as a picture"); + continue; + } self.png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten().map(|(png, _, _, notes)| keep((png, notes))) } }; diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 3d77bde156..58d5daf17a 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -325,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/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 19381709ab..dcc8833a87 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -698,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) } @@ -1275,9 +1277,33 @@ fn remember(s: &mut Session, p: &Value) { let _ = store_settings(s, settings); } +/// The PDF passwords an export may be given (`security` of a PDF row or of `settings.pdf`). +const PASSWORD_KEYS: [&str; 2] = ["openPassword", "permissionsPassword"]; + +/// `settings` without the PDF passwords anywhere in them: settings kept in the document (which +/// native saves write) or in the preferences hold the export's choices, never its secrets, as +/// the PDF settings themselves are saved without them. +fn remove_passwords(settings: &mut Map) { + for key in PASSWORD_KEYS { + settings.remove(key); + } + for v in settings.values_mut() { + remove_passwords_in(v); + } +} + +fn remove_passwords_in(v: &mut Value) { + match v { + Value::Object(m) => remove_passwords(m), + Value::Array(items) => items.iter_mut().for_each(remove_passwords_in), + _ => {} + } +} + /// Make `settings` the document's export settings. Not an undo step (like the settings of any /// export); the document has changed only if they differ. -pub(crate) fn store_settings(s: &mut Session, settings: Map) -> 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; @@ -1334,4 +1360,21 @@ mod tests { assert_eq!(safe_file_name("lpt9 .png"), "lpt9-.png"); assert_eq!(safe_file_name("My CON .png"), "My CON .png"); } + + /// The settings an export leaves in the document keep its PDF security choices but not its + /// passwords, in a row or in `settings.pdf`. + #[test] + fn stored_settings_leave_out_pdf_passwords() { + let mut s = crate::Session::new(); + s.execute("file.new", &serde_json::json!({"width": 100, "height": 100})).unwrap(); + let given = serde_json::json!({ + "formats": [{"format": "pdf", "security": {"openPassword": "open sesame", "permissionsPassword": "owner", "printing": "low"}}], + "settings": {"pdf": {"security": {"openPassword": "open sesame", "copy": false}}}, + }); + super::store_settings(&mut s, given.as_object().unwrap().clone()).unwrap(); + let kept = serde_json::Value::Object(s.doc().unwrap().doc.export_settings.clone()); + assert!(!kept.to_string().contains("Password"), "{kept}"); + assert_eq!(kept["formats"][0]["security"]["printing"], "low"); + assert_eq!(kept["settings"]["pdf"]["security"]["copy"], false); + } } 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/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 36c9589cd1..66f04f0ef9 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -2588,6 +2588,18 @@ fn formatting_the_whole_graphs_text_survives_it_being_drawn_again() { assert_eq!(spec(&s, id).label_styles, vectorcraft_doc::LabelStyles::default()); } +/// A stroke given to all of a graph's text without a weight is kept at 1 pt, as `paint.setStroke` keeps it. +#[test] +fn a_stroke_given_to_the_whole_graphs_text_is_kept_at_1_pt() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"stroke": "#ff0000"})).unwrap(); + let legend = spec(&s, id).label_styles.legend.unwrap(); + assert_eq!((legend.stroke.color().map(|c| c.to_hex()), legend.stroke_width), (Some("#ff0000".into()), 1.0)); +} + #[test] fn formatting_one_label_keeps_that_kind_of_label() { let mut s = Session::new(); 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/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/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cb6b1d0b59..4b8baa7c73 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -477,10 +477,12 @@ fn name_param<'a>(p: &'a Value, kind: Kind, verb: &str) -> Result<&'a str> { str_param(p, "name").ok_or_else(|| bad(&kind.cmd(verb), "missing `name`")) } -/// The `attrs` of `p`, validated. `kept` holds the style's current attributes (`charStyle.edit`) or -/// the target text's attributes (`charStyle.new`): a language tag that is not in the list, which a -/// file can give a style or a run, stays when `attrs` keeps it. -fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map>) -> 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 +492,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 +521,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 +598,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 +734,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 +746,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 +794,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..db7082f054 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -93,7 +93,12 @@ thread_local! { /// makes "changed" a pointer comparison). Deleted frames' text flows into the remaining ones; a /// frame that is now point type leaves its thread with the text it holds. pub(crate) fn reflow(before: &Document, doc: &mut Document) { - let threads = std::mem::take(&mut doc.text_threads); + // A frame is in one thread, once: a file that lists it again (in its thread or another) would + // copy its text into the story each time, and write the grown story back for the next thread + // to copy again. Only its first place counts. + let mut seen = std::collections::HashSet::new(); + let threads: Vec> = + std::mem::take(&mut doc.text_threads).into_iter().map(|t| t.into_iter().filter(|id| seen.insert(*id)).collect()).collect(); let mut kept = vec![]; for thread in threads { let changed = thread.iter().any(|id| match (before.node(*id), doc.node(*id)) { diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 07531d4edd..2dfb119fec 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -40,6 +40,24 @@ fn thread_flows_reflows_on_edit_and_survives_delete() { assert_eq!(s.doc().unwrap().doc.text_threads.len(), 1); } +/// A file that lists a frame more than once, in its own thread or in another, flows the story +/// through each frame once: repeated places would copy its text again and again. +#[test] +fn frames_listed_twice_flow_the_story_once() { + let (mut s, a, b) = setup(); + s.execute("text.thread.create", &json!({})).unwrap(); + let mut d = (*s.doc().unwrap().doc).clone(); + let (fa, fb) = (NodeId(a), NodeId(b)); + d.text_threads = vec![vec![fa, fb, fa, fb, fa], vec![fb, fa], vec![fa, fb]]; + reflow(&Document::new(1.0, 1.0), &mut d); + assert_eq!(d.text_threads, vec![vec![fa, fb]]); + let plain = |id: NodeId| match &d.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + }; + assert_eq!(format!("{}{}", plain(fa), plain(fb)), TEXT.repeat(4)); +} + #[test] fn edits_copy_only_the_stories_of_threads_whose_frames_changed() { let (mut s, a, b) = setup(); 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/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/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/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/clipflavours.rs b/crates/engine/src/tests/clipflavours.rs index fd72f2980d..c490c2684f 100644 --- a/crates/engine/src/tests/clipflavours.rs +++ b/crates/engine/src/tests/clipflavours.rs @@ -350,6 +350,25 @@ fn type_only_copies_offer_their_text() { assert!(run(&mut s, "clipboard.exportText", json!({}))["text"].is_null()); } +/// Art too large to fit the clipboard's PNG side at the encoder's smallest scale gets no PNG, +/// instead of a picture hundreds of megabytes large. +#[test] +fn copy_leaves_out_the_png_of_art_too_large_to_scale_down() { + let mut s = session(); + let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 1_000_000, "height": 1_000_000}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "edit.copy", json!({})); + assert!(s.clipboard.flavour_types(false, false).contains(&PNG)); + assert!(s.clipboard.flavours(false, false).iter().all(|f| f.mime != PNG)); + // Art that fits at that scale still gets its PNG, at most 4096 pixels a side. + let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 200_000, "height": 100}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "edit.copy", json!({})); + let png = s.clipboard.flavours(false, false).into_iter().find(|f| f.mime == PNG).expect("a PNG"); + let img = image::load_from_memory(&png.data).unwrap(); + assert!(img.width() <= 4096 && img.height() <= 4096, "{}x{}", img.width(), img.height()); +} + #[test] fn copy_offers_flavours_by_the_preferences() { let mut s = session(); 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/menucmds.rs b/crates/engine/src/tests/menucmds.rs index f378554562..0c351dba7d 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1991,6 +1991,19 @@ fn select_same_text_fill_and_stroke_color_needs_both_to_match() { assert!(s.execute("select.same.textFillAndStrokeColor", &json!({})).is_err()); } +#[test] +fn select_same_character_colors_ignore_empty_text() { + let mut s = session(); + let a = id_of(&s.execute("text.create", &json!({"x": 0, "y": 20, "text": "a"})).unwrap()); + let b = id_of(&s.execute("text.create", &json!({"x": 0, "y": 40, "text": "b"})).unwrap()); + let empty = id_of(&s.execute("text.create", &json!({"x": 0, "y": 60, "text": ""})).unwrap()); + for cmd in ["select.same.textFillColor", "select.same.textStrokeColor", "select.same.textFillAndStrokeColor"] { + sel(&mut s, &[a]); + s.execute(cmd, &json!({})).unwrap(); + assert_eq!(selected(&s), vec![a, b], "{cmd}: empty object {empty:?}"); + } +} + #[test] fn select_same_link_block_series_selects_the_frames_of_a_thread() { let mut s = session(); 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/textedit.rs b/crates/engine/src/tests/textedit.rs index a3e8f7c66e..2cdf299ce8 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(); @@ -1204,6 +1257,28 @@ fn type_tool_selection_replace_and_delete() { assert_eq!(obj(&s, id).plain_text(), " "); } +/// A Type tool click inside a ligature (Source Serif 4's fi) puts the caret between its +/// characters, and Shift+Right from there selects the i alone. +#[test] +fn type_tool_click_reaches_the_inside_of_a_ligature() { + let mut s = session(); + let v = ViewInfo::default(); + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "fin", "size": 40, "font": "Source Serif 4"})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.select_tool("type", v).unwrap(); + let t = obj(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let g = lay.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph"); + let (_, f) = g.carets[0]; + let p = t.xf * (g.origin + vectorcraft_geom::Vec2::new(g.advance * f + 0.2, -10.0)); + click(&mut s, p.x, p.y); + assert_eq!(s.tool_options()["caret"], json!(1), "between the f and the i"); + key(&mut s, ToolKey::Right, Mods { shift: true, ..Default::default() }); + assert_eq!((s.tool_options()["start"].as_u64(), s.tool_options()["end"].as_u64()), (Some(1), Some(2))); + s.tool_text("I", v).unwrap(); + assert_eq!(obj(&s, id).plain_text(), "fIn"); +} + #[test] fn character_panel_flow_styles_the_selected_range_while_editing() { let mut s = session(); 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/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/tooling.rs b/crates/engine/src/tooling.rs index ecbc459643..4eb1912294 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -358,26 +358,87 @@ impl Session { /// Feed a pointer event to the active tool. Returns requests for the UI. pub fn pointer(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result> { + 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)?; } @@ -658,11 +719,27 @@ impl Session { self.tool.options() } pub fn set_tool_option(&mut self, key: &str, v: &Value) { + if key == "queue" && self.tool.id() == "place" { + self.note_place_queue_roots(); + } self.tool.set_option(key, v); self.tool_set_since_reset = true; self.keep_tool_settings(); } + /// Keep the automation roots in force now as those the place cursor's queue, being loaded, + /// is placed under ([`Session::place_queue_roots`]). + fn note_place_queue_roots(&mut self) { + self.place_queue_roots = crate::file_access::current(); + } + + /// The automation roots the place cursor's files are placed under: those in force when it + /// was loaded. A frontend that places them itself ([`UiRequest::Place`]) reads them within + /// these roots ([`crate::file_access::confine`]). + pub fn place_queue_roots(&self) -> Option> { + self.place_queue_roots.clone() + } + /// The options of tool `id`: the active tool's, or those it would have if chosen now. pub fn tool_options_of(&self, id: &str) -> Value { if id == self.tool.id() { self.tool.options() } else { self.make_tool(id).options() } @@ -673,6 +750,9 @@ impl Session { /// Liquify tools' Global Brush Dimensions, the Smooth tool's Fidelity for Pencil, Paintbrush /// and Blob Brush Alt smoothing). Returns the tool's options. pub fn set_tool_options(&mut self, id: Option<&str>, values: &Map) -> Value { + if values.contains_key("queue") && id.unwrap_or(self.tool.id()) == "place" { + self.note_place_queue_roots(); + } let active = id.is_none_or(|id| id == self.tool.id()); self.tool_set_since_reset |= active; let mut other = (!active).then(|| self.make_tool(id.unwrap_or_default())); @@ -842,6 +922,13 @@ impl Session { } // The place cursor's file, placed by the frontend that asked for it. Action::Exec(cmd, p) if cmd == "file.place" && self.place_cursor_requests => ui.push(UiRequest::Place(p)), + // The place cursor's file, read within the roots of whoever loaded the cursor. + Action::Exec(cmd, p) if cmd == "file.place" => { + let roots = self.place_queue_roots.clone(); + if let Some(w) = crate::file_access::confine(roots.as_ref(), || self.execute(&cmd, &p))?.get("warning").and_then(Value::as_str) { + ui.push(UiRequest::Status(w.to_string())); + } + } Action::Exec(cmd, p) => { // A command's warning (Crop Image's when the image couldn't be decoded) goes to the // status bar too. diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index bd9069bd20..5b858b5f78 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3601,6 +3601,40 @@ proptest! { } } +/// A pattern's definition in the version 7 form (§3.4): a layer whose `_ &` fills the tile's box, +/// and one whose tile string has CR-separated lines, comments and escapes. +const LEGACY_PATTERN: &str = "%AI3_BeginPattern: (P)\n(P) 0 0 10 10 [\n%AI3_Tile\n(0 O 0 R 0 0 0 0.5 k) @ _ &\n\ + (0 O 1 R 0 0 0 1 \\(Ink\\) 0 X) @ (\r%AI6_BeginPatternLayer\r1 w u\r0 5 m\\r10 5 L\rS\rU\r%AI6_EndPatternLayer\r) &\n] E\n%AI3_EndPattern\n"; + +/// [`NAMED_PROLOG_AI`] with `pattern` in its setup, filling the square. +fn legacy_pattern_ai(pattern: &str) -> String { + NAMED_PROLOG_AI + .replace("%AI5_Begin_NonPrinting", &format!("{pattern}%AI5_Begin_NonPrinting")) + .replace("\n10 10 m\n", "\n(P) 5 5 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n10 10 m\n") + .replace("10 10 L\nS\n", "10 10 L\nB\n") +} + +/// The fixture, as it is, opens with the pattern filling the square. +#[test] +fn the_legacy_pattern_fixture_opens_with_its_pattern() { + let l = vectorcraft_engine::cmd::fileio::load("x.ai", legacy_pattern_ai(LEGACY_PATTERN).as_bytes()).unwrap(); + assert_eq!(l.doc.pattern("P").map(|p| p.art.len()), Some(2), "{:?}", l.warnings); + let square = &l.doc.layers[0].children().unwrap()[0]; + assert!(matches!(square.appearance.fill().map(|f| &f.paint), Some(vectorcraft_color::Paint::Pattern { .. }))); +} + +proptest! { + #![proptest_config(config())] + + /// That `.ai` with its pattern's definition damaged (its strings, `@`, `&`, `_`, the list's + /// brackets and its `E`): read, without the pattern where it can't be read whole, or refused. + #[test] + fn ps_form_ai_legacy_pattern_never_panics(cut in 0usize..500, edits in prop::collection::vec((0usize..500, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '\r', '(', ')', '\\', '[', ']', '%', '@', '&', '_', 'E', 'u', 'U', 'q', 'Q', 'm', 'f', 'S', 'k', 'X'])), 0..12)) { + let text = legacy_pattern_ai(&mutate_text(LEGACY_PATTERN, cut, &edits)); + survive("PostScript-form .ai with a damaged version 7 pattern", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; + } +} + /// An operand of a layer's options (`Lb`): a flag, a colour index or component, a percentage, or /// anything else. fn arb_layer_operand() -> impl Strategy { @@ -3906,6 +3940,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 +4154,53 @@ proptest! { survive("hostile editing data in an EPS of its art's box", || vectorcraft_engine::cmd::fileio::load("x.eps", &boxed).ok().map(|l| l.doc))?; } + /// A group with an Effect › Pathfinder style whose dictionary is hostile: any `Command`, keys of + /// any type and value (missing, repeated, unknown, not finite), shown or hidden, the style cut + /// short anywhere; in editing data, an EPS and a `.ai`. A `Command` other than 0 never becomes + /// a live effect. + #[test] + fn ai_pathfinder_styles_never_panic( + command in prop_oneof![(-3i64..16).prop_map(|c| c.to_string()), arb_num()], + keys in prop::collection::vec( + ( + prop::sample::select(vec!["Mix", "Precision", "RemovePoints", "ExtractUnpainted", "ConvertCustom", "TrapTint", "TrapThickness", "Command", "Extra"]), + prop::sample::select(vec!["Int", "Real", "Bool", "String"]), + arb_num(), + ), + 0..16, + ), + hidden in any::(), + 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/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..de12631eba 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -402,7 +402,8 @@ impl<'a> Reader<'a> { /// `(name) x y scaleX scaleY angle reflect axis shear shearAxis [matrix] p` (`P`: the stroke's): /// the pattern swatch `name`, its space taken to art space by the matrix. A pattern this hasn't - /// read can't be drawn. + /// read can't be drawn. For a pattern defined in the version 7 form, the other operands are + /// applied in order before the initial matrix ([`pattern_controls`]). fn pattern_paint(&mut self, w: &str, vals: &[V]) { // In the setup it paints nothing (and the art's space isn't fixed yet). if self.frames.is_empty() { @@ -413,7 +414,16 @@ impl<'a> Reader<'a> { self.unread_pattern(w); return; }; - let matrix = vals.iter().rev().find_map(|v| if let V::Arr(a) = v { paint::affine(&Self::nums(a)) } else { None }); + let mut matrix = vals.iter().rev().find_map(|v| if let V::Arr(a) = v { paint::affine(&Self::nums(a)) } else { None }); + if name.as_ref().is_some_and(|n| self.v7_patterns.contains(n)) { + let controls: Vec = + vals.iter().skip_while(|v| !matches!(v, V::Str(_))).skip(1).take_while(|v| !matches!(v, V::Arr(_))).filter_map(V::num).collect(); + let Some(controls) = pattern_controls(&controls) else { + self.unread_pattern(w); + return; + }; + matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * controls); + } let Some(xf) = pattern_xf(self.space(), matrix, tile) else { self.unread_pattern(w); return; @@ -596,11 +606,14 @@ impl<'a> Reader<'a> { return; } // A style read here: the object, painted as it says. - if let Some(mut appearance) = self - .styles - .get(&style) - .and_then(|st| styled(object, look, st, &StylePaints { gradients: &self.gradients, patterns: &self.pattern_tiles, space })) - { + if let Some(mut appearance) = self.styles.get(&style).and_then(|st| { + styled( + object, + look, + st, + &StylePaints { gradients: &self.gradients, patterns: &self.pattern_tiles, v7_patterns: &self.v7_patterns, space }, + ) + }) { // Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up). let k = space.determinant().abs().sqrt(); if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 { @@ -694,10 +707,33 @@ fn pattern_xf(space: Affine, matrix: Option, 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 +776,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 +785,8 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p if !st.plain || (!slot && !st.simple) || (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty()) + || (st.pathfinder + && (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. }))) { return None; } @@ -778,11 +817,15 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p }; AppearanceItem::Fill(FillLayer::new(paint)) } - StyleItem::Pattern { name, matrix } => match placed.get(&format!("{PATTERN_KEY}{name}")) { + StyleItem::Pattern { name, matrix, controls } => match placed.get(&format!("{PATTERN_KEY}{name}")) { Some(p) => AppearanceItem::Fill(FillLayer::new(p.clone())), None => { let tile = paints.patterns.get(name).copied()?; - let xf = pattern_xf(paints.space, matrix.and_then(|m| paint::affine(&m)), tile)?; + let mut matrix = matrix.and_then(|m| paint::affine(&m)); + if paints.v7_patterns.contains(name) { + matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * pattern_controls(controls)?); + } + let xf = pattern_xf(paints.space, matrix, tile)?; AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: name.clone(), xf })) } }, 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..6b1e8622d0 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}; @@ -525,7 +525,7 @@ fn a_gradient_in_a_patterns_definition_is_placed_from_the_canvas() { /// has that isn't read, where it shows. Its definition costs nothing else. #[test] fn a_pattern_it_cant_read_is_an_error_only_where_it_fills() { - let unread = "%AI3_BeginPattern: (Old)\n(Old) 0 0 8 8 [\n(0 O 0 R 0 g) @\n(\n0 0 m 8 8 L S\n) &\n] E\n%AI3_EndPattern\n\ + let unread = "%AI3_BeginPattern: (Old)\n(Old) 0 0 8 8 [\n(0 O 0 R 0 g) @\n(\n0 0 m 8 8 L frobnicate S\n) &\n] E\n%AI3_EndPattern\n\ %AI3_BeginPattern: (Odd)\n(Odd) 0 0 8 8\n%_U\nE\n%AI3_EndPattern\n%AI3_BeginPattern: (Flat)\n(Flat) 0 0 8 0\n%_0 0 m\n%_8 0 L\n%_S\nE\n%AI3_EndPattern\n"; let s = read_ok(&format!("{unread}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))); assert!(s.doc.patterns.is_empty() && s.doc.swatches.iter().all(|w| !matches!(w.paint, Paint::Pattern { .. }))); @@ -565,6 +565,231 @@ fn a_pattern_painting_with_an_unread_pattern_is_not_kept() { } } +/// A pattern's definition inside another's isn't read, so the outer one isn't kept either. +#[test] +fn a_pattern_with_a_definition_inside_it_isnt_kept() { + let tile = rect_path(0.0, 0.0, 8.0, 8.0).replace('\n', "\n%_"); + let inner = "%AI3_BeginPattern: (In)\n(In) 0 0 1 1\n%_0 0 m\n%_1 1 L\n%_S\nE\n%AI3_EndPattern\n"; + let def = format!("%AI3_BeginPattern: (Out)\n(Out) 0 0 8 8\n{inner}%_{tile}f\nE\n%AI3_EndPattern\n"); + let s = read_ok(&format!("{def}{}", layer(""))); + assert!(s.doc.patterns.is_empty(), "{:?}", s.doc.patterns.iter().map(|p| &p.name).collect::>()); + // 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 +3248,80 @@ fn an_object_with_a_feather_style_comes_in_with_a_live_effect() { assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); } +/// An art style section with style `PF`: an Effect › Pathfinder filter with `Command` `command` +/// and `Mix` `mix` in the object's chain, over a fill and stroke that paint nothing. +fn pathfinder_styles(command: u32, mix: f64) -> String { + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(PF) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Pathfinder) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + 0 /Bool (RemovePoints) ,\n{mix} /Real (Mix) ,\n1 /Bool (ConvertCustom) ,\n{command} /Int (Command) ,\n1 /Real (TrapMaxTint) ,\n\ + 1 /Real (TrapAspect) ,\n0.4 /Real (TrapTint) ,\n0.25 /Real (TrapThickness) ,\n0 /Bool (TrapReverse) ,\n10 /Real (Precision) ,\n\ + (Op) /UnicodeString (DisplayString) ,\n0 /Bool (TrapConvertCustom) ,\n0.05 /Real (TrapTintTolerance) ,\n1 /Bool (ExtractUnpainted) ,\n\ + ; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// A group of a red and a blue square with style `PF`: its drawn look (one path of their area), +/// then the group on `%_` lines. +fn pathfinder_group() -> String { + let hidden = |color: &str, x: f64| format!("{color}{}f\n", rect_path(x, 0.0, x + 10.0, 10.0)).replace('\n', "\n%_"); + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{}U\n1 (PF) XW\n", + rect_path(0.0, 0.0, 15.0, 10.0), + hidden(RED, 0.0), + hidden("0 0 1 0 0 0 1 Xa\n", 5.0) + ) +} + +#[test] +fn a_group_with_a_pathfinder_effect_keeps_its_members_and_the_effect() { + // GUARDS: the style was not read, and the group came in as its drawn look: one path, with no effect. + let r = read_ok(&format!("{}{}", pathfinder_styles(0, 0.5), layer(&pathfinder_group()))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let members = a[0].children().cloned().unwrap_or_default(); + assert_eq!(members.len(), 2, "the squares, not the look: {a:#?}"); + assert!(members.iter().all(|m| matches!(m.kind, NodeKind::Path { .. })), "{members:#?}"); + assert_eq!((fill(&members[0]).color(), fill(&members[1]).color()), (Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0)))); + let effects: Vec<_> = a[0].appearance.effects.iter().map(|e| (e.id.as_str(), e.visible)).collect(); + assert_eq!(effects, [("pathfinder.add", true)]); + assert!(a[0].appearance.items.is_empty(), "{:?}", a[0].appearance); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +#[test] +fn a_pathfinder_style_this_does_not_read_keeps_the_drawn_look() { + // Another command (Intersect, Trap), and a Precision other than the one read. + let other = pathfinder_styles(0, 0.5).replace("10 /Real (Precision)", "5 /Real (Precision)"); + for styles in [pathfinder_styles(1, 0.5), pathfinder_styles(12, 0.5), other] { + let r = read_ok(&format!("{styles}{}", layer(&pathfinder_group()))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let look = a[0].children().cloned().unwrap_or_default(); + assert_eq!(look.len(), 1, "the look's one path: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{:?}", a[0].appearance); + } +} + +#[test] +fn a_path_with_a_pathfinder_effect_keeps_its_drawn_look() { + // Effect › Pathfinder doesn't apply to a lone path: its style stays the drawn look's. + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_{hidden_rect}f\n1 (PF) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let r = read_ok(&format!("{}{}", pathfinder_styles(0, 0.5), layer(&art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "the look, not the path: {a:#?}"); + let mut effects = 0; + r.doc.walk(|n| effects += n.appearance.effects.len()); + assert_eq!(effects, 0); +} + #[test] fn an_object_with_convert_to_shape_comes_in_as_itself_with_the_effect_live() { // GUARDS: `Adobe Shape Effects` wasn't read, so the object came in as its drawn look. 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 6126b4b324..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()))?; @@ -1412,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/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_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/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/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/svg/src/import/prepass.rs b/crates/svg/src/import/prepass.rs index 245392fda3..5a393e79aa 100644 --- a/crates/svg/src/import/prepass.rs +++ b/crates/svg/src/import/prepass.rs @@ -149,7 +149,7 @@ fn named_made_up_ids(xml: &roxmltree::Document) -> HashSet { /// * so do objects with attributes in other applications' namespaces ([`foreign`]); /// * so do `` and `` elements, recorded: usvg makes their arcs into a varying /// number of curves, and they come back as the ellipse VectorCraft draws (not in a file whose -/// style sheet has an `[id` selector); +/// style sheet has an attribute selector); /// * linked files are read ([`files`]); /// * percentage lengths in a `` with a `viewBox` become numbers ([`symbol_units`]); /// * what style sheet rules with a `:not()` set goes in `style` attributes ([`not_rules`]). @@ -164,8 +164,9 @@ pub(super) fn prepass<'s>(svg: &'s str, markers: &str, xml: &roxmltree::Document let not = markers.contains(":not("); let events = SVG_EVENTS.iter().any(|e| markers.contains(e)); let foreign_attrs = markers.contains("xmlns:") && has_foreign_attributes(xml); - // An id would change what a style sheet's `[id]` selector matches: such files keep usvg's curves. - let ellipses = !markers.contains("[id") && [" (Document, Vec) { import_with_report(&svg(body)).unwrap() } +#[test] +fn decoded_id_selectors_do_not_recolor_bare_ellipses() { + for selector in ["circle[id]", "ellipse[id]", "circle[id]", "ellipse[id]", "circle[ id ]", r"ellipse[\69 d]"] { + let source = svg(&format!( + "" + )); + let doc = import(&source).unwrap(); + let actual = render_artboard(&doc); + let expected = resvg_render(&source, 200, 120); + assert_eq!((actual.width, actual.height), (expected.width, expected.height)); + for (x, y) in [(40, 50), (100, 50), (40, 100), (100, 100)] { + let at = 4 * (y * actual.width + x) as usize; + assert_eq!(&actual.rgba[at..at + 4], &expected.rgba[at..at + 4], "{selector}: ({x}, {y})"); + } + } +} + /// All non-layer nodes in paint order. fn art(d: &Document) -> Vec<&Node> { let mut v = Vec::new(); 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/layout.rs b/crates/text/src/layout.rs index 67b5c3c7c7..cbdd41725c 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, @@ -278,7 +332,7 @@ impl Ctx<'_> { // the middle of its own cell, not of its advance (tracking and justification add // space after the cell, and must not push the glyph off the centre line). let em = self.style_at(g.byte).size; - let cell = if g.adv > 0.0 { upright_cell(g) } else { advance }; + let cell = if takes_cell(g) { upright_cell(g) } else { advance }; // A leading space taken off moves it up the column after the turn (moving the // turning point instead would move it across the column too). let turn = Affine::translate((-g.lead, 0.0)) @@ -300,6 +354,29 @@ impl Ctx<'_> { p }; let font_id = g.face.id(); + // Its own width along the baseline: its font advance through its size, scale and the glyph + // scaling `pre` adds. In vertical type, an upright glyph's own length down the column is + // its cell with the Proportional Metrics change to it, and a tate-chu-yoko glyph takes its + // advance, as an inline graphic does. + let upright = self.vertical && g.inline.is_none() && g.tcy.is_none() && takes_cell(g) && stands_upright(g); + let width = if g.inline.is_some() || (self.vertical && g.tcy.is_some()) { + advance + } else if upright { + let proportional = g.vpal.filter(|_| g.face.vertical_glyph(g.gid).is_some()).map_or(0.0, |a| a.advance); + Some(upright_cell(g) + proportional).filter(|w| w.is_finite() && *w > 0.0).unwrap_or(advance) + } else { + let [a, b, ..] = pre.as_coeffs(); + Some(g.face.advance(g.gid) * g.sx * a.hypot(b)).filter(|w| w.is_finite()).unwrap_or(advance) + }; + // Where its own width starts along its advance: the shaper's placement, a leading space + // taken off and right-to-left manual kerning move the glyph along the line. An upright or + // tate-chu-yoko glyph in vertical type starts its cell at the start of its advance. + let width_start = if g.inline.is_none() && !upright && !(self.vertical && g.tcy.is_some()) { + let [a, b, ..] = pre.as_coeffs(); + Some((g.kern_shift + g.dx - g.lead) * a.hypot(b)).filter(|s| s.is_finite()).unwrap_or(0.0) + } else { + 0.0 + }; if let Some(art) = g.inline.as_ref().and_then(|ib| ib.art) { self.out.inlines.push(InlineGlyph { run: g.run, byte: g.byte, glyph: self.out.glyphs.len(), xf: m, bounds: m.transform_rect_bbox(art) }); } @@ -323,6 +400,9 @@ impl Ctx<'_> { bend: None, unturned, pivot, + carets: if g.inline.is_some() { Vec::new() } else { ligature_carets(self.text, g, g.level.is_rtl() && !self.vertical, upright) }, + width, + width_start, }); } 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/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/lib.rs b/crates/text/src/lib.rs index a1b77e02aa..bafaf70af0 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -149,6 +149,25 @@ pub struct PositionedGlyph { /// Font units: `xf * pivot` is the point its Character Rotation turns it about, its pen /// position on the baseline moved by its baseline shift. pub pivot: Point, + /// A ligature (one glyph that alone stands for several characters, grapheme clusters, of the + /// text): the caret stop between each two of them, in logical order, as the byte offset of the + /// later character and how far the caret stands along the glyph's own width ([`Self::width`]) + /// from its logical leading edge, 0 to 1. The font's ligature carets + /// ([`FontFace::ligature_carets`], or [`FontFace::vertical_ligature_carets`] for a glyph + /// standing upright in vertical type) when it lists one for each stop, else the width divided + /// equally among the characters. Empty for any other glyph. + pub carets: Vec<(usize, f64)>, + /// The glyph's own width along its advance in text space: its font advance at its size, + /// Horizontal Scale and glyph scaling, without the tracking, kerning, justification space and + /// kashida that [`Self::advance`] includes after it (to its right in horizontal type). The + /// advance itself in vertical type. + pub width: f64, + /// How far right of the left end of its advance the glyph's own width ([`Self::width`]) starts, + /// in text space: the font's placement of the glyph (`GPOS` x placement), less a leading space + /// taken off, plus the manual kerning of right-to-left text, which moves the glyph right so that + /// the space it adds lies on the glyph's left. 0 for a glyph standing upright or set across the + /// column in vertical type, and for an inline graphic. + pub width_start: f64, } /// How a glyph on a path is bent along it: a point of its pen space (x along its advance from its @@ -167,6 +186,57 @@ pub struct GlyphBend { } impl PositionedGlyph { + /// The glyph's caret stops in logical order: its first byte, its ligature carets + /// ([`Self::carets`]) and its end, each with how far along its own width ([`Self::width`]) from + /// its logical leading edge the caret stands, 0 to 1. + fn width_stops(&self) -> impl Iterator + '_ { + 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/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..3f86a85bdc 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; 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/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/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/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/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/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 dd5977f5a1..7aa338ab45 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -124,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![] } 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/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 b0f8c812b3..572c667e4b 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -47,7 +47,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag}; use crate::corners::{self, CornerDrag, over_widget}; use crate::guides::{PointSnap, Targets, distance_guides, hold_on_path}; -use crate::objects_on_path::{RotateAllDrag, over_rotate_all}; +use crate::objects_on_path::{RotateAllDrag, SpaceDrag, over_rotate_all, over_space}; use crate::pathtype::{self, BracketDrag, over_bracket}; use crate::pie::{self, PieDrag}; use crate::rulerguide::GuideEdit; @@ -107,6 +107,8 @@ enum State { Pie(PieDrag), /// Dragging an Objects on Path group's Rotate All widget. RotateAll(RotateAllDrag), + /// Dragging an Objects on Path group's Space widget. + Space(SpaceDrag), /// Move or rotate a live mirror axis. Mirror(crate::mirror::MirrorDrag), /// Drag a grid repeat's row, column or corner handle or a spacing slider. @@ -150,6 +152,11 @@ pub struct SelectionTool { /// The last hover had Alt held: what it measures depends on what lies under the pointer /// ([`Tool::wants_rehover`]). alt_hover: bool, + /// The text the pointer was loaded with when the button went down: a dropped press loads it + /// again. + loaded_at_press: Option<(NodeId, bool)>, + /// Where the pointer last hovered: the type on a path bracket under it draws thicker. + bracket_hover: Option, } /// What Distance Guides measure the selection to. @@ -556,6 +563,21 @@ impl SelectionTool { }) } + /// On a press, notes the text the pointer is loaded with ([`Self::loaded_at_press`]); a + /// release clears it. + fn note_loaded_at_press(&mut self, kind: PointerKind) { + match kind { + PointerKind::Down => { + self.loaded_at_press = match self.state { + State::Loaded { from, before, .. } => Some((from, before)), + _ => None, + } + } + PointerKind::Up => self.loaded_at_press = None, + _ => {} + } + } + /// The pointer loaded with the text of area type or type on a path `from` ([`State::Loaded`]): /// a press starts placing it, and its release threads it (`text.thread.add`), into a frame put /// `before` `from` or after it. None when `from` can no longer thread: the press is an @@ -622,7 +644,7 @@ impl Tool for SelectionTool { /// E during a marquee drag switches the marquee between the objects it touches and only the /// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or - /// rotation, a marquee, a corner widget, a pie widget, the Rotate All widget, the brackets of type on a path, a mirror + /// rotation, a marquee, a corner widget, a pie widget, the Rotate All or Space widget, the brackets of type on a path, a mirror /// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy /// is left, and the tool waits for the next press. With the pointer loaded with text, Escape /// drops the text. @@ -669,6 +691,18 @@ impl Tool for SelectionTool { if key == ToolKey::Escape { self.guide.cancel() } else { vec![] } } + /// A dropped press is canceled as by Escape, so a dropped press on a port loads no text. With + /// the pointer loaded with text, the press threads nothing and the text stays loaded for the + /// next click, a press on the port that loaded it included. + fn drop_press(&mut self, cx: &ToolContext) -> Vec { + let loaded = self.loaded_at_press.take(); + let out = if matches!(self.state, State::Loaded { press: Some(_), .. }) { vec![] } else { self.key(cx, ToolKey::Escape, Mods::default()) }; + if let Some((from, before)) = loaded { + self.state = State::Loaded { from, before, press: None }; + } + out + } + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { match self.state { State::Marquee { .. } => key == ToolKey::Letter('e'), @@ -683,6 +717,7 @@ impl Tool for SelectionTool { self.hover = None; self.distance = None; self.alt_hover = false; + self.bracket_hover = None; } fn wants_rehover(&self) -> bool { @@ -695,6 +730,7 @@ impl Tool for SelectionTool { State::Corner(c) => c.adjusting(), State::Pie(d) => d.adjusting(), State::RotateAll(d) => d.adjusting(), + State::Space(d) => d.adjusting(), State::Bracket(b) => b.adjusting(), State::Mirror(d) => d.adjusting(), State::GridRepeat(d) => d.adjusting(), @@ -703,7 +739,9 @@ impl Tool for SelectionTool { } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + self.note_loaded_at_press(ev.kind); let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle); + self.bracket_hover = hovering.then_some(ev.pos); self.alt_hover = hovering && ev.mods.alt; self.distance = hovering.then(|| distance_target(cx, ev.pos, ev.mods)).flatten(); if let State::Loaded { from, before, press } = self.state @@ -856,6 +894,15 @@ impl Tool for SelectionTool { self.state = State::Idle; d.finish() } + (PointerKind::Drag, State::Space(mut d)) => { + let out = d.drag(cx, p, m.alt); + self.state = State::Space(d); + out + } + (PointerKind::Up, State::Space(d)) => { + self.state = State::Idle; + d.finish() + } (PointerKind::Drag, State::Bracket(mut b)) => { let out = b.drag(cx, p, m.cmd); self.state = State::Bracket(b); @@ -899,7 +946,9 @@ impl Tool for SelectionTool { } fn overlays(&self, cx: &ToolContext) -> Vec { - let mut o = pathtype::overlays(cx); + // Highlighted only where a press would take the bracket, not a nearer port. + let drag = if let State::Bracket(b) = &self.state { Some(b) } else { None }; + let mut o = pathtype::overlays(cx, self.bracket_hover.filter(|p| over_bracket(cx, *p)), drag); if let Some(source) = cx.isolation.and_then(|id| cx.doc.node(id)).filter(|n| n.name.as_deref() == Some(vectorcraft_doc::shaper::SOURCES)) { for n in source.children().into_iter().flatten() { if let Some(path) = n.path_data() { @@ -912,6 +961,7 @@ impl Tool for SelectionTool { State::Corner(c) => o.extend(c.overlays(cx)), State::Pie(d) => o.extend(d.overlays(cx)), State::RotateAll(d) => o.extend(d.overlays(cx)), + State::Space(d) => o.extend(d.overlays(cx)), State::Loaded { press: Some((start, cur)), .. } => o.push(Overlay::Marquee(Rect::from_points(*start, *cur))), _ => {} } @@ -960,6 +1010,7 @@ impl Tool for SelectionTool { State::Corner(_) => return Cursor::CornerRadius, State::Pie(_) => return Cursor::ArrowHollow, State::RotateAll(_) => return Cursor::Rotate, + State::Space(_) => return Cursor::ArrowHollow, State::Bracket(_) => return Cursor::PathBracket, State::Loaded { .. } => return Cursor::LoadedText, _ => {} @@ -976,6 +1027,9 @@ impl Tool for SelectionTool { if over_rotate_all(cx, p) { return Cursor::Rotate; } + if over_space(cx, p) { + return Cursor::ArrowHollow; + } if over_bracket(cx, p) { return Cursor::PathBracket; } @@ -1314,11 +1368,11 @@ impl SelectionTool { fn press_widgets(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point) -> Option> { // 0. A port of selected area type or type on a path: the pointer takes its text, // to thread on from the out port or back from the in port. - if let Some((from, port)) = crate::text::port_at(cx, p) { + if let Some((from, port)) = crate::text::port_at(cx, p).filter(|_| !over_bracket(cx, p)) { self.state = State::Loaded { from, before: port == crate::text::Port::In, press: None }; return Some(vec![]); } - // 1. Live Corners widgets, pie widgets, the Rotate All widget and type on a path's brackets, then the + // 1. Live Corners widgets, pie widgets, the Rotate All and Space widgets and type on a path's brackets, then the // bounding-box handles of the current selection. if let Some(c) = CornerDrag::hit(cx, ev, false) { self.state = State::Corner(c); @@ -1332,6 +1386,10 @@ impl SelectionTool { self.state = State::RotateAll(d); return Some(vec![]); } + if let Some(d) = SpaceDrag::hit(cx, ev) { + self.state = State::Space(d); + return Some(vec![]); + } if let Some(b) = BracketDrag::hit(cx, ev) { self.state = State::Bracket(b); return Some(vec![]); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 8f6299f06d..6638083aca 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -1871,6 +1871,41 @@ fn escape_drops_the_loaded_text() { assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 30.0, 420.0)), vec![Action::Exec("select.none".into(), json!({}))]); } +/// A dropped press with the pointer loaded with text threads nothing, and the text stays loaded: +/// the next click threads it. A dropped press on the port loads no text. +#[test] +fn a_dropped_press_keeps_the_text_loaded() { + let (d, id, _, port) = overflowing_area_type(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y)); + t.drop_press(&cx); + t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y)); + assert_ne!(t.cursor(&cx, Point::new(30.0, 420.0), Mods::default()), Cursor::LoadedText, "the dropped press loads no text"); + t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y)); + t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y)); + // The engine sends the release after the drop. + t.pointer(&cx, &ev(PointerKind::Down, 20.0, 20.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 90.0)); + assert!(t.drop_press(&cx).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 80.0, 90.0)).is_empty(), "the release threads nothing"); + assert!(!t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Marquee(_))), "the new frame's outline is removed"); + assert_eq!(t.cursor(&cx, Point::new(30.0, 420.0), Mods::default()), Cursor::LoadedText); + // A press on the port that loaded the text puts it down; dropped, it leaves the text loaded. + t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y)); + assert!(t.drop_press(&cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y)); + assert_eq!(t.cursor(&cx, Point::new(30.0, 420.0), Mods::default()), Cursor::LoadedText, "a dropped press on the port"); + t.pointer(&cx, &ev(PointerKind::Down, 30.0, 420.0)); + assert_eq!( + t.pointer(&cx, &ev(PointerKind::Up, 30.0, 420.0)), + vec![Action::Exec("text.thread.add".into(), json!({"from": id.0, "at": [30.0, 420.0]}))] + ); +} + /// [`doc_with_area_type`], its text fitting its frame; where its in and out ports are. fn fitting_area_type() -> (vectorcraft_doc::Document, NodeId, Point, Point) { let (d, id) = doc_with_area_type(); 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/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/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 404eaa81b7..63bb4de7b0 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(), @@ -427,18 +429,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 +526,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 afcd2c37b7..065907b4fb 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; 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/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 499ff8a7e3..0c9462818e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4024,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() }; @@ -6578,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(); @@ -6586,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"); @@ -6597,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, @@ -6605,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"); } @@ -6643,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] @@ -7200,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/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..7f1c6cf039 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(), 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/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/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/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 9b878ba85f..614054f41a 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 Папка @@ -2639,6 +2640,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 Изискване на парола за отваряне на документа diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9534ca7a9f..a0b4e236db 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -628,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 @@ -3917,6 +3918,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 diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 53a3ce1ef7..2a1f0a518d 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 @@ -3339,6 +3340,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… @@ -5986,6 +5989,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}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index e7afe3baf6..b9e6fd7406 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -636,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 @@ -3959,6 +3960,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 @@ -6002,6 +6005,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 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f19aa9edf2..20a0a4dfec 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -586,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 @@ -3679,6 +3680,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 diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index fe96b30fbc..94430d21ee 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 @@ -2666,6 +2667,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 @@ -5587,6 +5590,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 diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2a8c832706..0a7d2be71c 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 Φάκελος @@ -3262,6 +3263,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 Επαναφορά πλαισίου οριοθέτησης @@ -5953,6 +5956,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}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index dedfa88e05..4e5ba28d4e 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 @@ -2709,6 +2710,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 @@ -5944,6 +5947,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}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d31f24261f..c75f15ba54 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -627,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 @@ -3878,6 +3879,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 @@ -6032,6 +6035,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 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3835db6e9c..20b608bb4f 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 @@ -2701,6 +2702,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 @@ -5997,6 +6000,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 diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 683bd329ea..12e8b0ec1f 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 @@ -3235,6 +3236,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… @@ -5986,6 +5989,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ó diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 5973cf3b65..8e4aa69f2f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -586,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 @@ -3679,6 +3680,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 diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d18977cdad..6fd38b0f77 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 @@ -2742,6 +2743,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 @@ -5621,6 +5624,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 diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f0cc99c69a..5096fef13c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -648,6 +648,7 @@ digits Malayalam マラヤーラム数字 Cascade 重ねて表示 Tile 並べて表示 Float in Window ウィンドウを分離 + Float All in Windows すべてをウィンドウに分離 Consolidate All Windows すべてのウィンドウを統合 Workspace ワークスペース Reset Essentials 初期設定をリセット @@ -2727,6 +2728,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… 置換… @@ -5686,6 +5689,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}` が見つかりません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8bcf813ccb..5389e1f093 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -538,6 +538,7 @@ Cascade კასკადად Tile ფილებად Float in Window ცალკე ფანჯარაში გამოტანა + Float All in Windows ყველას ცალკე ფანჯრებში გამოტანა Consolidate All Windows ყველა ფანჯრის გაერთიანება Workspace სამუშაო სივრცე Reset Essentials Essentials-ის ჩამოყრა @@ -3462,6 +3463,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 ყველა დამწერლობა @@ -5990,6 +5993,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}` ვერ მოიძებნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 3031e5fc5a..8596570c74 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -641,6 +641,7 @@ digits Malayalam 말라얄람어 Cascade 계단식 배열 Tile 바둑판식 배열 Float in Window 창에 플로팅 + Float All in Windows 모두 창에 플로팅 Consolidate All Windows 모든 창 통합 Workspace 작업 영역 Reset Essentials Essentials 재설정 @@ -2716,6 +2717,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… 바꾸기… @@ -5582,6 +5585,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}`을 찾을 수 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 9c34aff5ac..4cde5d4036 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -600,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 @@ -3693,6 +3694,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 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index bd65bde99b..52800ade00 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -594,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 @@ -3799,6 +3800,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 @@ -5856,6 +5859,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}` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 576575cf61..8369f4d23f 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 @@ -2257,6 +2258,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… @@ -5918,6 +5921,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 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 03dbb91d54..e6bf3f77ca 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 Папка @@ -2737,6 +2738,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 Требовать пароль для открытия документа @@ -5979,6 +5982,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}` не найден diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 94ed6a29ec..f123510402 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 @@ -2645,6 +2646,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 @@ -6054,6 +6057,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 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 6315c7fc00..b198e1af18 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 @@ -2516,6 +2517,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 @@ -5959,6 +5962,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ı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4a3eabe4d4..d468a63d71 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 Папка @@ -2734,6 +2735,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 Вимагати пароль для відкриття документа @@ -5601,6 +5604,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}` не знайдено diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 9c8c731582..9d4acddcbd 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 @@ -3003,6 +3004,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ế… @@ -5602,6 +5605,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}` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 040c49a7fb..0426b415f8 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 文件夹 @@ -1743,7 +1744,7 @@ file-filter Templates 模板 Lossy: 有损: Low 低 lowercase 小写 - Luminosity 亮度 + Luminosity 明度 LZW Compression LZW 压缩 Mac Mac Magenta 洋红 @@ -2612,6 +2613,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 打开文档时需要密码 @@ -5843,6 +5846,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}` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 5cc7916df0..92a1a98087 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 資料夾 @@ -3594,6 +3595,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 開啟文件時需要密碼 @@ -5639,6 +5642,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}` 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/run.rs b/crates/ui-egui/src/menus/run.rs index 5ba39f237d..b788cd58bb 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -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), 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/tree.rs b/crates/ui-egui/src/menus/tree.rs index d197ee9061..3a55ab37c0 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -612,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..97b7926e83 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", 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/character.rs b/crates/ui-egui/src/panels/character.rs index f1f0707f69..d8e76c8ed6 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"); 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/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/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, + /// 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, @@ -944,6 +953,8 @@ 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(), diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index 680afa6d1a..624c32c7ea 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -203,6 +203,333 @@ 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(); + 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/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/widgets.rs b/crates/ui-egui/src/widgets.rs index e8da10df34..b6b4130b88 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -43,7 +43,7 @@ pub use drag::{ }; #[cfg(test)] use dropdowns::combo_button_id; -pub(crate) use dropdowns::{combo, combo_menu, combo_named}; +pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field, combo_named, popover_is_open}; pub use dropdowns::{ dropdown, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, 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/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/file-format-parity.md b/docs/file-format-parity.md index 92d6f79d22..6f02703ca5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -104,7 +104,9 @@ 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. diff --git a/docs/gaps.md b/docs/gaps.md index dccc4a5193..d226df6b69 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,10 +1,17 @@ # 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 (G15: a compound path's assembled path is kept between frames; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence -**Feature evidence last updated:** 2026-10-22. +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. @@ -20,6 +27,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| | 2026-11-03 | minor | Windows: opt-in direct PDF transport writes the print-ready PDF to a printer's Standard TCP/IP RAW port, for PCL-only drivers that rewrite custom pages (#5339, #4004); TCP framing and ticket-independent submission covered by app tests. No ranked entry closed; 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. | @@ -417,13 +425,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 @@ -593,7 +604,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 @@ -607,6 +620,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 @@ -705,6 +730,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 3d8e999b5c..6878e137b4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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 @@ -1684,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 @@ -2358,7 +2361,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. @@ -3634,11 +3641,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}}} @@ -5469,19 +5495,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. @@ -6012,12 +6058,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 @@ -6032,10 +6088,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":{}}} ``` 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..bf5f67279b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,10 +1,10 @@ # 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 (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence -**Feature evidence last updated:** 2026-10-30. +**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. @@ -97,10 +97,14 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | 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 | | 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,6 +145,8 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 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 | Symbol editing shows draggable 9-slice guides (#5280). Guides outside the artwork remain unsupported. Scores and hours remain 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-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. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3f95343c96..15d40489a6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,10 +1,10 @@ # 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 (font-family fields accept the mouse wheel, #5253; 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. +**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. @@ -130,9 +130,9 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | 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 +144,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 | @@ -405,7 +405,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | 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 | +| 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 | @@ -505,6 +505,7 @@ since 2026-10-01. - **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, 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) ("Change the Character Color, Tint, Weight, and Overprint Fill or Stroke options"; "Set the Figure, Position, Ligatures, Alternates, Ordinals, or Fractions options") and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) ("In the Character Styles or Paragraph Styles panel, select OpenType Features"). - **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`. @@ -525,7 +526,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). @@ -567,7 +572,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. @@ -635,9 +640,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`). @@ -759,6 +764,7 @@ 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)). 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. @@ -840,6 +846,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. @@ -879,12 +886,15 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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, is the font menu of every installed family. 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. @@ -971,7 +981,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. @@ -989,7 +1000,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): "Select a smooth color wheel, a segmented color wheel, or color bars to display and edit colors"). 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. + - **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. @@ -1102,6 +1113,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text (unless `outlineText` already asks for every type object as outlines): a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`). A PDF saved with Illustrator's editing data opens through it as a PDF-compatible `.ai` does, with its layers and groups and with art reaching past its page unclipped; such a PDF holds the data in `AIPDFPrivateData` streams (part of #868). A shape a PDF or `.ai` paints with a gradient (a clip path round a shading) opens as one path filled with the gradient, not a clip group round a rectangle, so Shape Builder, Live Paint and Pathfinder work on its outline (#1304). In a `.ai` opened from its editing data, a text object on a layer that shows and doesn't print stays on that layer, made from the file's text document, even where the page doesn't draw it (`crates/eps/src/import/tests_native.rs`). Such a `.ai` opens without the PDF part's warnings that text was kept as outlines when no outlined glyphs come in, and a warning counts the text objects that hold the page's type next to glyphs the page has only as outlines, which don't come in (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Where the art of a `.ai` or EPS opened from its editing data differs a little from the file's page, the warning gives the share of the page that differs away from type. When that share is 0.2% or less, the warning names the type and gives the share of the page that differs where the type is; when all the type is made from the text document, the type's share has a warning of its own beside the art's (`crates/eps/src/import/tests_native.rs`). + A `.ai` opened from its editing data keeps Effect › Pathfinder on a group with no fills or strokes of its own as a live effect, with the group's members editable: Add, shown or hidden, in its order among the group's effects. The other operations, Pathfinder Options values other than the ones the reader accepts, and the effect on a path, on type, or on a fill or stroke open as the drawn look (`crates/eps/src/import/ai/style.rs`, `pathfinder_effect`). PDF text opens with every glyph where the file draws it (#722): the font's kerning or none, whichever the file followed, word and character spacing, `TJ` adjustments and horizontal scaling kept per character as tracking, text rise as baseline shift within its line, vertical glyphs narrower than an em centred on their column (`/W2`, `/W`, `/DW`), justified text boxes with word spacing back as justified area type (`tests_text_placement`, fixtures written from ISO 32000-1 §9). A `.ai` or PDF whose editing data holds a readable variable library opens with its variable definitions, data-set rows, text, visibility and linked-file values, active row and lock in the Variables panel, whether its layers are read or it comes in as its PDF part; graph values and malformed entries are skipped with a note, and objects aren't bound yet (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data keeps each artboard's center mark, cross hairs, video safe areas and video ruler pixel aspect ratio, and the file's Document Raster Effects Settings; the author comes from the header's `%%For` (the editing data's, else an EPS's own) when the file's File Info gives none, the header's custom colors that no swatch has come in as spot swatches, a named color the file defines takes the place of a default swatch of that name when the file has no palette, and an older file's `%%TemplateBox` places its artboard. A value of another type or out of range keeps its default (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). @@ -1535,6 +1547,8 @@ A double-click on a Repeat (Radial, Grid or Mirror) with the Selection tool ente | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Wheel input over closed font-family fields changes selected text (#5253); public documentation and application choices distinguished; scores and estimates unchanged. | +| 2026-11-03 | minor | SVG imports preserve exported ellipses as four-anchor paths (#5243). Inline graphics use manual kerning (#5245). Symbol editing shows draggable 9-slice guides (#5280). Recolor Artwork offers smooth and segmented wheels and color bars (#5249). Scores and hours remain unchanged. | | 2026-11-01 | minor | Repeat: a double-click isolates it to edit its source art, text included (#5054); evidence added; scores unchanged. | | 2026-11-01 | minor | Live Corners: Up/Down while dragging a corner widget step the corner kind (#2898); evidence added; scores unchanged. | | 2026-11-01 | minor | Shortcuts for Effect menu items (#3296); evidence added; scores unchanged. | diff --git a/docs/type-parity.md b/docs/type-parity.md index 9c0b7d4006..9ecf0f1663 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (the Type tools make area type or type on a path from a clicked path; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -18,6 +18,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Feature | Status | Notes | |---|---|---| +| Mouse wheel over the closed font-family field | done | #5253: Character, Properties and Control step selected text through the family list using saved font filters (excluding search text), one undo step per notch; the style is matched and the list stops at either end. Escape and leaving the field keep the change. Order, bounds and Undo grouping are VectorCraft's choices; scores unchanged. | | Soft return (forced line break, Shift+Enter) | done | Shift+Enter inserts a soft return (U+2028), breaking the line without starting a new paragraph; paragraph spacing (space before/after) and first-line indents apply only at paragraph ends; continuation lines in lists do not repeat the marker; soft return lines in justified text do not spread (#2754) | | Native font-family labels | partial | With Show Font Names in English off, localized legacy names are used when typographic names contain no native label (#2208); loaded-font and catalog-only regressions. Choosing among multiple native languages is unchanged. | | Point, area and type-on-a-path type; vertical variants | done / partial | vertical point, area and path type have initial support; fullwidth `!` / `?` keep the nominal glyph upright when no vertical alternate exists (Unicode Tu); in a non-rectangular area a word too wide for the top lines moves down to the first line that holds it (#1615); Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802); `text.create` and `text.createInPath` take `justify` (#1752); MCP `add_text` forwards `vertical` to both commands; the Type and Vertical Type tools make area type when a closed path's outline is clicked and type on a path when an open one is, with pointers that say which, as the public help describes ([Create text](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html), [Create type on a path](https://web.archive.org/web/20220127090635/https://helpx.adobe.com/illustrator/using/creating-type-path.html)) | @@ -75,6 +76,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | The wheel over Character, Properties and Control font-family fields changes selected text, one undo step per notch (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | The Type and Vertical Type tools make area type in a clicked closed path and type on a path along a clicked open one, with their own pointers; each type tool has its own icon; scores unchanged (estimated) | | 2026-10-31 | minor | Units › East Asian Type acts (#394): Q and Ha (a quarter of a millimetre each) are units that preference offers; scores unchanged | | 2026-11-01 | minor | Glyphs panel (#4908): the character selected with the Type tool (a range's first, else the one before the caret) is highlighted in the grid and scrolled into view when the selection moves to another character; Show › Alternates for Current Selection not yet; scores unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b001155030..ae4eb5626b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,10 +1,10 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Color Effects add-on: Find Nearest Swatch, #4923) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence -**Feature evidence last updated:** 2026-10-22. +**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. @@ -194,6 +194,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| +| Wheel over a closed font-family field in Character, Properties or Control | done | #5253: applies the next or previous family to selected text, one undo step per notch; uses saved font filters, ignores search text and stops at the list's ends. Escape and pointer departure keep the change. Other font-picking menus and modifier-wheel input keep their existing behavior. | | Arrow keys nudge by Keyboard Increment (0.001–1296 pt); Shift ×10; Alt copies | done | | | Fields commit what was typed on a click away or a move to another field, as Enter does; Escape discards it | done | #1787 | | Number fields: Up/Down step, Shift ×10, Cmd/Ctrl ÷10, wheel over a focused field; steps, the wheel and label scrubs stop at the field's bounds (a stroke weight at 0, a miter limit at 1) | done | Shift+arrow in the Stroke weight field doesn't step by 10 (#991); bounds #3370 | @@ -334,7 +335,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Swatch, graphic style and symbol library panels: each library opens in a panel of its own, several at once, that floats, groups, docks and closes like any panel; opening an open library brings its panel forward; Previous / Next Library change the library in place; the panel menu's Persistent reopens the panel at startup with its view and find field (a library loaded from a file is read again; when its file is missing the panel reopens showing the file's path with Locate Library…, and the status bar names the file) | done | #2603; panel ids `library::`, `ui.libraryPanel {panel, library?, view?, showFind?, persistent?}`, `ui.libraryPanel.locate {panel, path?}`; the library panels have no sort option, as before | | DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; native CIRCLE/ARC export and CNC preset remain pending | | macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | -| Preferences: every option acts | partial | 4 stored but unused (#394, audited 2026-10-30): Open Documents As Tabs, Hyphenation › Default Language, Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | +| Preferences: every option acts | partial | 3 stored but unused (#394, audited 2026-10-30): Hyphenation › Default Language, Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | | Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, ); arcs, spirals, flares and Pen paths are not turned | | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | @@ -400,6 +401,8 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | +| 2026-11-03 | minor | Symbol editing draws and drags 9-slice guides on the canvas (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-11-01 | minor | A double-click on a Repeat with the Selection tool enters isolation mode on it, where its source art (type included: a double-click there edits the text) is edited and every copy follows (#5054); scores and estimates unchanged | | 2026-11-01 | minor | Live Corners: while a corner widget is pressed or dragged with the Selection or Direct Selection tool, the Up and Down arrows step the corners' kind (round, inverted round, chamfer) with the radius, as one undo step (#2898); scores and estimates unchanged | | 2026-11-01 | minor | Keyboard Shortcuts: every Effect menu item (Distort & Transform › Transform…, Stylize › Drop Shadow…, …) is listed under its menu path and takes a shortcut of its own, which the menu shows and which opens that effect's dialog (or applies an effect without options) (#3296); scores and estimates unchanged | diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 6e59920624..49341cc1b4 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,12 +5,10 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "92d392cff132eaf53e13afff77f38b5c11b73aa0"; -/// The writer's revision: craft-libs#417, CMYK, gray and spot colors with their exact inks. -const KRILLA_REV: &str = "fb08be5fa19eee8d37e624397fcdc96df6035e92"; +const REV: &str = "f8f8829cc7be65d466d687dae381d1ca60e31242"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), - ("krilla", "0.8.2", KRILLA_REV), + ("krilla", "0.8.2", REV), ("hayro-syntax", "0.7.2", REV), ("hayro-interpret", "0.7.0", REV), ("hayro-jbig2", "0.3.0", REV), @@ -34,7 +32,7 @@ pub fn run(root: &Path) -> Result<(), String> { } let metadata: Value = serde_json::from_slice(&output.stdout).map_err(|e| format!("cargo metadata: {e}"))?; validate(&metadata)?; - println!("PDF: shared crate and patched backends resolve once to {REV} (krilla to {KRILLA_REV})"); + println!("PDF: shared crate and patched backends resolve once to {REV}"); Ok(()) } @@ -94,7 +92,7 @@ mod tests { ("source", Value::Null), ("source", json!("registry+https://github.com/rust-lang/crates.io-index")), ("source", json!("git+https://github.com/storytold/craft-libs?branch=main#other")), - ("source", json!(source(if PACKAGES[index].2 == REV { KRILLA_REV } else { REV }))), + ("source", json!(source("92d392cff132eaf53e13afff77f38b5c11b73aa0"))), ("version", json!("0.99.0")), ] { let mut m = metadata();