diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index d60a898fd1..507caffe10 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1398097510, "producer_workflow_id": 430275079, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "signer_tooling_revision": "main", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 3b79c61ba5..6cc6f885a2 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,12 +34,26 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: main app-name: vectorcraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} + secrets: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} + AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} + AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} # No secrets: inherit or raw platform values in this caller. Only the isolated native # callee job may bind the release environment and export its keys; that environment must # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 989d6974dd..0e963e43e1 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: main app-name: vectorcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 @@ -32,3 +32,4 @@ jobs: # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, # #369 and #364). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' + linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]' diff --git a/Cargo.lock b/Cargo.lock index 1f22f325e8..cec7a3e5df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -613,6 +613,19 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "blake3" +version = "1.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64c0e36294adc8db531500e3f2b8ec75c4af9177271e9c6d33f93609d56e57cd" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures 0.3.1", +] + [[package]] name = "block" version = "0.1.6" @@ -1106,6 +1119,15 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "constant_time_eq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] + [[package]] name = "cookie-factory" version = "0.3.3" @@ -1217,7 +1239,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-automation", "craft-behavior", @@ -1258,7 +1280,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "crc32fast", "flate2", @@ -1269,7 +1291,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1280,7 +1302,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "rustix 1.1.6", ] @@ -1288,7 +1310,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1313,7 +1335,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1331,7 +1353,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-docpath", @@ -1349,7 +1371,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "crc32fast", "flate2", @@ -1358,7 +1380,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "egui", ] @@ -1366,7 +1388,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "md-5", "rayon", @@ -1375,12 +1397,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-cms", @@ -1400,11 +1422,10 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-control-protocol", "craft-platform", - "getrandom 0.3.4", "serde", "serde_json", ] @@ -1412,8 +1433,9 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ + "getrandom 0.3.4", "serde_json", "subtle", ] @@ -1421,7 +1443,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "rayon", ] @@ -1429,7 +1451,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1452,10 +1474,26 @@ dependencies = [ "zbus", ] +[[package]] +name = "craft-doc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +dependencies = [ + "blake3", + "craft-ecproj-format", + "craft-pcraft-format", + "craft-vectorcraft-format", + "flate2", + "ruzstd", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "serde", ] @@ -1463,7 +1501,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1482,7 +1520,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-codepage", "encoding_rs", @@ -1491,15 +1529,25 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-ecproj-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1514,7 +1562,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1533,7 +1581,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1542,7 +1590,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "cap-primitives", "craft-atomic", @@ -1565,12 +1613,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "gif", ] @@ -1578,7 +1626,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "flate2", ] @@ -1586,7 +1634,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1599,7 +1647,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "chrono", "fixed_decimal", @@ -1627,7 +1675,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-dds", "craft-jpeg", @@ -1654,7 +1702,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1672,7 +1720,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "thiserror 2.0.21", ] @@ -1680,7 +1728,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1691,7 +1739,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-host", "craft-i18n", @@ -1706,7 +1754,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-i18n", @@ -1720,7 +1768,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -1738,7 +1786,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1750,7 +1798,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "encoding_rs", "image", @@ -1761,7 +1809,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "chrono", "craft-codepage", @@ -1771,7 +1819,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-keymap", @@ -1784,10 +1832,21 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-pcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +dependencies = [ + "flate2", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1799,7 +1858,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "async-channel", "async-io", @@ -1830,7 +1889,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1839,7 +1898,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -1863,7 +1922,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1874,7 +1933,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-eps", "flate2", @@ -1888,7 +1947,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "encoding_rs", "flate2", @@ -1899,7 +1958,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "dispatch2", "egui", @@ -1912,7 +1971,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1931,7 +1990,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-atomic", "craft-host", @@ -1948,7 +2007,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "fax", "hayro-ccitt", @@ -1959,7 +2018,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1980,7 +2039,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-keymap", @@ -1992,7 +2051,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2017,7 +2076,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2032,7 +2091,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-atomic", "craft-behavior", @@ -2047,7 +2106,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "serde", "thiserror 2.0.21", @@ -2057,7 +2116,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "serde", "thiserror 2.0.21", @@ -2066,7 +2125,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-keymap", @@ -2081,12 +2140,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2100,7 +2159,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-i18n", @@ -2116,7 +2175,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "accesskit", "craft-behavior", @@ -2154,7 +2213,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2165,7 +2224,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -2183,7 +2242,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -2204,7 +2263,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -2225,7 +2284,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -2244,7 +2303,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "base64 0.22.1", "chrono", @@ -2276,7 +2335,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "flate2", "serde", @@ -2287,7 +2346,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2297,7 +2356,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "js-sys", "serde_json", @@ -2308,7 +2367,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "winsafe", ] @@ -2316,7 +2375,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-appkit", "craft-atomic", @@ -2348,7 +2407,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3703,7 +3762,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "brotli", "hayro-postscript", @@ -3712,7 +3771,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3730,7 +3789,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3748,12 +3807,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "flate2", "hayro-ccitt", @@ -4736,7 +4795,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4893,7 +4952,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -8600,6 +8659,7 @@ dependencies = [ "proptest", "serde", "serde_json", + "sha2 0.10.9", "thiserror 2.0.21", "tiff", "vectorcraft-color", @@ -8637,6 +8697,7 @@ dependencies = [ "chrono", "craft-cdr", "craft-codepage", + "craft-doc", "craft-docpath", "craft-font-catalog", "craft-font-store", @@ -8904,6 +8965,7 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-geom 0.24.1", "vectorcraft-js", + "vectorcraft-plugins", "wasmi", "wasmparser 0.228.0", "wat", @@ -9033,6 +9095,15 @@ dependencies = [ "vectorcraft-pathops 0.24.1", ] +[[package]] +name = "vectorcraft-thumbnail-handler" +version = "0.24.1" +dependencies = [ + "png 0.18.1", + "windows", + "windows-core", +] + [[package]] name = "vectorcraft-tools" version = "0.24.1" diff --git a/Cargo.toml b/Cargo.toml index de98dd834b..3944e46dc8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,47 +11,49 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # 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 = "51fcc3b0413af193db952df28dffae2321745703" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -194,13 +196,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } diff --git a/ROADMAP.md b/ROADMAP.md index abd6bea6bf..d40c33e9e1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -174,6 +174,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged. +- 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 3064392942..c01f84edd9 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -7,6 +7,7 @@ //! vectorcraft-cli commands //! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] //! vectorcraft-cli info FILE +//! vectorcraft-cli thumbnail [--size 256] IN OUT //! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5] //! vectorcraft-cli perf [--paths 50000] [--deep] //! ``` @@ -145,6 +146,15 @@ USAGE: read from its preview and why), title, colour mode, units, artboards, object counts by kind, fonts. + vectorcraft-cli thumbnail [--size N] IN OUT + Open IN (any readable format) and write OUT as a PNG of its first artboard (else the art), + N pixels on its longer side (1 to 1024, default 256), with a transparent background. Linux + file managers run it for .vectorcraft, .drawcraft and .vctemplate files through + share/thumbnailers/ai.storyteller.vectorcraft.thumbnailer, and the Windows thumbnail + handler (vectorcraft_thumbnail_handler.dll) runs it for Explorer. It exits with an error + and writes nothing when IN is larger than 256 MiB, can't be opened, shows nothing, or takes + longer than 20 seconds. + vectorcraft-cli bench FILE [--size WxH] [--iters N] Render FILE (any readable format) fitted to WxH (default 2880x1800) and print ms per frame (warm), multithreaded and single-threaded. @@ -220,6 +230,7 @@ fn main() -> ExitCode { Some("commands") => commands(), Some("convert") => convert(&args[1..]), Some("info") => info(&args[1..]), + Some("thumbnail") => thumbnail(&args[1..]), Some("bench") => bench(&args[1..]), Some("perf") => perf::run(&args[1..]), Some("-h" | "--help" | "help") | None => help(), @@ -524,6 +535,83 @@ fn info(args: &[String]) -> Result<(), String> { Ok(()) } +/// Largest file `thumbnail` opens, in bytes on disk. +const THUMBNAIL_MAX_FILE: u64 = 256 << 20; +/// Largest `--size` of `thumbnail`: the thumbnail standard's largest size, xx-large. +const THUMBNAIL_MAX_SIZE: u32 = 1024; +/// `--size` when it isn't given: the thumbnail standard's large size. +const THUMBNAIL_DEFAULT_SIZE: u32 = 256; +/// Longest `thumbnail` runs before it exits without writing OUT. +const THUMBNAIL_TIME: std::time::Duration = std::time::Duration::from_secs(20); + +/// `thumbnail`: the PNG a Linux file manager shows for a document, run through the +/// `.thumbnailer` entry in `packaging/linux` +/// (), and the +/// picture the Windows thumbnail handler (`apps/vectorcraft-thumbnail-handler`) gives Explorer. +fn thumbnail(args: &[String]) -> Result<(), String> { + if help_requested(args, &["--size", "-s"]) { + return help(); + } + let mut files = vec![]; + let mut size = THUMBNAIL_DEFAULT_SIZE; + let mut it = args.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--size" | "-s" => { + size = it + .next() + .and_then(|v| v.parse().ok()) + .filter(|n| (1..=THUMBNAIL_MAX_SIZE).contains(n)) + .ok_or_else(|| format!("--size needs a number of pixels from 1 to {THUMBNAIL_MAX_SIZE}"))?; + } + other if other.starts_with('-') => return Err(format!("unknown thumbnail option `{other}`")), + f => files.push(f), + } + } + let [input, output] = <[&str; 2]>::try_from(files).map_err(|_| "thumbnail needs IN and OUT")?; + // The process ends when the time is up, wherever the work is: OUT is written whole or not at all. + std::thread::spawn(|| { + std::thread::sleep(THUMBNAIL_TIME); + eprintln!("vectorcraft-cli: thumbnail: took longer than {} seconds", THUMBNAIL_TIME.as_secs()); + std::process::exit(1); + }); + let len = std::fs::metadata(input).map_err(|e| format!("{input}: {e}"))?.len(); + if len > THUMBNAIL_MAX_FILE { + return Err(format!("{input}: larger than {} MiB", THUMBNAIL_MAX_FILE >> 20)); + } + // Opened as the app opens it: the fonts it carries, its type measured, its linked files read. + let mut h = Headless::new(); + h.call("app.open", json!({"path": input})).map_err(|e| format!("{input}: {e}"))?; + let doc = &h.session.doc().map_err(|e| e.to_string())?.doc; + // A picture without a visible pixel is an error, and the file manager keeps the file's icon. + let img = vectorcraft_render::encode::first_artboard(doc, size) + .filter(|img| img.pixels.as_chunks::<4>().0.iter().any(|px| px[3] != 0)) + .ok_or_else(|| format!("{input}: the document shows nothing"))?; + let png = img.to_png().map_err(|e| format!("{input}: {e}"))?; + write_whole(Path::new(output), &png, |tmp, out| std::fs::rename(tmp, out)).map_err(|e| format!("{output}: {e}")) +} + +/// Writes `bytes` to a temporary file beside `out` and moves it over `out` with `rename`. When the +/// temporary file can't be written or `rename` fails, this returns the error, removes the temporary +/// file and leaves `out` unchanged; it never copies into `out`. +fn write_whole(out: &Path, bytes: &[u8], rename: impl FnOnce(&Path, &Path) -> std::io::Result<()>) -> std::io::Result<()> { + let name = out.file_name().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a file name"))?; + let mut tmp_name = std::ffi::OsString::from("."); + tmp_name.push(name); + tmp_name.push(format!(".{}.tmp", std::process::id())); + let tmp = out.with_file_name(tmp_name); + // A file already at `tmp` is not this run's: the error leaves it in place. + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?; + let written = f.write_all(bytes).and_then(|()| vectorcraft_format::sync_file(&f)); + drop(f); + let written = written.and_then(|()| rename(&tmp, out)); + if written.is_err() { + // Best effort: the temporary file is all there is to clean up. + let _ = std::fs::remove_file(&tmp); + } + written +} + enum Step { Cmd(String, Value), Export(String), @@ -773,3 +861,41 @@ fn bench(args: &[String]) -> Result<(), String> { } Ok(()) } + +#[cfg(test)] +mod write_whole_tests { + use super::write_whole; + + #[test] + fn a_failed_rename_leaves_out_unchanged_and_no_temporary_file() { + let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}")); + let out = dir.path().join("out.png"); + std::fs::write(&out, b"old").unwrap_or_else(|e| panic!("{e}")); + let refused = write_whole(&out, b"new picture", |_, _| Err(std::io::Error::other("refused"))); + assert!(refused.is_err()); + assert_eq!(std::fs::read(&out).unwrap_or_else(|e| panic!("{e}")), b"old"); + let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap_or_else(|e| panic!("{e}")).flatten().map(|e| e.file_name()).collect(); + assert_eq!(names, ["out.png"]); + } + + #[test] + fn a_file_already_at_the_temporary_name_is_kept() { + let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}")); + let out = dir.path().join("out.png"); + let tmp = dir.path().join(format!(".out.png.{}.tmp", std::process::id())); + std::fs::write(&tmp, b"someone else's").unwrap_or_else(|e| panic!("{e}")); + assert!(write_whole(&out, b"new picture", |tmp, out| std::fs::rename(tmp, out)).is_err()); + assert_eq!(std::fs::read(&tmp).unwrap_or_else(|e| panic!("{e}")), b"someone else's"); + assert!(!out.exists()); + } + + #[test] + fn a_rename_replaces_out() { + let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}")); + let out = dir.path().join("out.png"); + std::fs::write(&out, b"old").unwrap_or_else(|e| panic!("{e}")); + write_whole(&out, b"new picture", |tmp, out| std::fs::rename(tmp, out)).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(std::fs::read(&out).unwrap_or_else(|e| panic!("{e}")), b"new picture"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap_or_else(|e| panic!("{e}")).count(), 1); + } +} diff --git a/apps/vectorcraft-cli/tests/it/main.rs b/apps/vectorcraft-cli/tests/it/main.rs index d898dda20a..a820d4f7b4 100644 --- a/apps/vectorcraft-cli/tests/it/main.rs +++ b/apps/vectorcraft-cli/tests/it/main.rs @@ -6,6 +6,7 @@ mod cli; mod fileio; mod mcp_e2e; mod script; +mod thumbnail; /// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner. fn bin() -> std::path::PathBuf { diff --git a/apps/vectorcraft-cli/tests/it/thumbnail.rs b/apps/vectorcraft-cli/tests/it/thumbnail.rs new file mode 100644 index 0000000000..b75d99b158 --- /dev/null +++ b/apps/vectorcraft-cli/tests/it/thumbnail.rs @@ -0,0 +1,162 @@ +//! `thumbnail` and the Linux `.thumbnailer` entry that runs it for file managers. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const THUMBNAILER: &str = include_str!("../../../../packaging/linux/ai.storyteller.vectorcraft.thumbnailer"); +const MIME: &str = include_str!("../../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml"); +const PACKAGE: &str = include_str!("../../../../packaging/linux/package.sh"); + +/// Returns a new empty folder in the temp folder, removed with everything in it when the guard drops. +fn tmp() -> tempfile::TempDir { + tempfile::tempdir().unwrap() +} + +fn cli(args: &[&str]) -> Output { + Command::new(crate::bin()).args(args).output().unwrap() +} + +/// Saves a `width`×`height` document with a rectangle on its artboard as `name` in `dir` and returns its path. +fn document(dir: &Path, name: &str, width: u32, height: u32) -> PathBuf { + save(dir, name, width, height, &["--cmd", "shape.rectangle", "--params", r#"{"x":10,"y":10,"width":40,"height":20}"#]) +} + +/// Saves a new `width`×`height` document as `name` in `dir` after the `run` arguments `steps`. +fn save(dir: &Path, name: &str, width: u32, height: u32, steps: &[&str]) -> PathBuf { + let path = dir.join(name); + let size = format!(r#"{{"width":{width},"height":{height}}}"#); + let mut args = vec!["run", "--cmd", "file.new", "--params", &size]; + args.extend_from_slice(steps); + args.extend(["--export", path.to_str().unwrap()]); + let out = cli(&args); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + path +} + +/// The width and height in a PNG's IHDR chunk, after checking that it is the 8-bit, non-interlaced +/// RGBA a thumbnail must be (). +fn png_size(png: &[u8]) -> (u32, u32) { + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n") && &png[12..16] == b"IHDR", "not a PNG"); + assert_eq!((png[24], png[25], png[28]), (8, 6, 0), "bit depth, color type (RGBA) and interlacing"); + let be = |b: &[u8]| u32::from_be_bytes([b[0], b[1], b[2], b[3]]); + (be(&png[16..20]), be(&png[20..24])) +} + +/// The value of `key` in the entry's `[Thumbnailer Entry]` group. +fn entry(key: &str) -> &'static str { + assert_eq!(THUMBNAILER.lines().next(), Some("[Thumbnailer Entry]")); + THUMBNAILER.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).unwrap_or_else(|| panic!("no {key} key")) +} + +/// The file manager's command for the entry: `Exec` split at spaces, `%s` the size, `%i` the +/// input path and `%o` the output path (the codes the thumbnail factories expand). +fn exec(size: u32, input: &Path, output: &Path) -> Vec { + entry("Exec") + .split(' ') + .map(|arg| match arg { + "%s" => size.to_string(), + "%i" => input.to_string_lossy().into_owned(), + "%o" => output.to_string_lossy().into_owned(), + other => { + assert!(!other.contains('%'), "a field code the CLI doesn't take: {other}"); + other.to_string() + } + }) + .collect() +} + +/// The entry runs the CLI with the size, the document and the PNG to write, as a file manager +/// does: with no environment, and the PNG is the first artboard at that size, drawn by the +/// renderer that embeds a native file's preview. +#[test] +fn the_thumbnailer_entry_writes_the_first_artboard() { + let dir = tmp(); + let doc = document(dir.path(), "wide.vectorcraft", 200, 100); + let out = dir.path().join("wide.png"); + let command = exec(128, &doc, &out); + assert_eq!(command[0], entry("TryExec")); + assert_eq!(command[0], "vectorcraft-cli"); + let run = Command::new(crate::bin()).args(&command[1..]).env_clear().output().unwrap(); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + let png = std::fs::read(&out).unwrap(); + assert_eq!(png_size(&png), (128, 64)); + let saved = vectorcraft_format::load(&std::fs::read(&doc).unwrap()).unwrap(); + assert_eq!(Some(png), vectorcraft_render::encode::first_artboard_png(&saved, 128).unwrap(), "the renderer's picture"); +} + +/// Each type the entry lists is a native document type the app's MIME package declares, and the +/// packages install the entry where the thumbnail factories look. +#[test] +fn the_thumbnailer_entry_covers_the_native_types() { + let types: Vec<&str> = entry("MimeType").split(';').filter(|t| !t.is_empty()).collect(); + assert_eq!(types, ["application/x-vectorcraft", "application/x-vectorcraft-template"]); + for t in types { + assert!(MIME.contains(&format!("")), "the MIME package doesn't declare {t}"); + } + assert!( + PACKAGE.contains(r#"install -Dm644 "$HERE/$APP_ID.thumbnailer" "$STAGE/usr/share/thumbnailers/$APP_ID.thumbnailer""#), + "package.sh doesn't install the entry" + ); +} + +/// The size defaults to 256 pixels on the longer side, and a tall artboard is fitted by its height. +#[test] +fn thumbnail_fits_the_longer_side() { + let dir = tmp(); + let doc = document(dir.path(), "tall.vectorcraft", 100, 400); + let out = dir.path().join("tall.png"); + let run = cli(&["thumbnail", doc.to_str().unwrap(), out.to_str().unwrap()]); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + assert_eq!(png_size(&std::fs::read(&out).unwrap()), (64, 256)); +} + +/// A size outside 1 to 1024 pixels, a missing file name and an unknown option are errors, and no +/// PNG is written. +#[test] +fn thumbnail_refuses_bad_arguments() { + let dir = tmp(); + let doc = document(dir.path(), "args.vectorcraft", 100, 100); + let out = dir.path().join("args.png"); + let (d, o) = (doc.to_str().unwrap(), out.to_str().unwrap()); + for (args, says) in [ + (vec!["thumbnail", "--size", "0", d, o], "--size"), + (vec!["thumbnail", "--size", "1025", d, o], "--size"), + (vec!["thumbnail", "--size", "big", d, o], "--size"), + (vec!["thumbnail", "--size"], "--size"), + (vec!["thumbnail", d], "IN and OUT"), + (vec!["thumbnail", "--quality", "9", d, o], "--quality"), + ] { + let run = cli(&args); + assert!(!run.status.success(), "{args:?}"); + assert!(String::from_utf8_lossy(&run.stderr).contains(says), "{args:?}: {}", String::from_utf8_lossy(&run.stderr)); + assert!(!out.exists(), "{args:?} wrote a PNG"); + } +} + +/// A file that isn't a document, a damaged one, one larger than the CLI opens, a missing one and +/// an empty document get an error and no PNG, so the file manager shows the file's icon. +#[test] +fn thumbnail_writes_nothing_for_files_it_cannot_read() { + let dir = tmp(); + let text = dir.path().join("notes.vectorcraft"); + std::fs::write(&text, b"not a document").unwrap(); + let saved = std::fs::read(document(dir.path(), "whole.vectorcraft", 100, 100)).unwrap(); + let damaged = dir.path().join("damaged.vectorcraft"); + std::fs::write(&damaged, &saved[..saved.len() / 2]).unwrap(); + // Sparse where the file system allows it: its size is checked before anything is read. + let large = dir.path().join("large.vectorcraft"); + std::fs::File::create(&large).unwrap().set_len((256 << 20) + 1).unwrap(); + let missing = dir.path().join("missing.vectorcraft"); + let empty = save(dir.path(), "empty.vectorcraft", 100, 100, &[]); + for (input, says) in + [(&text, None), (&damaged, None), (&large, Some("larger than 256 MiB")), (&missing, None), (&empty, Some("the document shows nothing"))] + { + let out = dir.path().join("unreadable.png"); + let run = cli(&["thumbnail", input.to_str().unwrap(), out.to_str().unwrap()]); + assert!(!run.status.success(), "{input:?}"); + let err = String::from_utf8_lossy(&run.stderr); + assert!(err.contains(input.to_str().unwrap()), "{input:?}: {err}"); + assert!(says.is_none_or(|s| err.contains(s)), "{input:?}: {err}"); + assert!(!out.exists(), "{input:?} wrote a PNG"); + } +} diff --git a/apps/vectorcraft-thumbnail-handler/Cargo.toml b/apps/vectorcraft-thumbnail-handler/Cargo.toml new file mode 100644 index 0000000000..af502bd751 --- /dev/null +++ b/apps/vectorcraft-thumbnail-handler/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "vectorcraft-thumbnail-handler" +description = "Windows Explorer thumbnail handler for VectorCraft documents and templates" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[lints] +workspace = true + +# A COM server DLL that Explorer loads; on other systems it builds the parts the tests check. +[lib] +crate-type = ["cdylib"] + +# PNG decoding of the picture `vectorcraft-cli thumbnail` writes. MIT OR Apache-2.0. +[dependencies] +png = "0.18" + +# IThumbnailProvider, IInitializeWithStream, the class factory, DIB sections and the registry. +# MIT OR Apache-2.0. +[target.'cfg(windows)'.dependencies] +windows = { version = "0.62", features = [ + "Win32_Foundation", + "Win32_Graphics_Gdi", + "Win32_System_Com", + "Win32_System_LibraryLoader", + "Win32_System_Registry", + "Win32_System_SystemServices", + "Win32_UI_Shell", + "Win32_UI_Shell_PropertiesSystem", +] } +windows-core = "0.62" diff --git a/apps/vectorcraft-thumbnail-handler/src/com.rs b/apps/vectorcraft-thumbnail-handler/src/com.rs new file mode 100644 index 0000000000..ebd421060d --- /dev/null +++ b/apps/vectorcraft-thumbnail-handler/src/com.rs @@ -0,0 +1,345 @@ +//! The COM server: the thumbnail provider, its class factory and the functions the DLL exports +//! (`DllGetClassObject`, `DllCanUnloadNow`, `DllRegisterServer` and `DllUnregisterServer`). +//! +//! COM, GDI and the registry are C APIs with no safe binding, hence the scoped `unsafe_code` +//! allowance. +#![allow(unsafe_code)] + +use std::ffi::c_void; +use std::io::{self, Read}; +use std::os::windows::ffi::OsStringExt; +use std::panic::AssertUnwindSafe; +use std::path::PathBuf; +use std::ptr::null_mut; +use std::sync::Mutex; +use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; + +use windows::Win32::Foundation::{ + CLASS_E_CLASSNOTAVAILABLE, CLASS_E_NOAGGREGATION, E_FAIL, E_POINTER, ERROR_ALREADY_INITIALIZED, ERROR_FILE_NOT_FOUND, HINSTANCE, HMODULE, + S_FALSE, S_OK, +}; +use windows::Win32::Graphics::Gdi::{BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateDIBSection, DIB_RGB_COLORS, DeleteObject, HBITMAP}; +use windows::Win32::System::Com::{CoTaskMemFree, IClassFactory, IClassFactory_Impl, IStream}; +use windows::Win32::System::LibraryLoader::GetModuleFileNameW; +use windows::Win32::System::Registry::{HKEY_CURRENT_USER, REG_SZ, RRF_RT_REG_SZ, RegDeleteTreeW, RegGetValueW, RegSetKeyValueW}; +use windows::Win32::System::SystemServices::DLL_PROCESS_ATTACH; +use windows::Win32::UI::Shell::PropertiesSystem::{IInitializeWithStream, IInitializeWithStream_Impl}; +use windows::Win32::UI::Shell::{ + FOLDERID_LocalAppDataLow, IThumbnailProvider, IThumbnailProvider_Impl, KNOWN_FOLDER_FLAG, SHCNE_ASSOCCHANGED, SHCNF_IDLIST, SHChangeNotify, + SHGetKnownFolderPath, WTS_ALPHATYPE, WTSAT_ARGB, +}; +use windows::core::{BOOL, Error, GUID, HRESULT, HSTRING, IUnknown, Interface, PCWSTR, Ref, Result, implement}; + +use crate::{CLI, CLSID_VALUE, DEADLINE, Document, MAX_FILE, Picture, RegistryValue}; + +/// The handler's class id ([`crate::CLSID`]). +const CLASS_ID: GUID = GUID::from_u128(CLSID_VALUE); +/// The registry key the values of [`crate::registry_values`] go under. +const CLASSES: &str = "Software\\Classes"; +/// The longest DLL path read, in UTF-16 units (Windows' own limit). +const MAX_PATH: usize = 32_767; + +/// The DLL's module handle, from `DllMain`. +static MODULE: AtomicPtr = AtomicPtr::new(null_mut()); +/// Providers and class factories alive plus `LockServer` locks held; the DLL can be unloaded at 0. +static LIVE: AtomicUsize = AtomicUsize::new(0); + +/// The thumbnail provider: Explorer hands it the file's stream, then asks for the picture. +#[implement(IInitializeWithStream, IThumbnailProvider)] +struct Provider { + document: Mutex>>, +} + +impl Provider { + fn new() -> Self { + LIVE.fetch_add(1, Ordering::SeqCst); + Self { document: Mutex::new(None) } + } +} + +impl Drop for Provider { + fn drop(&mut self) { + LIVE.fetch_sub(1, Ordering::SeqCst); + } +} + +impl IInitializeWithStream_Impl for Provider_Impl { + fn Initialize(&self, stream: Ref, _mode: u32) -> Result<()> { + let stream = stream.ok()?.clone(); + let mut slot = self.document.lock().map_err(|_| Error::from(E_FAIL))?; + if slot.is_some() { + return Err(ERROR_ALREADY_INITIALIZED.to_hresult().into()); + } + *slot = Some(Document::new(StreamReader(stream))); + Ok(()) + } +} + +impl IThumbnailProvider_Impl for Provider_Impl { + fn GetThumbnail(&self, cx: u32, bitmap: *mut HBITMAP, alpha: *mut WTS_ALPHATYPE) -> Result<()> { + if bitmap.is_null() || alpha.is_null() { + return Err(E_POINTER.into()); + } + let mut slot = self.document.lock().map_err(|_| Error::from(E_FAIL))?; + let document = slot.as_mut().ok_or_else(|| Error::new(E_FAIL, "not initialized"))?; + // A panic must not unwind into Explorer's process. + let picture = match std::panic::catch_unwind(AssertUnwindSafe(|| thumbnail(document, cx))) { + Ok(Ok(picture)) => picture, + Ok(Err(e)) => return Err(Error::new(E_FAIL, e)), + Err(_) => return Err(Error::new(E_FAIL, "the thumbnail could not be made")), + }; + drop(slot); + let made = dib_section(&picture)?; + // SAFETY: both pointers were checked for null above, and Explorer passes them writable. + unsafe { + *bitmap = made; + *alpha = WTSAT_ARGB; + } + Ok(()) + } +} + +/// The class factory COM asks for the provider. +#[implement(IClassFactory)] +struct Factory; + +impl Factory { + fn new() -> Self { + LIVE.fetch_add(1, Ordering::SeqCst); + Self + } +} + +impl Drop for Factory { + fn drop(&mut self) { + LIVE.fetch_sub(1, Ordering::SeqCst); + } +} + +impl IClassFactory_Impl for Factory_Impl { + fn CreateInstance(&self, outer: Ref, iid: *const GUID, object: *mut *mut c_void) -> Result<()> { + if iid.is_null() || object.is_null() { + return Err(E_POINTER.into()); + } + // SAFETY: `object` was checked for null above. + unsafe { *object = null_mut() }; + if !outer.is_null() { + return Err(CLASS_E_NOAGGREGATION.into()); + } + let provider: IUnknown = Provider::new().into(); + // SAFETY: both pointers were checked for null above. + unsafe { provider.query(iid, object) }.ok() + } + + fn LockServer(&self, lock: BOOL) -> Result<()> { + if lock.as_bool() { + LIVE.fetch_add(1, Ordering::SeqCst); + } else { + LIVE.fetch_sub(1, Ordering::SeqCst); + } + Ok(()) + } +} + +/// `IStream` as [`Read`]. +struct StreamReader(IStream); + +impl Read for StreamReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let len = u32::try_from(buf.len()).unwrap_or(u32::MAX); + let mut read = 0u32; + // SAFETY: `buf` holds at least `len` writable bytes, and `read` outlives the call. + unsafe { self.0.Read(buf.as_mut_ptr().cast(), len, Some(&mut read)) }.ok().map_err(io::Error::other)?; + usize::try_from(read).map_err(io::Error::other) + } +} + +/// The picture of `document`, at most `cx` pixels on its longer side. +fn thumbnail(document: &mut Document, cx: u32) -> std::result::Result { + let size = crate::request_size(cx).ok_or("a thumbnail of 0 pixels")?; + let bytes = document.bytes(MAX_FILE).map_err(|e| e.to_string())?; + let dll = module_path()?; + let cli = PathBuf::from(dll).parent().ok_or("the DLL's folder is unknown")?.join(CLI); + let png = crate::render(&cli, bytes, size, &staging_folder(), DEADLINE)?; + crate::picture(&png, size) +} + +/// Creates the thumbnail staging folder in LocalLow, falling back to the temp folder. +fn staging_folder() -> PathBuf { + // SAFETY: the folder ID is valid, and no token means the current user. + let Ok(folder) = (unsafe { SHGetKnownFolderPath(&FOLDERID_LocalAppDataLow, KNOWN_FOLDER_FLAG(0), None) }) else { + return std::env::temp_dir(); + }; + // SAFETY: the call returned a NUL-terminated path allocated by COM; copy it before freeing it. + let path = unsafe { + let path = PathBuf::from(std::ffi::OsString::from_wide(folder.as_wide())); + CoTaskMemFree(Some(folder.0.cast())); + path + }; + let path = path.join("VectorCraft").join("Thumbnails"); + if std::fs::create_dir_all(&path).is_ok() { path } else { std::env::temp_dir() } +} + +/// `picture` as a top-down 32-bit DIB section. +fn dib_section(picture: &Picture) -> Result { + let bad = || Error::new(E_FAIL, "the picture's size is wrong"); + let width = i32::try_from(picture.width).map_err(|_| bad())?; + let height = i32::try_from(picture.height).map_err(|_| bad())?; + let len = usize::try_from(u64::from(picture.width) * u64::from(picture.height) * 4).map_err(|_| bad())?; + if picture.bgra.len() != len { + return Err(bad()); + } + let info = BITMAPINFO { + bmiHeader: BITMAPINFOHEADER { + biSize: size_of::() as u32, + biWidth: width, + // A negative height: the rows go from top to bottom. + biHeight: -height, + biPlanes: 1, + biBitCount: 32, + biCompression: BI_RGB.0, + ..Default::default() + }, + ..Default::default() + }; + let mut bits: *mut c_void = null_mut(); + // SAFETY: `info` describes a 32-bit picture and `bits` outlives the call. + let bitmap = unsafe { CreateDIBSection(None, &info, DIB_RGB_COLORS, &mut bits, None, 0) }?; + if bits.is_null() { + // SAFETY: `bitmap` was just made and nothing else holds it. + unsafe { + let _ = DeleteObject(bitmap.into()); + } + return Err(Error::new(E_FAIL, "the bitmap has no pixels")); + } + // SAFETY: the DIB section holds `width * height * 4` bytes, `len`, and `bgra` holds `len` bytes. + unsafe { std::ptr::copy_nonoverlapping(picture.bgra.as_ptr(), bits.cast::(), len) }; + Ok(bitmap) +} + +/// The path of this DLL. +fn module_path() -> std::result::Result { + let module = HMODULE(MODULE.load(Ordering::SeqCst)); + if module.0.is_null() { + return Err("the DLL's module handle is unknown".into()); + } + let mut buf = vec![0u16; MAX_PATH]; + // SAFETY: `module` is this DLL's handle, which stays valid while the DLL is loaded. + let len = unsafe { GetModuleFileNameW(Some(module), &mut buf) }; + let path = usize::try_from(len).ok().filter(|&n| n > 0 && n < buf.len()).and_then(|n| buf.get(..n)).ok_or("the DLL's path is unknown")?; + String::from_utf16(path).map_err(|e| e.to_string()) +} + +/// Writes `value` under `Software\Classes` of the current user. +fn set(value: &RegistryValue) -> Result<()> { + let key = HSTRING::from(format!("{CLASSES}\\{}", value.key)); + let name = value.name.map(HSTRING::from); + let name = name.as_ref().map_or(PCWSTR::null(), |n| PCWSTR(n.as_ptr())); + let data: Vec = value.data.encode_utf16().chain([0]).collect(); + let bytes = u32::try_from(data.len() * 2).map_err(|_| Error::from(E_FAIL))?; + // SAFETY: `data` holds `bytes` bytes of a NUL-terminated string, and the names outlive the call. + unsafe { RegSetKeyValueW(HKEY_CURRENT_USER, &key, name, REG_SZ.0, Some(data.as_ptr().cast()), bytes) }.ok() +} + +/// The default value of `key` under `Software\Classes` of the current user, when it is a string. +fn default_value(key: &str) -> Option { + let key = HSTRING::from(format!("{CLASSES}\\{key}")); + let mut buf = [0u16; 128]; + let mut bytes = u32::try_from(buf.len() * 2).ok()?; + // SAFETY: `buf` holds `bytes` writable bytes, and `bytes` outlives the call. + unsafe { RegGetValueW(HKEY_CURRENT_USER, &key, PCWSTR::null(), RRF_RT_REG_SZ, None, Some(buf.as_mut_ptr().cast()), Some(&mut bytes)) } + .ok() + .ok()?; + let units = buf.get(..usize::try_from(bytes / 2).ok()?)?; + String::from_utf16(units).ok().map(|s| s.trim_end_matches('\0').to_owned()) +} + +/// Removes `key` under `Software\Classes` of the current user with its subkeys; a key that isn't +/// there is no error. +fn remove(key: &str) -> Result<()> { + let key = HSTRING::from(format!("{CLASSES}\\{key}")); + // SAFETY: `key` outlives the call. + match unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, &key) } { + ERROR_FILE_NOT_FOUND => Ok(()), + e => e.ok(), + } +} + +/// Tells Explorer that file associations changed, so it asks for thumbnails again. +fn associations_changed() { + // SAFETY: SHCNE_ASSOCCHANGED takes no items. + unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, None, None) }; +} + +/// Registers the handler for the current user ([`crate::registry_values`]). +fn register() -> Result<()> { + let dll = module_path().map_err(|e| Error::new(E_FAIL, e))?; + crate::registry_values(&dll).iter().try_for_each(set) +} + +/// Removes the class key and each extension's thumbnail handler key that names this handler. +fn unregister() -> Result<()> { + for ext in crate::EXTENSIONS { + let key = crate::shell_ex_key(ext); + if default_value(&key).is_some_and(|v| crate::names_this_handler(&v)) { + remove(&key)?; + } + } + remove(&crate::class_key()) +} + +/// Keeps the DLL's module handle for [`module_path`]. +#[unsafe(no_mangle)] +extern "system" fn DllMain(module: HINSTANCE, reason: u32, _reserved: *mut c_void) -> BOOL { + if reason == DLL_PROCESS_ATTACH { + MODULE.store(module.0, Ordering::SeqCst); + } + true.into() +} + +/// COM's request for the class factory of class `class`. +/// +/// # Safety +/// +/// `class` and `iid` point to GUIDs and `object` to writable memory for an interface pointer, as +/// COM passes them. +#[unsafe(no_mangle)] +unsafe extern "system" fn DllGetClassObject(class: *const GUID, iid: *const GUID, object: *mut *mut c_void) -> HRESULT { + if class.is_null() || iid.is_null() || object.is_null() { + return E_POINTER; + } + // SAFETY: the caller passes valid pointers, checked for null above. + unsafe { + *object = null_mut(); + if *class != CLASS_ID { + return CLASS_E_CLASSNOTAVAILABLE; + } + let factory: IClassFactory = Factory::new().into(); + factory.query(iid, object) + } +} + +/// Whether COM may unload the DLL: no provider or class factory is alive and no lock is held. +#[unsafe(no_mangle)] +extern "system" fn DllCanUnloadNow() -> HRESULT { + if LIVE.load(Ordering::SeqCst) == 0 { S_OK } else { S_FALSE } +} + +/// `regsvr32`: registers the handler for the current user. +#[unsafe(no_mangle)] +extern "system" fn DllRegisterServer() -> HRESULT { + let result = register(); + if result.is_err() { + let _ = unregister(); + } + associations_changed(); + result.map_or_else(|e| e.code(), |()| S_OK) +} + +/// `regsvr32 /u`: removes the current user's registration. +#[unsafe(no_mangle)] +extern "system" fn DllUnregisterServer() -> HRESULT { + let result = unregister(); + associations_changed(); + result.map_or_else(|e| e.code(), |()| S_OK) +} diff --git a/apps/vectorcraft-thumbnail-handler/src/lib.rs b/apps/vectorcraft-thumbnail-handler/src/lib.rs new file mode 100644 index 0000000000..4633bfa86d --- /dev/null +++ b/apps/vectorcraft-thumbnail-handler/src/lib.rs @@ -0,0 +1,251 @@ +//! Windows: the thumbnail handler that Explorer and the file dialogs run for `.vectorcraft`, +//! `.drawcraft` and `.vctemplate` files. It is a COM server DLL whose class implements +//! `IThumbnailProvider` and `IInitializeWithStream` +//! (, +//! ). +//! +//! Explorer gives the handler the file's bytes as a stream. The handler writes them to a new file +//! in `%USERPROFILE%\AppData\LocalLow\VectorCraft\Thumbnails` (falling back to the temp folder), +//! runs `vectorcraft-cli thumbnail --size N IN OUT` from the DLL's folder on +//! it, and returns the PNG that command writes (the first artboard, else the art, drawn by +//! `vectorcraft_render::encode::first_artboard`) as a 32-bit DIB section with alpha. A file larger +//! than 256 MiB, a document that can't be opened or shows nothing, and a `vectorcraft-cli` run +//! longer than [`DEADLINE`] give Explorer an error, and Explorer shows the file's icon. Rendering +//! runs in the `vectorcraft-cli` process, so a file that makes it fail or hang ends that process. +//! The handler is not given the file's path (`IInitializeWithStream` is the only initialization +//! an isolated handler gets), so a linked image found only relative to the document's folder +//! shows the preview saved with it. +//! +//! `regsvr32 vectorcraft_thumbnail_handler.dll` registers the handler for the current user, and +//! `regsvr32 /u` removes it ([`registry_values`]). The COM parts build on Windows only; the parts +//! in this file build everywhere and their tests run on every system. + +use std::ffi::OsString; +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +#[cfg(windows)] +mod com; + +#[cfg(test)] +mod tests; + +/// The handler's class id: the key under `CLSID`, and the value of each extension's `ShellEx` key. +pub const CLSID: &str = "{1971F5DA-D761-4655-AB25-6B3825BD1748}"; +/// [`CLSID`] as a number, the form COM compares. +pub const CLSID_VALUE: u128 = 0x1971_f5da_d761_4655_ab25_6b38_25bd_1748; +/// The `ShellEx` subkey that names an extension's thumbnail handler, the interface id of +/// `IThumbnailProvider` (). +pub const THUMBNAIL_SHELL_EX: &str = "{e357fccd-a995-4576-b01f-234630154e96}"; +/// The extensions the handler is registered for: documents, documents under their former +/// extension, and templates (the globs of `packaging/linux/ai.storyteller.vectorcraft.mime.xml`). +pub const EXTENSIONS: &[&str] = &[".vectorcraft", ".drawcraft", ".vctemplate"]; +/// The description in the class key. +pub const DESCRIPTION: &str = "VectorCraft document thumbnail handler"; +/// The largest file the handler reads, in bytes, the limit `vectorcraft-cli thumbnail` applies. +pub const MAX_FILE: u64 = 256 << 20; +/// The largest `--size` `vectorcraft-cli thumbnail` takes. Explorer asks for sizes up to 1024. +pub const MAX_SIDE: u32 = 1024; +/// The largest PNG the handler reads back, in bytes: an uncompressed 1024 by 1024 RGBA picture +/// with room for the chunks around it. +pub const MAX_PNG: u64 = 8 << 20; +/// How long the handler waits for `vectorcraft-cli` before it ends the process: the command's +/// own 20-second limit and 5 seconds to start. +pub const DEADLINE: Duration = Duration::from_secs(25); +/// How often the handler checks whether `vectorcraft-cli` has exited. +const POLL: Duration = Duration::from_millis(10); +/// The program the handler runs, in the DLL's folder. +pub const CLI: &str = "vectorcraft-cli.exe"; + +/// A picture in the layout Explorer takes: rows from top to bottom, 4 bytes per pixel in blue, +/// green, red and alpha order, with the colors premultiplied by alpha. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Picture { + pub width: u32, + pub height: u32, + pub bgra: Vec, +} + +/// One registry value the handler writes, under `Software\Classes` of the current user. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RegistryValue { + /// The key, relative to `Software\Classes`. + pub key: String, + /// The value's name; `None` is the key's default value. + pub name: Option<&'static str>, + /// The string the value holds. + pub data: String, +} + +/// The class key, relative to `Software\Classes`. +pub fn class_key() -> String { + format!("CLSID\\{CLSID}") +} + +/// The key that names `extension`'s thumbnail handler, relative to `Software\Classes`. +pub fn shell_ex_key(extension: &str) -> String { + format!("{extension}\\ShellEx\\{THUMBNAIL_SHELL_EX}") +} + +/// The values that register the handler in the DLL at path `dll`: the class with its server and +/// threading model, and the class as the thumbnail handler of each of [`EXTENSIONS`], as +/// describes. +pub fn registry_values(dll: &str) -> Vec { + let class = class_key(); + let server = format!("{class}\\InprocServer32"); + let mut values = vec![ + RegistryValue { key: class, name: None, data: DESCRIPTION.into() }, + RegistryValue { key: server.clone(), name: None, data: dll.into() }, + RegistryValue { key: server, name: Some("ThreadingModel"), data: "Apartment".into() }, + ]; + values.extend(EXTENSIONS.iter().map(|ext| RegistryValue { key: shell_ex_key(ext), name: None, data: CLSID.into() })); + values +} + +/// Whether `value`, the default value of an extension's `ShellEx` key, names this handler: class +/// ids are compared without regard to letter case. `regsvr32 /u` removes only such keys. +pub fn names_this_handler(value: &str) -> bool { + value.trim().eq_ignore_ascii_case(CLSID) +} + +/// Reads all of `r` when it holds at most `max` bytes, else returns an error. +pub fn read_bounded(r: impl Read, max: u64) -> io::Result> { + let mut bytes = Vec::new(); + r.take(max.saturating_add(1)).read_to_end(&mut bytes)?; + if u64::try_from(bytes.len()).map_or(true, |n| n > max) { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("larger than {max} bytes"))); + } + Ok(bytes) +} + +/// The document Explorer passed as a stream. Its bytes are read on the first request and kept, so +/// a later request on the same handler, at another size for example, gets the same document. +pub struct Document { + stream: Option, + bytes: Option>, +} + +impl Document { + pub fn new(stream: R) -> Self { + Self { stream: Some(stream), bytes: None } + } + + /// The document's bytes, read from the stream when it holds at most `max` bytes. When the + /// first read fails, this call and every later one return an error. + pub fn bytes(&mut self, max: u64) -> io::Result<&[u8]> { + if let Some(stream) = self.stream.take() { + self.bytes = Some(read_bounded(stream, max)?); + } + self.bytes.as_deref().ok_or_else(|| io::Error::other("the document's stream could not be read")) + } +} + +/// The `--size` for Explorer's request of a picture `cx` pixels on its longer side: `cx`, at most +/// [`MAX_SIDE`]; `None` for 0. +pub fn request_size(cx: u32) -> Option { + (cx > 0).then(|| cx.min(MAX_SIDE)) +} + +/// The arguments of `vectorcraft-cli` that write the thumbnail of `input` to `output`, `size` +/// pixels on its longer side. +pub fn arguments(size: u32, input: &Path, output: &Path) -> Vec { + vec!["thumbnail".into(), "--size".into(), size.to_string().into(), input.into(), output.into()] +} + +/// A file the handler made in the temp folder, removed when dropped. +struct TempFile(PathBuf); + +impl Drop for TempFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +/// Writes `bytes` to a new file `vectorcraft-thumbnail--.vectorcraft` in `dir`, with the +/// first `n` whose name no file has. +fn write_input(dir: &Path, bytes: &[u8]) -> io::Result { + use std::io::Write; + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + loop { + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = dir.join(format!("vectorcraft-thumbnail-{}-{n}.vectorcraft", std::process::id())); + match File::options().write(true).create_new(true).open(&path) { + Ok(mut file) => { + let temp = TempFile(path); + file.write_all(bytes)?; + return Ok(temp); + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e), + } + } +} + +/// Runs `cli thumbnail --size SIZE IN OUT` with `bytes` written to a new file IN in `dir` and +/// returns the PNG it writes to OUT, IN's name with `.png`. The process is ended when it runs +/// longer than `deadline`. IN and OUT are removed before this returns. +pub fn render(cli: &Path, bytes: &[u8], size: u32, dir: &Path, deadline: Duration) -> Result, String> { + let input = write_input(dir, bytes).map_err(|e| format!("{}: {e}", dir.display()))?; + let output = TempFile(input.0.with_extension("png")); + let mut command = Command::new(cli); + command.args(arguments(size, &input.0, &output.0)).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); + no_console_window(&mut command); + let mut child = command.spawn().map_err(|e| format!("{}: {e}", cli.display()))?; + let end = Instant::now() + deadline; + let status = loop { + if let Some(status) = child.try_wait().map_err(|e| format!("{}: {e}", cli.display()))? { + break status; + } + if Instant::now() >= end { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("{} ran longer than {} seconds", cli.display(), deadline.as_secs())); + } + std::thread::sleep(POLL); + }; + if !status.success() { + return Err(format!("{} exited with {status}", cli.display())); + } + let png = File::open(&output.0).and_then(|f| read_bounded(f, MAX_PNG)).map_err(|e| format!("{}: {e}", output.0.display()))?; + Ok(png) +} + +/// Starts `command` without a console window (`CREATE_NO_WINDOW`, +/// ). +#[cfg(windows)] +fn no_console_window(command: &mut Command) { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NO_WINDOW); +} + +#[cfg(not(windows))] +fn no_console_window(_: &mut Command) {} + +/// The 8-bit RGBA PNG `png` (what `vectorcraft-cli thumbnail` writes, with straight alpha) as a +/// [`Picture`]. An error +/// when it can't be decoded, has another pixel format, or is empty or larger than `max_side` +/// pixels on a side. +pub fn picture(png: &[u8], max_side: u32) -> Result { + let mut reader = png::Decoder::new(io::Cursor::new(png)).read_info().map_err(|e| e.to_string())?; + let (width, height) = (reader.info().width, reader.info().height); + if width == 0 || height == 0 || width > max_side || height > max_side { + return Err(format!("a {width} by {height} picture, not 1 to {max_side} pixels on each side")); + } + let mut buf = vec![0; reader.output_buffer_size().ok_or("the picture is too large")?]; + let frame = reader.next_frame(&mut buf).map_err(|e| e.to_string())?; + if (frame.color_type, frame.bit_depth) != (png::ColorType::Rgba, png::BitDepth::Eight) { + return Err(format!("a {:?} {:?} picture, not 8-bit RGBA", frame.bit_depth, frame.color_type)); + } + let rgba = buf.get(..frame.buffer_size()).ok_or("the picture is cut short")?; + let bgra = rgba.as_chunks::<4>().0.iter().flat_map(|&[r, g, b, a]| [premultiply(b, a), premultiply(g, a), premultiply(r, a), a]).collect(); + Ok(Picture { width, height, bgra }) +} + +/// Color `c` multiplied by alpha `a`, both 0 to 255, rounded to the nearest value. +fn premultiply(c: u8, a: u8) -> u8 { + u8::try_from((u16::from(c) * u16::from(a) + 127) / 255).unwrap_or(u8::MAX) +} diff --git a/apps/vectorcraft-thumbnail-handler/src/tests.rs b/apps/vectorcraft-thumbnail-handler/src/tests.rs new file mode 100644 index 0000000000..5c58697a63 --- /dev/null +++ b/apps/vectorcraft-thumbnail-handler/src/tests.rs @@ -0,0 +1,174 @@ +use std::path::Path; + +use super::*; + +const MIME: &str = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml"); + +/// A PNG of `width`×`height` pixels with `data` as its samples. +fn png_of(width: u32, height: u32, color: png::ColorType, data: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut encoder = png::Encoder::new(&mut out, width, height); + encoder.set_color(color); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().unwrap(); + writer.write_image_data(data).unwrap(); + writer.finish().unwrap(); + out +} + +/// An empty folder `vectorcraft-thumbnail-handler--` in the temp folder. +#[cfg(unix)] +fn folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vectorcraft-thumbnail-handler-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// The names of the files in `dir`. +#[cfg(unix)] +fn files_in(dir: &Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names +} + +#[test] +fn the_class_id_string_and_number_are_the_same_id() { + let hex = format!("{CLSID_VALUE:032X}"); + let grouped = format!("{{{}-{}-{}-{}-{}}}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..]); + assert_eq!(grouped, CLSID); +} + +#[test] +fn registration_names_the_dll_and_the_handler_of_every_extension() { + let values = registry_values("C:\\Program Files\\VectorCraft\\vectorcraft_thumbnail_handler.dll"); + let class = format!("CLSID\\{CLSID}"); + let server = format!("{class}\\InprocServer32"); + let want = vec![ + RegistryValue { key: class, name: None, data: DESCRIPTION.into() }, + RegistryValue { key: server.clone(), name: None, data: "C:\\Program Files\\VectorCraft\\vectorcraft_thumbnail_handler.dll".into() }, + RegistryValue { key: server, name: Some("ThreadingModel"), data: "Apartment".into() }, + RegistryValue { key: format!(".vectorcraft\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() }, + RegistryValue { key: format!(".drawcraft\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() }, + RegistryValue { key: format!(".vctemplate\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() }, + ]; + assert_eq!(values, want); + assert_eq!(THUMBNAIL_SHELL_EX.to_ascii_uppercase(), "{E357FCCD-A995-4576-B01F-234630154E96}"); +} + +#[test] +fn the_extensions_are_the_globs_of_the_document_and_template_types() { + let mut globs = Vec::new(); + let mut in_type = false; + for line in MIME.lines().map(str::trim) { + if let Some(rest) = line.strip_prefix("::new()); + assert_eq!(read_bounded(&[7u8; 11][..], 10).unwrap_err().kind(), io::ErrorKind::InvalidData); + assert!(read_bounded(&[7u8; 11][..], u64::MAX).is_ok()); +} + +#[test] +fn a_second_request_gets_the_same_document() { + let mut document = Document::new(io::Cursor::new(vec![1u8, 2, 3])); + assert_eq!(document.bytes(10).unwrap(), [1, 2, 3]); + assert_eq!(document.bytes(10).unwrap(), [1, 2, 3]); + + let mut large = Document::new(&[7u8; 11][..]); + assert_eq!(large.bytes(10).unwrap_err().kind(), io::ErrorKind::InvalidData); + assert!(large.bytes(10).is_err()); +} + +#[test] +fn the_size_asked_of_the_command_is_at_most_its_limit() { + assert_eq!(request_size(0), None); + assert_eq!(request_size(1), Some(1)); + assert_eq!(request_size(256), Some(256)); + assert_eq!(request_size(MAX_SIDE), Some(MAX_SIDE)); + assert_eq!(request_size(2048), Some(MAX_SIDE)); +} + +#[test] +fn the_command_line_is_thumbnail_size_input_output() { + let args = arguments(96, Path::new("in.vectorcraft"), Path::new("out.png")); + assert_eq!(args, ["thumbnail", "--size", "96", "in.vectorcraft", "out.png"]); +} + +#[test] +fn an_rgba_png_becomes_top_down_premultiplied_bgra() { + // Two rows: opaque red and half-transparent blue, then 20% white and a clear white pixel. + let rgba = [255, 0, 0, 255, 0, 0, 255, 128, 255, 255, 255, 51, 255, 255, 255, 0]; + let picture = picture(&png_of(2, 2, png::ColorType::Rgba, &rgba), 2).unwrap(); + assert_eq!((picture.width, picture.height), (2, 2)); + assert_eq!(picture.bgra, [0, 0, 255, 255, 128, 0, 0, 128, 51, 51, 51, 51, 0, 0, 0, 0]); +} + +#[test] +fn a_png_that_is_not_an_rgba_thumbnail_is_refused() { + assert!(picture(&png_of(1, 1, png::ColorType::Rgb, &[1, 2, 3]), 8).is_err()); + assert!(picture(&png_of(3, 1, png::ColorType::Rgba, &[0; 12]), 2).is_err(), "wider than asked"); + assert!(picture(&png_of(1, 3, png::ColorType::Rgba, &[0; 12]), 2).is_err(), "taller than asked"); + assert!(picture(b"not a picture", 8).is_err()); + let png = png_of(2, 2, png::ColorType::Rgba, &[9; 16]); + assert!(picture(&png[..png.len() - 20], 8).is_err(), "cut short"); +} + +/// `render` runs the program with the thumbnail arguments, returns what it writes to OUT, gives +/// an error for a failed or overlong run, and leaves no file behind. The stand-ins are shell +/// scripts, all written before the first one runs. +#[cfg(unix)] +#[test] +fn render_runs_the_command_and_removes_its_files() { + use std::os::unix::fs::PermissionsExt; + use std::time::Duration; + let dir = folder("render"); + let temp = dir.join("temp"); + std::fs::create_dir(&temp).unwrap(); + let png = png_of(1, 1, png::ColorType::Rgba, &[1, 2, 3, 4]); + std::fs::write(dir.join("picture.png"), &png).unwrap(); + std::fs::write(dir.join("document"), b"document bytes").unwrap(); + let script = |name: &str, body: &str| { + let path = dir.join(name); + std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path + }; + let d = dir.display(); + let writes = script( + "writes", + &format!( + "[ \"$1 $2 $3\" = \"thumbnail --size 64\" ] || exit 4\ncase \"$4\" in *.vectorcraft) ;; *) exit 5 ;; esac\n\ + cmp -s \"$4\" '{d}/document' || exit 3\ncp '{d}/picture.png' \"$5\"" + ), + ); + let fails = script("fails", "echo broken >&2\nexit 1"); + let silent = script("silent", "exit 0"); + let hangs = script("hangs", "exec sleep 30"); + + assert_eq!(render(&writes, b"document bytes", 64, &temp, DEADLINE).unwrap(), png); + assert!(render(&fails, b"x", 64, &temp, DEADLINE).unwrap_err().contains("exited with")); + assert!(render(&silent, b"x", 64, &temp, DEADLINE).is_err(), "no OUT written"); + assert!(render(&hangs, b"x", 64, &temp, Duration::ZERO).unwrap_err().contains("ran longer than")); + assert!(render(&dir.join("missing"), b"x", 64, &temp, DEADLINE).is_err()); + assert_eq!(files_in(&temp), Vec::::new()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index a9a1013520..e8b56c29a9 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -27,7 +27,7 @@ log = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/apps/vectorcraft/src/cursor_theme.rs b/apps/vectorcraft/src/cursor_theme.rs index b23d1099db..ce044dded4 100644 --- a/apps/vectorcraft/src/cursor_theme.rs +++ b/apps/vectorcraft/src/cursor_theme.rs @@ -7,11 +7,17 @@ //! fails in a Flatpak sandbox (`XCURSOR_PATH` unset, no cursor theme in the runtime) and where the //! `default` theme is a dangling symlink; the desktop's own setting names a theme that loads. //! +//! Where no cursor theme can be found at all (KDE or sway without gsettings), the env fix does +//! nothing: [`shell_caps`] leaves out [`Caps::SYSTEM_CURSOR`], and the framework keeps the system +//! pointer and paints no tool cursor beside it (#5311). +//! //! This reads the desktop's cursor theme and size and sets what the user left unset, once, before //! any thread starts and before the window opens. #![cfg_attr(not(target_os = "linux"), allow(dead_code))] +use craft::host::target::Caps; use std::ffi::OsString; +use std::path::{Path, PathBuf}; /// Where a Flatpak sandbox mounts the host's cursor themes (user and system). const FLATPAK_HOST_ICONS: [&str; 2] = ["/run/host/user-share/icons", "/run/host/share/icons"]; @@ -48,6 +54,74 @@ pub fn plan(var: impl Fn(&str) -> Option, host_icons: &[&str], desktop out } +/// Xcursor's default search path when `XCURSOR_PATH` is unset (relative entries are in `$HOME`). +const DEFAULT_ICON_DIRS: [&str; 5] = ["~/.local/share/icons", "~/.icons", "/usr/share/icons", "/usr/share/pixmaps", "/usr/X11R6/lib/X11/icons"]; + +/// The themes `index.theme` lists after `Inherits=`. +fn inherits(index: &str) -> Vec { + index + .lines() + .find_map(|l| l.trim().strip_prefix("Inherits=")) + .map(|v| v.split([',', ';']).map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).collect()) + .unwrap_or_default() +} + +/// Can Xcursor load a pointer for the environment's theme (`XCURSOR_THEME`, else `default`)? It does +/// when the theme, or one it inherits from, has a `default` or `left_ptr` cursor file in a folder of +/// `XCURSOR_PATH` (else Xcursor's default folders). `read` returns a file's text, `exists` tells +/// whether a file is there. +pub fn theme_usable( + var: impl Fn(&str) -> Option, + home: Option<&Path>, + read: impl Fn(&Path) -> Option, + exists: impl Fn(&Path) -> bool, +) -> bool { + let dirs: Vec = match var("XCURSOR_PATH").filter(|v| !v.is_empty()) { + Some(v) => std::env::split_paths(&v).collect(), + None => DEFAULT_ICON_DIRS + .iter() + .filter_map(|d| match d.strip_prefix("~/") { + Some(rest) => home.map(|h| h.join(rest)), + None => Some(PathBuf::from(d)), + }) + .collect(), + }; + let first = var("XCURSOR_THEME").and_then(|v| v.into_string().ok()).filter(|t| !t.is_empty()).unwrap_or_else(|| "default".into()); + let mut todo = vec![first]; + let mut seen: Vec = Vec::new(); + while let Some(theme) = todo.pop() { + // Bounded: themes inherit in short chains, and a cycle must end. + if seen.contains(&theme) || seen.len() >= 16 { + continue; + } + for dir in &dirs { + let base = dir.join(&theme); + if ["default", "left_ptr"].iter().any(|c| exists(&base.join("cursors").join(c))) { + return true; + } + if let Some(index) = read(&base.join("index.theme")) { + todo.extend(inherits(&index)); + } + } + seen.push(theme); + } + false +} + +/// On this machine, after [`apply`]: is there no cursor theme Xcursor can load? Then winit never +/// sets a pointer, and a hidden system pointer does not come back (#2450). +pub fn theme_missing() -> bool { + let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(PathBuf::from); + !theme_usable(|n| std::env::var_os(n), home.as_deref(), |p| std::fs::read_to_string(p).ok(), |p| p.exists()) +} + +/// The shell's capabilities `caps`, without [`Caps::SYSTEM_CURSOR`] when the window opens on +/// Wayland and `theme_missing` finds no cursor theme. The framework then keeps the system pointer +/// and paints no tool cursor beside it (#5311). `theme_missing` runs only on Wayland. +pub fn shell_caps(caps: Caps, wayland: bool, theme_missing: impl FnOnce() -> bool) -> Caps { + if wayland && theme_missing() { caps.difference(Caps::SYSTEM_CURSOR) } else { caps } +} + /// The value of a `gsettings get` line: `'Adwaita'` becomes `Adwaita`, `24` stays `24`. fn gsettings_value(output: &str) -> &str { output.trim().trim_matches('\'') @@ -113,6 +187,43 @@ mod tests { assert!(plan(env(&[("WAYLAND_DISPLAY", "wayland-0")]), &[], odd).is_empty()); } + #[test] + fn a_theme_is_usable_directly_or_through_inherits_and_missing_otherwise() { + let files = ["/i/Bibata/cursors/left_ptr", "/i/Breeze/index.theme", "/i/Loop/index.theme"]; + // Compared as paths, so the joins match on Windows too, where they use `\`. + let exists = |p: &Path| files.iter().any(|f| Path::new(f) == p); + let read = |p: &Path| { + if p == Path::new("/i/Breeze/index.theme") { + Some("[Icon Theme]\nInherits=Other, Bibata\n".to_owned()) + } else if p == Path::new("/i/Loop/index.theme") { + Some("Inherits=Loop\n".to_owned()) + } else { + None + } + }; + let with = |theme: &'static str| { + move |n: &str| (n == "XCURSOR_PATH").then(|| OsString::from("/i")).or((n == "XCURSOR_THEME").then(|| OsString::from(theme))) + }; + assert!(theme_usable(with("Bibata"), None, read, exists)); + assert!(theme_usable(with("Breeze"), None, read, exists)); + // No such theme, a theme without cursors, an inheritance loop: nothing to load. + assert!(!theme_usable(with("Nope"), None, read, exists)); + assert!(!theme_usable(with("Loop"), None, read, exists)); + // Unset: Xcursor's default folders and the `default` theme. + assert!(!theme_usable(|_| None, Some(Path::new("/home/u")), read, exists)); + } + + #[test] + fn without_a_cursor_theme_on_wayland_the_system_pointer_stays_alone() { + let native = Caps::native(craft::host::target::Os::Linux); + assert!(native.contains(Caps::SYSTEM_CURSOR)); + let without = shell_caps(native, true, || true); + assert!(!without.contains(Caps::SYSTEM_CURSOR), "Wayland with no cursor theme: no painted cursor beside the system pointer"); + assert_eq!(without.union(Caps::SYSTEM_CURSOR), native, "only the system cursor is left out"); + assert_eq!(shell_caps(native, true, || false), native, "Wayland with a theme"); + assert_eq!(shell_caps(native, false, || panic!("the theme is looked up only on Wayland")), native, "X11 and XWayland"); + } + #[test] fn gsettings_output_is_unquoted() { assert_eq!(gsettings_value("'Adwaita'\n"), "Adwaita"); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 4f4069d438..5a7d3e33ba 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -671,6 +671,11 @@ fn main() -> std::process::ExitCode { // framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and // Preferences › User Interface › System Title Bar. let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() }; + // On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted + // beside it (#2450, #5311). + let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland; + let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing); + let shell_info = shell_info.caps(caps); let titlebar_pref = if engine_pref("systemTitleBar").and_then(|v| v.as_bool()).unwrap_or(false) { TitleBarPref::System } else { TitleBarPref::Integrated }; let decision = decide_for(Prefix::new("VECTORCRAFT"), shell_info.backend, titlebar_pref); diff --git a/apps/vectorcraft/src/profile_root.rs b/apps/vectorcraft/src/profile_root.rs index f8cf51eaeb..7f46e77766 100644 --- a/apps/vectorcraft/src/profile_root.rs +++ b/apps/vectorcraft/src/profile_root.rs @@ -175,7 +175,16 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let child = canonical_future(&chosen.join(name))?; + let target = chosen.join(name); + match std::fs::symlink_metadata(&target) { + Ok(metadata) if !metadata.is_dir() => { + return Err(format!("the nightly {label} must be a directory inside its selected profile")); + } + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")), + } + let child = canonical_future(&target)?; if child == chosen || !child.starts_with(&chosen) { return Err(format!("the nightly {label} must stay inside its selected profile")); } @@ -192,11 +201,86 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> { }; for entry in entries { let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - private_subdirectory(root, entry.file_name(), "profile entry")?; + let path = entry.path(); + let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + // Settings and session state are ordinary files, not directories. Keep the existing + // directory-boundary check for folders (including the known folder-only entries). + let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); + if metadata.is_file() && !folder_only { + private_regular_file(&path, &metadata)?; + } else { + private_subdirectory(root, entry.file_name(), "profile entry")?; + } } Ok(()) } +/// Persisted files must have their own ordinary file identity, not an alias to other data. +fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt as _; + if metadata.nlink() != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + #[cfg(all(windows, feature = "wgpu"))] + { + use winsafe::{HFILE, co}; + let (file, _) = HFILE::CreateFile( + path.to_str().ok_or("the nightly profile file path is not textual")?, + co::GENERIC::default(), + Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), + None, + co::DISPOSITION::OPEN_EXISTING, + co::FILE_ATTRIBUTE::NORMAL, + Some(co::FILE_FLAG::OPEN_REPARSE_POINT), + None, + None, + ) + .map_err(|e| e.to_string())?; + let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; + if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT) || info.dwFileAttributes.has(co::FILE_ATTRIBUTE::DIRECTORY) { + return Err("the nightly profile file must not be an alias or directory".into()); + } + if info.nNumberOfLinks != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + #[cfg(all(windows, not(feature = "wgpu")))] + { + use std::os::windows::fs::MetadataExt as _; + const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400; + if metadata.file_attributes() & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0 { + return Err("the nightly profile file must not be an alias or directory".into()); + } + } + let _ = (path, metadata); + Ok(()) +} + +const PROFILE_FOLDERS: [&str; 18] = [ + "Data Recovery", + "Fonts", + "logs", + "Launch", + "Color Profiles", + "Plug-ins", + "Scripts", + "Startup Scripts", + "Metadata Templates", + "New Document Profiles", + "Proof Setups", + "Script Data", + "PDF Presets", + "Swatches", + "Graphic Styles", + "Symbols", + "Brushes", + "Libraries", +]; + /// Recognise the shared portable data namespace in both the supplied and the resolved path. Up to /// the chosen folder itself, a marker only counts beside a VectorCraft executable, so an unrelated /// `portable.txt` higher up (in a user folder or at a drive root) does not refuse the profile. @@ -557,6 +641,31 @@ mod tests { assert!(result.unwrap_err().contains("not writable")); } + #[test] + fn nightly_profile_reopens_after_saving_settings_and_session_state() { + let fixture = Fixture::new(); + for platform in PLATFORMS { + let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); + assert_eq!(fixture.check(platform, &private).unwrap(), private); + for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] { + std::fs::write(private.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + std::fs::create_dir(private.join(name)).unwrap(); + } + assert_eq!(fixture.check(platform, &private).unwrap(), private); + assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data"); + for name in PROFILE_FOLDERS { + let path = private.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } + } + } + #[test] fn the_platform_case_rules_are_the_file_systems_ones() { let fixture = Fixture::new(); diff --git a/crates/brush/src/colorize.rs b/crates/brush/src/colorize.rs index f0caf2ac01..47211426f6 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -121,14 +121,125 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) { /// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter. const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474; -/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its -/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's -/// [`crate::track::seed_of`]). -pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) { - let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT); +/// Mixed into a stroke's seed for its saturation jitter, so its amounts do not follow the hue +/// jitter's and the hue jitter's amounts stay as they were without it. +const SATURATION_JITTER_SALT: u64 = 0x7361_745f_6a69_7474; + +/// Mixed into a stroke's seed for its brightness jitter, so its amounts follow neither the hue +/// jitter's nor the saturation jitter's, and theirs stay as they were without it. +const BRIGHTNESS_JITTER_SALT: u64 = 0x6272_695f_6a69_7474; + +/// Recolor each of `copies` (a scatter brush's copies, in order along the path) with `adjust`, +/// given that copy's own amount between −`amount` and `amount`, drawn from `seed` (the stroke's +/// [`crate::track::seed_of`]) mixed with `salt`. `adjust` gives `None` for a color it leaves as it +/// is. +fn jitter_copies(copies: &mut [Node], amount: f64, seed: u64, salt: u64, adjust: fn(&Color, f32) -> Option) { + let mut rng = crate::track::Rng::new(seed ^ salt); for n in copies { - let turn = rng.range(-amount, amount) as f32; - turn_hues(n, turn); + let by = rng.range(-amount, amount) as f32; + recolor_solids(n, &|c| adjust(c, by)); + } +} + +/// Turn the hue of each of `copies` by its own amount between −`amount` and `amount` degrees (see +/// [`jitter_copies`]). +pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) { + jitter_copies(copies, amount, seed, HUE_JITTER_SALT, turned); +} + +/// Move the saturation of each of `copies` by its own amount between −`amount` and `amount` +/// percentage points (see [`jitter_copies`]). +pub(crate) fn jitter_saturations(copies: &mut [Node], amount: f64, seed: u64) { + jitter_copies(copies, amount, seed, SATURATION_JITTER_SALT, saturated); +} + +/// Move the brightness of each of `copies` by its own amount between −`amount` and `amount` +/// percentage points (see [`jitter_copies`]). +pub(crate) fn jitter_brightnesses(copies: &mut [Node], amount: f64, seed: u64) { + jitter_copies(copies, amount, seed, BRIGHTNESS_JITTER_SALT, brightened); +} + +/// `c` with its brightness moved by `points` percentage points, worked out on its own components +/// so its hue and saturation stay: RGB in HSB of its values, Gray by taking that much ink off or +/// adding it, CMYK by changing its K over the brightness its C, M and Y leave (C, M and Y change +/// only to go brighter than they show with no K), Lab by moving its lightness by `points` units +/// with a and b kept. The result stays between black and full brightness. White, black and grays +/// move too. `None` when the brightness stays as it is. +fn brightened(c: &Color, points: f32) -> Option { + if !points.is_finite() { + return None; + } + let by = points / 100.0; + match *c { + Color::Rgb { r, g, b } => { + let [h, s, v] = vectorcraft_color::rgb_to_hsb([r, g, b]); + let to = (v + by).clamp(0.0, 1.0); + (to != v).then(|| { + let [r, g, b] = vectorcraft_color::hsb_to_rgb([h, s, to]); + Color::rgb(r, g, b) + }) + } + Color::Gray { k } => { + let to = (k - by).clamp(0.0, 1.0); + (to != k).then_some(Color::gray(to)) + } + Color::Cmyk { c, m, y, k } => { + // `v` is the brightness C, M and Y leave; with its K the color shows `v` × (1 − K). + let [h, s, v] = vectorcraft_color::rgb_to_hsb([1.0 - c, 1.0 - m, 1.0 - y]); + let shown = v * (1.0 - k); + let to = (shown + by).clamp(0.0, 1.0); + if to == shown { + None + } else if to <= v { + // v > 0 here: to < shown would need shown > 0, and to > shown leaves to > 0. + Some(Color::cmyk(c, m, y, (1.0 - to / v).clamp(0.0, 1.0))) + } else { + let [r, g, b] = vectorcraft_color::hsb_to_rgb([h, s, to]); + Some(Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, 0.0)) + } + } + Color::Lab { l, a, b } => { + let to = (l + points).clamp(0.0, 100.0); + (to != l).then_some(Color::lab(to, a, b)) + } + } +} + +/// The largest a or b a Lab color takes. +const LAB_AB_MAX: f64 = 127.0; + +/// `c` with its saturation moved by `points` percentage points, worked out on its own components +/// so its hue and brightness stay: RGB in HSB of its values, CMYK over C, M and Y with K kept, Lab +/// by moving its chroma (the length of a and b) by `points` with its lightness and hue angle kept. +/// The result stays between no saturation and full. `None` for a color without a hue (white, +/// black and grays, which have no saturation to move) and for one whose saturation stays as it is +/// (already at the end it would move past), so such a color keeps its swatch link. +fn saturated(c: &Color, points: f32) -> Option { + if !points.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() { + return None; + } + let by = points / 100.0; + let move_by = |v: [f32; 3]| { + let [h, s, b] = vectorcraft_color::rgb_to_hsb(v); + let to = (s + by).clamp(0.0, 1.0); + (s > 0.0 && to != s).then(|| vectorcraft_color::hsb_to_rgb([h, to, b])) + }; + match *c { + Color::Rgb { r, g, b } => move_by([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)), + Color::Cmyk { c, m, y, k } => move_by([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)), + Color::Gray { .. } => None, + Color::Lab { l, a, b } => { + let (a, b) = (f64::from(a), f64::from(b)); + let chroma = a.hypot(b); + if chroma <= 0.0 { + return None; + } + // A longer chroma is cut back along the same hue angle until a and b fit; one that + // already reaches past that does not grow. + let fit = (LAB_AB_MAX / a.abs().max(b.abs())).max(1.0); + let scale = ((chroma + f64::from(points)).max(0.0) / chroma).min(fit); + (scale != 1.0).then(|| Color::lab(l, (a * scale) as f32, (b * scale) as f32)) + } } } @@ -156,32 +267,36 @@ fn turned(c: &Color, degrees: f32) -> Option { } } -fn turn_paint(p: &mut Paint, degrees: f32) { +/// Replace a solid paint's color with what `adjust` gives for it, dropping its swatch link. A +/// color that comes back unchanged (an amount too small to move its components) keeps the paint +/// and its link. +fn recolor_paint(p: &mut Paint, adjust: &dyn Fn(&Color) -> Option) { if let Paint::Solid { color, .. } = p - && let Some(c) = turned(color, degrees) + && let Some(c) = adjust(color) + && c != *color { *p = Paint::solid(c); } } -/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A +/// Recolor the solid fills and strokes under `n` with `adjust`, its type's characters included. A /// mask's colors are its values, so they stay. -fn turn_hues(n: &mut Node, degrees: f32) { +fn recolor_solids(n: &mut Node, adjust: &dyn Fn(&Color) -> Option) { for it in &mut n.appearance.items { match it { - AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees), - AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees), + AppearanceItem::Fill(f) => recolor_paint(&mut f.paint, adjust), + AppearanceItem::Stroke(s) => recolor_paint(&mut s.paint, adjust), } } if let NodeKind::Text(t) = &mut n.kind { for r in &mut t.runs { - turn_paint(&mut r.style.fill, degrees); - turn_paint(&mut r.style.stroke, degrees); + recolor_paint(&mut r.style.fill, adjust); + recolor_paint(&mut r.style.stroke, adjust); } } if let Some(ch) = n.children_mut() { for c in ch.iter_mut() { - turn_hues(Arc::make_mut(c), degrees); + recolor_solids(Arc::make_mut(c), adjust); } } } diff --git a/crates/brush/src/defaults.rs b/crates/brush/src/defaults.rs index b99f36ecec..dc07707cd3 100644 --- a/crates/brush/src/defaults.rs +++ b/crates/brush/src/defaults.rs @@ -173,6 +173,8 @@ pub fn defaults() -> &'static [Brush] { rotation_relative_to_path: false, colorization: Colorization::Tints, hue_jitter: 0.0, + saturation_jitter: 0.0, + brightness_jitter: 0.0, modes: None, }), }, @@ -187,6 +189,8 @@ pub fn defaults() -> &'static [Brush] { rotation_relative_to_path: true, colorization: Colorization::None, hue_jitter: 0.0, + saturation_jitter: 0.0, + brightness_jitter: 0.0, modes: None, }), }, diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 850a60e33e..85dfc8e084 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -324,6 +324,22 @@ pub struct Scatter { /// 0 (brushes saved before there was hue jitter) leaves the colors as they are. #[serde(skip_serializing_if = "is_zero")] pub hue_jitter: f64, + /// Saturation jitter in percent, 0 to 100: each copy moves the saturation of the solid colors it + /// draws, after the colorization and the hue jitter, by its own amount between + /// −`saturation_jitter` and `saturation_jitter` percentage points, keeping their hue and + /// brightness. The stroke's path and the brush name fix the amounts, so a stroke draws the same + /// colors every time. 0 (brushes saved before there was saturation jitter) leaves the colors as + /// they are. + #[serde(skip_serializing_if = "is_zero")] + pub saturation_jitter: f64, + /// Brightness jitter in percent, 0 to 100: each copy moves the brightness of the solid colors + /// it draws, after the colorization and the hue and saturation jitter, by its own amount + /// between −`brightness_jitter` and `brightness_jitter` percentage points, keeping their hue + /// and saturation. White, black and grays move too. The stroke's path and the brush name fix + /// the amounts, so a stroke draws the same colors every time. 0 (brushes saved before there + /// was brightness jitter) leaves the colors as they are. + #[serde(skip_serializing_if = "is_zero")] + pub brightness_jitter: f64, /// How size, spacing, scatter and rotation vary between their two values: Fixed takes the /// first, Random any value between them, Pressure the first at the lightest pen pressure and /// the second at the heaviest, Tilt the first with the pen lying flat and the second upright, @@ -346,6 +362,8 @@ impl Default for Scatter { rotation_relative_to_path: false, colorization: Colorization::None, hue_jitter: 0.0, + saturation_jitter: 0.0, + brightness_jitter: 0.0, modes: None, } } @@ -356,6 +374,10 @@ impl Scatter { pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)]; /// The range of [`Scatter::hue_jitter`] (°). pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0); + /// The range of [`Scatter::saturation_jitter`] (%). + pub const SATURATION_JITTER_RANGE: (f64, f64) = (0.0, 100.0); + /// The range of [`Scatter::brightness_jitter`] (%). + pub const BRIGHTNESS_JITTER_RANGE: (f64, f64) = (0.0, 100.0); /// Size, spacing, scatter and rotation, each as its (first, second) values. pub fn values(&self) -> [(f64, f64); 4] { @@ -549,6 +571,15 @@ pub struct PatternBrush { pub end_swatch: Option, /// Scale in percent. pub scale: f64, + /// How the scale varies along a stroke: `None` (Fixed) always `scale`; a mode that follows the + /// pen goes from `scale` to [`Self::scale_max`] over the ranges [`Variation`] gives, as an Art + /// brush's width does ([`ArtBrush::width_mode`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_mode: Option, + /// The second scale (%) of a mode that follows the pen: at the heaviest pressure, upright, at + /// 180° or at the wheel's far end (`scale` without one). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_max: Option, /// Space between tiles in percent of the tile width. pub spacing: f64, pub fit: PatternFit, @@ -561,6 +592,15 @@ impl PatternBrush { /// The ranges of the scale and of the spacing (%). pub const SCALE_RANGE: (f64, f64) = (1.0, 10000.0); pub const SPACING_RANGE: (f64, f64) = (0.0, 10000.0); + + /// The scales (%) where the pen reads 0 and 1 for the scale's mode (the lightest and the + /// heaviest pressure, for Pressure): `scale` for both unless the scale follows the pen. + pub fn scale_range(&self) -> (f64, f64) { + match self.scale_mode { + Some(m) if m.follows_pen() => (self.scale, self.scale_max.unwrap_or(self.scale)), + _ => (self.scale, self.scale), + } + } } impl Default for PatternBrush { @@ -584,6 +624,8 @@ impl Default for PatternBrush { end_frame: None, end_swatch: None, scale: 100.0, + scale_mode: None, + scale_max: None, spacing: 0.0, fit: PatternFit::Stretch, flip_along: false, @@ -750,6 +792,8 @@ impl Brush { s.scatter = within_pair(s.scatter, scatter, 0.0); s.rotation = within_pair(s.rotation, rotation, 0.0); s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0); + s.saturation_jitter = within(s.saturation_jitter, Scatter::SATURATION_JITTER_RANGE, 0.0); + s.brightness_jitter = within(s.brightness_jitter, Scatter::BRIGHTNESS_JITTER_RANGE, 0.0); s.colorization.sanitize(); } BrushKind::Art(a) => { @@ -767,6 +811,11 @@ impl Brush { } BrushKind::Pattern(p) => { p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0); + // The scale follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed. + if !p.scale_mode.is_some_and(Variation::follows_pen) { + p.scale_mode = None; + } + p.scale_max = p.scale_max.map(|s| within(s, PatternBrush::SCALE_RANGE, p.scale)); p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0); for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] { if frame.is_some_and(|f| !valid_tile_frame(f)) { @@ -801,6 +850,9 @@ struct ScatterOptions { modes: Option<[Variation; 4]>, rotation_relative_to_path: bool, colorization: Colorization, + hue_jitter: f64, + saturation_jitter: f64, + brightness_jitter: f64, } /// The Art brush fields a stroke can set for itself. @@ -819,6 +871,8 @@ struct ArtOptions { #[derive(Serialize, Deserialize)] struct PatternOptions { scale: f64, + scale_mode: Option, + scale_max: Option, spacing: f64, fit: PatternFit, flip_along: bool, @@ -833,9 +887,20 @@ impl BrushKind { pub fn stroke_option_keys(&self) -> &'static [&'static str] { match self { BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"], - BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"], + BrushKind::Scatter(_) => &[ + "size", + "spacing", + "scatter", + "rotation", + "modes", + "rotation_relative_to_path", + "colorization", + "hue_jitter", + "saturation_jitter", + "brightness_jitter", + ], BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"], - BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"], + BrushKind::Pattern(_) => &["scale", "scale_mode", "scale_max", "spacing", "fit", "flip_along", "flip_across", "colorization"], BrushKind::Bristle(_) => &[], } } @@ -858,6 +923,9 @@ impl BrushKind { modes: s.modes, rotation_relative_to_path: s.rotation_relative_to_path, colorization: s.colorization, + hue_jitter: s.hue_jitter, + saturation_jitter: s.saturation_jitter, + brightness_jitter: s.brightness_jitter, }), BrushKind::Art(a) => serde_json::to_value(ArtOptions { width: a.width, @@ -870,6 +938,8 @@ impl BrushKind { }), BrushKind::Pattern(p) => serde_json::to_value(PatternOptions { scale: p.scale, + scale_mode: p.scale_mode, + scale_max: p.scale_max, spacing: p.spacing, fit: p.fit, flip_along: p.flip_along, @@ -890,6 +960,7 @@ impl BrushKind { let o: ScatterOptions = serde_json::from_value(v)?; (s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes); (s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization); + (s.hue_jitter, s.saturation_jitter, s.brightness_jitter) = (o.hue_jitter, o.saturation_jitter, o.brightness_jitter); } BrushKind::Art(a) => { let o: ArtOptions = serde_json::from_value(v)?; @@ -898,8 +969,8 @@ impl BrushKind { } BrushKind::Pattern(p) => { let o: PatternOptions = serde_json::from_value(v)?; - (p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) = - (o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization); + (p.scale, p.scale_mode, p.scale_max, p.spacing) = (o.scale, o.scale_mode, o.scale_max, o.spacing); + (p.fit, p.flip_along, p.flip_across, p.colorization) = (o.fit, o.flip_along, o.flip_across, o.colorization); } BrushKind::Bristle(_) => {} } @@ -1123,17 +1194,23 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name), BrushKind::Art(a) => warp::art(a, bp, w, stroke), BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name), - BrushKind::Pattern(p) => warp::pattern(p, bp, w), + BrushKind::Pattern(p) => warp::pattern(p, bp, w, stroke), }; let colorization = brush.kind.colorization(); for n in &mut out { colorize(n, colorization, &stroke.paint); } // One piece per copy, in the order the copies run along the path. - if let BrushKind::Scatter(s) = &brush.kind - && s.hue_jitter > 0.0 - { - colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name)); + if let BrushKind::Scatter(s) = &brush.kind { + if s.hue_jitter > 0.0 { + colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name)); + } + if s.saturation_jitter > 0.0 { + colorize::jitter_saturations(&mut out, s.saturation_jitter, track::seed_of(bp, &brush.name)); + } + if s.brightness_jitter > 0.0 { + colorize::jitter_brightnesses(&mut out, s.brightness_jitter, track::seed_of(bp, &brush.name)); + } } leave_out_brushed(doc, &mut out, &mut Known::new()); out diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index ad19488f96..c5d13cd0fa 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1249,6 +1249,380 @@ fn hue_jitter_turns_type_every_colorization_and_linked_colors() { } } +/// A stroke's own hue, saturation and brightness jitter replace the brush's, as its other scatter +/// settings do, and are kept within their ranges. +#[test] +fn a_strokes_own_jitter_replaces_the_brushs() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + let pink = Color::rgb(0.8, 0.4, 0.4); + let b = sat_jittered(pink, Colorization::None, 0.0, 0.0); + let own = + stroke_pieces(&doc, &b, &path, &with_options(serde_json::json!({"hue_jitter": 30.0, "saturation_jitter": 40.0, "brightness_jitter": 20.0}))); + let brushed = stroke_pieces(&doc, &bri_jittered(sat_jittered(pink, Colorization::None, 30.0, 40.0), 20.0), &path, &stroke(1.0)); + assert_eq!(fill_colors(&own), fill_colors(&brushed)); + assert!(fill_colors(&own).iter().any(|c| *c != pink)); + // The brightness is part of what the stroke's own options give. + let without = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 30.0, 40.0), &path, &stroke(1.0)); + assert_ne!(fill_colors(&own), fill_colors(&without)); + for (key, given, kept) in [("saturation_jitter", 500.0, 100.0), ("brightness_jitter", 500.0, 100.0)] { + let options = serde_json::Map::from_iter([(key.to_string(), serde_json::json!(given))]); + assert_eq!(b.stroke_options_that_differ(&options).unwrap(), serde_json::Map::from_iter([(key.to_string(), serde_json::json!(kept))])); + } + // A stroke that sets 0 on a jittered brush draws the art's own color. + let still = + stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 40.0), &path, &with_options(serde_json::json!({"saturation_jitter": 0.0}))); + assert!(!still.is_empty() && fill_colors(&still).iter().all(|c| *c == pink)); +} + +/// A scatter brush of rectangles filled `fill`, with `colorization`, `hue_jitter` and +/// `saturation_jitter`. +fn sat_jittered(fill: Color, colorization: Colorization, hue_jitter: f64, saturation_jitter: f64) -> Brush { + let mut b = jittered(fill, colorization, hue_jitter); + if let BrushKind::Scatter(s) = &mut b.kind { + s.saturation_jitter = saturation_jitter; + } + b +} + +/// The HSB of an RGB color's own values. +fn rgb_hsb(c: &Color) -> [f32; 3] { + let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") }; + vectorcraft_color::rgb_to_hsb([r, g, b]) +} + +#[test] +fn saturation_jitter_moves_each_copy_the_same_every_time() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + // A red at 50% saturation and 80% brightness. + let pink = Color::rgb(0.8, 0.4, 0.4); + let b = sat_jittered(pink, Colorization::None, 0.0, 40.0); + let out = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(out.len(), 20); + assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors"); + let colors = fill_colors(&out); + let hsb: Vec<[f32; 3]> = colors.iter().map(rgb_hsb).collect(); + // Each copy's saturation is within 40 points of 50%; its hue and brightness stay. + assert!(hsb.iter().all(|[h, s, v]| hue_gap(*h, 0.0) < 1e-3 && (s - 0.5).abs() <= 0.4001 && near(f64::from(*v), 0.8, 1e-4)), "{hsb:?}"); + assert!(hsb.iter().any(|[_, s, _]| *s > 0.55) && hsb.iter().any(|[_, s, _]| *s < 0.45), "the copies move both ways: {hsb:?}"); + let distinct: std::collections::HashSet = colors.iter().map(Color::to_hex).collect(); + assert!(distinct.len() > 10, "each copy moves by its own amount: {distinct:?}"); + // The copies stay where they were, at their size and angle. + let plain = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 0.0), &path, &stroke(1.0)); + let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::>(); + assert_eq!(boxes(&out), boxes(&plain)); + // Another path draws other amounts. + let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0))); + assert_ne!(other, colors); + // At 100 the copies reach gray or full saturation and go no further. + let full: Vec = fill_colors(&stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 100.0), &path, &stroke(1.0))) + .iter() + .map(|c| rgb_hsb(c)[1]) + .collect(); + assert!(full.iter().all(|s| (0.0..=1.0).contains(s)), "{full:?}"); + assert!(full.iter().any(|s| *s < 1e-6) && full.iter().any(|s| *s > 1.0 - 1e-6), "{full:?}"); + // Saturation jitter leaves the hue jitter's amounts as they were. + let red = Color::rgb(1.0, 0.0, 0.0); + let hue_only = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 0.0), &path, &stroke(1.0))); + let both = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 50.0), &path, &stroke(1.0))); + assert_eq!(both.len(), hue_only.len()); + assert_ne!(both, hue_only); + for (b, h) in both.iter().zip(&hue_only) { + assert!(hue_gap(rgb_hsb(b)[0], rgb_hsb(h)[0]) < 0.01, "{b:?} from {h:?}"); + } +} + +#[test] +fn saturation_jitter_of_zero_changes_nothing() { + let pink = Color::rgb(0.8, 0.4, 0.4); + let out = stroke_pieces(&Document::new(1.0, 1.0), &sat_jittered(pink, Colorization::None, 0.0, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0)); + assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == pink)); + // A brush without saturation jitter is saved as before, and one saved before reads as 0. + let v = serde_json::to_value(sat_jittered(pink, Colorization::None, 0.0, 0.0)).unwrap(); + assert!(v.get("saturation_jitter").is_none(), "{v}"); + let mut old = serde_json::to_value(sat_jittered(pink, Colorization::None, 0.0, 25.0)).unwrap(); + assert_eq!(old.as_object_mut().unwrap().remove("saturation_jitter"), Some(serde_json::json!(25.0))); + let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.saturation_jitter, 0.0, "a brush saved without the key reads as 0"); + let mut with = v.clone(); + with["saturation_jitter"] = serde_json::json!(25.0); + let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.saturation_jitter, 25.0); + // Values outside 0..100 are clamped. + for (given, kept) in [(250.0, 100.0), (-5.0, 0.0)] { + let mut v = v.clone(); + v["saturation_jitter"] = serde_json::json!(given); + let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.saturation_jitter, kept, "{given}"); + } +} + +#[test] +fn saturation_jitter_moves_after_the_colorization_in_each_model() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + // Tints: black art takes the blue stroke color, whose saturation then moves. + let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + let hsb: Vec<[f32; 3]> = + fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 30.0), &path, &blue)).iter().map(rgb_hsb).collect(); + assert!(!hsb.is_empty() && hsb.iter().all(|[h, s, _]| hue_gap(*h, 240.0) < 1e-3 && *s >= 0.6999), "{hsb:?}"); + assert!(hsb.iter().any(|[_, s, _]| *s < 0.97), "{hsb:?}"); + // Black, white and grays have no saturation to move, in every model. + for key in + [Color::rgb(0.5, 0.5, 0.5), Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4), Color::lab(60.0, 0.0, 0.0)] + { + let key = StrokeLayer::new(Paint::solid(key), 1.0); + let moved = stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 100.0), &path, &key); + let still = stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 0.0), &path, &key); + assert_eq!(fill_colors(&moved), fill_colors(&still), "{key:?}"); + } + // A process color stays a process color with its K kept, moved over its C, M and Y. + let cmyk = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::cmyk(0.0, 0.6, 0.6, 0.25), Colorization::None, 0.0, 30.0), &path, &stroke(1.0))); + assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 0.6, 0.6, 0.25)), "{cmyk:?}"); + for c in &cmyk { + let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") }; + // No cyan, as before, and magenta equal to yellow: the hue stays; the ink is within 30 points. + assert!(k == 0.25 && near(f64::from(c), 0.0, 1e-5) && near(f64::from(m), f64::from(y), 1e-5), "{c} {m} {y} {k}"); + assert!((m - 0.6).abs() <= 0.3001, "{m}"); + } + // A Lab color keeps its lightness and hue angle; its chroma moves within 20 of its 50. + let lab = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 0.0, 20.0), &path, &stroke(1.0))); + assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}"); + for c in &lab { + let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") }; + let chroma = f64::from(a.hypot(b)); + assert!(l == 50.0 && (chroma - 50.0).abs() <= 20.001 && near(f64::from(b.atan2(a)), 30f64.atan2(40.0), 1e-4), "{c:?}"); + } + // A chroma that grows stops where a and b reach their largest. + let vivid = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::lab(50.0, 120.0, 0.0), Colorization::None, 0.0, 100.0), &path, &stroke(1.0))); + assert!(vivid.iter().all(|c| matches!(*c, Color::Lab { a, b, .. } if (0.0..=127.0001).contains(&a) && b.abs() < 1e-4)), "{vivid:?}"); + assert!(vivid.iter().any(|c| matches!(*c, Color::Lab { a, .. } if a > 126.999)), "{vivid:?}"); +} + +/// Saturation jitter moves type's characters and a color linked to a swatch (which loses the +/// link); a pattern paint stays. +#[test] +fn saturation_jitter_moves_type_and_linked_colors() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let typed = |saturation_jitter| Brush { + name: "s".into(), + kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), saturation_jitter, ..Default::default() }), + }; + let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0))); + let moved = run_paints(&stroke_pieces(&doc, &typed(60.0), &path, &stroke(1.0))); + assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}"); + assert_eq!(moved.len(), still.len()); + assert!(moved.iter().any(|p| *p != (red.clone(), red.clone())), "the characters move: {moved:?}"); + assert!(moved.iter().all(|(f, s)| f == s), "a copy's character fill and stroke move by the same amount: {moved:?}"); + let linked = Paint::Solid { color: Color::rgb(0.8, 0.4, 0.4), swatch: Some("Rose".into()), tint: 1.0 }; + let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }; + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(linked.clone()); + art.appearance.set_stroke(pattern.clone()); + let b = |saturation_jitter| Brush { + name: "s".into(), + kind: BrushKind::Scatter(Scatter { art: art.clone(), saturation_jitter, ..Default::default() }), + }; + let moved = stroke_pieces(&doc, &b(50.0), &path, &stroke(1.0)); + assert!(!moved.is_empty()); + assert!(moved.iter().any(|n| n.appearance.fill_paint().color() != Some(Color::rgb(0.8, 0.4, 0.4))), "the linked color moves"); + for n in &moved { + assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint()); + assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern)); + } +} + +/// `b` (a scatter brush) with `brightness_jitter`. +fn bri_jittered(mut b: Brush, brightness_jitter: f64) -> Brush { + if let BrushKind::Scatter(s) = &mut b.kind { + s.brightness_jitter = brightness_jitter; + } + b +} + +#[test] +fn brightness_jitter_moves_each_copy_the_same_every_time() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + // A red at 50% saturation and 80% brightness. + let pink = Color::rgb(0.8, 0.4, 0.4); + let b = bri_jittered(sat_jittered(pink, Colorization::None, 0.0, 0.0), 15.0); + let out = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(out.len(), 20); + assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors"); + let colors = fill_colors(&out); + let hsb: Vec<[f32; 3]> = colors.iter().map(rgb_hsb).collect(); + // Each copy's brightness is within 15 points of 80%; its hue and saturation stay. + assert!(hsb.iter().all(|[h, s, v]| hue_gap(*h, 0.0) < 1e-3 && near(f64::from(*s), 0.5, 1e-4) && (v - 0.8).abs() <= 0.1501), "{hsb:?}"); + assert!(hsb.iter().any(|[_, _, v]| *v > 0.85) && hsb.iter().any(|[_, _, v]| *v < 0.75), "the copies move both ways: {hsb:?}"); + let distinct: std::collections::HashSet = colors.iter().map(Color::to_hex).collect(); + assert!(distinct.len() > 10, "each copy moves by its own amount: {distinct:?}"); + // The copies stay where they were, at their size and angle. + let plain = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 0.0), &path, &stroke(1.0)); + let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::>(); + assert_eq!(boxes(&out), boxes(&plain)); + // Another path draws other amounts. + let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0))); + assert_ne!(other, colors); + // At 100 the copies reach black or full brightness and go no further. + let full: Vec = + fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(pink, Colorization::None, 0.0, 0.0), 100.0), &path, &stroke(1.0))) + .iter() + .map(|c| rgb_hsb(c)[2]) + .collect(); + assert!(full.iter().all(|v| (0.0..=1.0).contains(v)), "{full:?}"); + assert!(full.iter().any(|v| *v < 1e-6) && full.iter().any(|v| *v > 1.0 - 1e-6), "{full:?}"); + // Brightness jitter leaves the hue and saturation jitter's amounts as they were. + let red = Color::rgb(1.0, 0.0, 0.0); + let hue_sat = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 50.0), &path, &stroke(1.0))); + let all = fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(red, Colorization::None, 90.0, 50.0), 30.0), &path, &stroke(1.0))); + assert_eq!(all.len(), hue_sat.len()); + assert_ne!(all, hue_sat); + for (a, h) in all.iter().zip(&hue_sat) { + let ([ha, sa, _], [hh, sh, _]) = (rgb_hsb(a), rgb_hsb(h)); + assert!(hue_gap(ha, hh) < 0.01 && (sa - sh).abs() < 1e-4, "{a:?} from {h:?}"); + } +} + +#[test] +fn brightness_jitter_of_zero_changes_nothing() { + let pink = Color::rgb(0.8, 0.4, 0.4); + let plain = sat_jittered(pink, Colorization::None, 0.0, 0.0); + let out = stroke_pieces(&Document::new(1.0, 1.0), &bri_jittered(plain.clone(), 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0)); + assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == pink)); + // A brush without brightness jitter is saved as before, and one saved before reads as 0. + let v = serde_json::to_value(&plain).unwrap(); + assert!(v.get("brightness_jitter").is_none(), "{v}"); + let mut old = serde_json::to_value(bri_jittered(plain.clone(), 25.0)).unwrap(); + assert_eq!(old.as_object_mut().unwrap().remove("brightness_jitter"), Some(serde_json::json!(25.0))); + let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.brightness_jitter, 0.0, "a brush saved without the key reads as 0"); + let mut with = v.clone(); + with["brightness_jitter"] = serde_json::json!(25.0); + let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.brightness_jitter, 25.0); + // Values outside 0..100 are clamped. + for (given, kept) in [(250.0, 100.0), (-5.0, 0.0)] { + let mut v = v.clone(); + v["brightness_jitter"] = serde_json::json!(given); + let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.brightness_jitter, kept, "{given}"); + } +} + +#[test] +fn brightness_jitter_moves_after_the_colorization_in_each_model() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + let jittered_fills = |art: Color, colorization: Colorization, amount: f64, key: &StrokeLayer| { + fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(art, colorization, 0.0, 0.0), amount), &path, key)) + }; + // Tints: black art takes the blue stroke color, whose brightness then moves. + let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + let hsb: Vec<[f32; 3]> = jittered_fills(Color::BLACK, Colorization::Tints, 30.0, &blue).iter().map(rgb_hsb).collect(); + assert!(!hsb.is_empty() && hsb.iter().all(|[h, s, v]| hue_gap(*h, 240.0) < 1e-3 && near(f64::from(*s), 1.0, 1e-4) && *v >= 0.6999), "{hsb:?}"); + assert!(hsb.iter().any(|[_, _, v]| *v < 0.97), "{hsb:?}"); + // White, black and grays move too, and stay neutral. RGB white gets darker. + let white: Vec<[f32; 3]> = jittered_fills(Color::WHITE, Colorization::None, 30.0, &stroke(1.0)).iter().map(rgb_hsb).collect(); + assert!(white.iter().all(|[_, s, v]| *s == 0.0 && *v >= 0.6999) && white.iter().any(|[_, _, v]| *v < 0.95), "{white:?}"); + // A gray's ink moves within 20 points of its 40%. + let gray = StrokeLayer::new(Paint::solid(Color::gray(0.4)), 1.0); + let grays = jittered_fills(Color::BLACK, Colorization::Tints, 20.0, &gray); + assert!(grays.iter().all(|c| matches!(*c, Color::Gray { k } if (k - 0.4).abs() <= 0.2001)), "{grays:?}"); + assert!(grays.iter().any(|c| *c != Color::gray(0.4)), "{grays:?}"); + // Black ink alone stays black ink alone, lighter by its K. + let k_only = jittered_fills(Color::cmyk(0.0, 0.0, 0.0, 1.0), Colorization::None, 30.0, &stroke(1.0)); + assert!(k_only.iter().all(|c| matches!(*c, Color::Cmyk { c, m, y, k } if c == 0.0 && m == 0.0 && y == 0.0 && k >= 0.6999)), "{k_only:?}"); + assert!(k_only.iter().any(|c| matches!(*c, Color::Cmyk { k, .. } if k < 0.97)), "{k_only:?}"); + // A process color with room in its K moves by its K and keeps its C, M and Y. + let cmyk = jittered_fills(Color::cmyk(0.0, 0.6, 0.6, 0.25), Colorization::None, 20.0, &stroke(1.0)); + assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 0.6, 0.6, 0.25)), "{cmyk:?}"); + for c in &cmyk { + let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") }; + assert!(c == 0.0 && m == 0.6 && y == 0.6 && (k - 0.25).abs() <= 0.2001, "{c} {m} {y} {k}"); + } + // One brighter than its C, M and Y show with no K loses its K and takes less ink, its hue and + // saturation kept (full magenta and yellow, cyan the brightness). + let deep = jittered_fills(Color::cmyk(0.4, 1.0, 1.0, 0.0), Colorization::None, 30.0, &stroke(1.0)); + let mut ways = (false, false); + for c in &deep { + let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") }; + assert!(near(f64::from(m), 1.0, 1e-5) && near(f64::from(y), 1.0, 1e-5), "{c} {m} {y} {k}"); + if k > 0.0 { + assert!(c == 0.4 && k <= 0.5001, "darker: {c} {k}"); + ways.0 = true; + } else { + assert!((0.0999..=0.4).contains(&c), "brighter: {c}"); + ways.1 |= c < 0.4; + } + } + assert!(ways.0 && ways.1, "the copies move both ways: {deep:?}"); + // A Lab color keeps its a and b; its lightness moves within 20 of its 50. + let lab = jittered_fills(Color::lab(50.0, 40.0, 30.0), Colorization::None, 20.0, &stroke(1.0)); + assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}"); + assert!(lab.iter().all(|c| matches!(*c, Color::Lab { l, a, b } if a == 40.0 && b == 30.0 && (l - 50.0).abs() <= 20.001)), "{lab:?}"); +} + +/// A swatch-linked color already at the end a copy's saturation or brightness moves toward stays as +/// it is and keeps its link; the copies that move it lose the link. +#[test] +fn jitter_at_a_limit_keeps_the_swatch_link() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + // Full red (full saturation and brightness), full magenta and yellow ink, and a Lab red whose a + // is at its largest: saturation that grows and brightness that grows leave them as they are. + for (color, saturation_jitter, brightness_jitter) in [ + (Color::rgb(1.0, 0.0, 0.0), 50.0, 0.0), + (Color::cmyk(0.0, 1.0, 1.0, 0.0), 50.0, 0.0), + (Color::lab(50.0, 127.0, 0.0), 50.0, 0.0), + (Color::rgb(1.0, 0.0, 0.0), 0.0, 50.0), + (Color::lab(100.0, 20.0, 10.0), 0.0, 50.0), + ] { + let linked = Paint::Solid { color, swatch: Some("Spot".into()), tint: 1.0 }; + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(linked.clone()); + let mut s = Scatter { art, saturation_jitter, ..Default::default() }; + s.brightness_jitter = brightness_jitter; + let out = stroke_pieces(&doc, &Brush { name: "s".into(), kind: BrushKind::Scatter(s) }, &path, &stroke(1.0)); + let (mut kept, mut moved) = (0, 0); + for n in &out { + match n.appearance.fill_paint() { + p if p == linked => kept += 1, + Paint::Solid { color: c, swatch: None, .. } if c != color => moved += 1, + p => panic!("{color:?}: {p:?}"), + } + } + assert!(kept > 0 && moved > 0, "{color:?}: {kept} kept, {moved} moved"); + } +} + +/// A hue or saturation jitter too small to move a Lab color's components gives each copy the color +/// it had, and the copies keep the swatch link. +#[test] +fn jitter_too_small_to_change_a_color_keeps_the_swatch_link() { + let linked = Paint::Solid { color: Color::lab(50.0, 64.0, 0.0), swatch: Some("Spot".into()), tint: 1.0 }; + // 1e-50 degrees turns a and b by less than an f32 holds; 1e-6 points scales the chroma by + // 1 + 1.6e-8, which rounds back to the same f32 components. + type Jitter = fn(&mut [Node], f64, u64); + let jitters: [(&str, Jitter, f64); 2] = [("hue", crate::colorize::jitter_hues, 1e-50), ("saturation", crate::colorize::jitter_saturations, 1e-6)]; + for (name, jitter, amount) in jitters { + let mut copies: Vec = (0..8) + .map(|_| { + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(linked.clone()); + art + }) + .collect(); + jitter(&mut copies, amount, 7); + for n in &copies { + assert_eq!(n.appearance.fill_paint(), linked, "{name}"); + } + } +} + /// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its /// swatch links. #[test] @@ -2031,6 +2405,374 @@ fn art_brush_width_follows_tilt_bearing_and_rotation() { assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]); } +/// A pattern brush with `scale`, `scale_mode` and `scale_max`, its 10 × 4 pt side tile on `fit`. +fn scaled_pattern(fit: PatternFit, corners: bool, scale: f64, mode: Option, max: Option) -> Brush { + let mut b = pattern_brush(fit, corners); + if let BrushKind::Pattern(p) = &mut b.kind { + (p.scale, p.scale_mode, p.scale_max) = (scale, mode, max); + } + b +} + +/// The bounds of each piece, left to right. +fn piece_spans(out: &[Node]) -> Vec { + let mut spans: Vec = out.iter().filter_map(Node::geometric_bounds).collect(); + spans.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + spans +} + +/// Pattern Brush Options: with Scale on Pressure the tiles go from Scale at the lightest pen +/// pressure to the second scale at the heaviest, taller and longer along the stroke where the pen +/// pressed harder, and each Fit still fits them to the path. +#[test] +fn pattern_brush_scale_follows_the_pressure() { + let bp = line(0.0, 0.0, 200.0, 0.0); + let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st); + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + // 4 pt tall tiles at 50 %: 1 pt either side at the lightest; at 300 %: 6 pt at the heaviest. + let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp); + assert!(near(half_width(&out, 0.0, 1.0), 1.0, 0.1), "{}", half_width(&out, 0.0, 1.0)); + assert!(near(half_width(&out, 199.0, 200.0), 6.0, 0.2), "{}", half_width(&out, 199.0, 200.0)); + assert!(near(half_width(&out, 99.0, 101.0), 3.5, 0.2), "{}", half_width(&out, 99.0, 101.0)); + // Stretch to Fit fills the path, and the tiles grow longer along it. + let spans = piece_spans(&out); + assert!(near(bounds(&out).x0, 0.0, 1e-6) && near(bounds(&out).x1, 200.0, 1e-6), "{:?}", bounds(&out)); + assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{spans:?}"); + assert!(spans.last().unwrap().width() > 4.0 * spans[0].width(), "{spans:?}"); + // The stroke weight scales it. + let out = + draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &StrokeLayer { width: 2.0, ..ramp.clone() }); + assert!(near(half_width(&out, 199.0, 200.0), 12.0, 0.4), "{}", half_width(&out, 199.0, 200.0)); + // Without recorded pressure, half way between the two scales. + let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &stroke(1.0)); + assert!(near(bounds(&out).height(), 7.0, 1e-6), "{:?}", bounds(&out)); + // With an even pressure, Add Space with spacing places as many tiles as the one scale that + // pressure gives: the spacing counts when the tiles are counted again. + let even = pressed(vec![(0.0, 0.5), (1.0, 0.5)]); + let spaced = |mode: Option, max: Option| { + let mut b = scaled_pattern(PatternFit::AddSpace, false, if max.is_some() { 50.0 } else { 100.0 }, mode, max); + if let BrushKind::Pattern(p) = &mut b.kind { + p.spacing = 100.0; + } + piece_spans(&draw(&b, &even)).len() + }; + assert_eq!(spaced(Some(Variation::Pressure), Some(150.0)), spaced(None, None)); + // With spacing, Stretch to Fit still fills the path and Approximate Path still centers the + // tiles, with the gaps between them counted and none after the last. + for fit in [PatternFit::Stretch, PatternFit::Approximate] { + let mut b = scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + p.spacing = 50.0; + } + let spans = piece_spans(&draw(&b, &ramp)); + let (first, last) = (spans[0], spans[spans.len() - 1]); + assert!(spans.len() > 1 && near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{fit:?}: {spans:?}"); + if fit == PatternFit::Stretch { + assert!(near(first.x0, 0.0, 1e-6) && near(last.x1, 200.0, 1e-6), "{spans:?}"); + } + } + // Add Space to Fit keeps the tiles apart within the path; Approximate Path centers them on it. + for fit in [PatternFit::AddSpace, PatternFit::Approximate] { + let out = draw(&scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp); + let spans = piece_spans(&out); + assert!(spans.len() > 1 && spans.windows(2).all(|w| w[1].x0 >= w[0].x1 - 1e-6), "{fit:?}: {spans:?}"); + assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{fit:?}: {spans:?}"); + let (first, last) = (spans[0], spans[spans.len() - 1]); + if fit == PatternFit::AddSpace { + assert!(first.x0 >= -1e-6 && last.x1 <= 200.0 + 1e-6, "{spans:?}"); + } else { + assert!(near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{spans:?}"); + } + } +} + +/// Pattern Brush Options: Scale on Tilt, Bearing, Rotation or Stylus Wheel reads only its own +/// input, half way without it; Fixed, a mode without a second scale and equal scales draw as a +/// brush without the setting does. +#[test] +fn pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel() { + let bp = line(0.0, 0.0, 100.0, 0.0); + let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st); + let brush = |mode: Variation| scaled_pattern(PatternFit::Stretch, false, 50.0, Some(mode), Some(300.0)); + let wheel = |v: f64| StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, v), (1.0, v)] }), ..stroke(1.0) }; + // 4 pt tiles: 2 pt tall at 50 %, 12 pt at 300 %. + for (mode, st, height) in [ + (Variation::Tilt, posed(Some(0.0), None, None), 12.0), + (Variation::Tilt, posed(Some(1.0), None, None), 2.0), + (Variation::Bearing, posed(Some(0.5), Some(90.0), None), 9.5), + (Variation::Rotation, posed(None, None, Some(-90.0)), 4.5), + (Variation::StylusWheel, wheel(1.0), 12.0), + (Variation::StylusWheel, wheel(0.0), 2.0), + // Without its own input, half way. + (Variation::Tilt, posed(None, Some(90.0), Some(90.0)), 7.0), + (Variation::Bearing, posed(Some(0.0), None, Some(90.0)), 7.0), + (Variation::Rotation, posed(Some(0.0), Some(90.0), None), 7.0), + (Variation::StylusWheel, pressed(vec![(0.0, 1.0), (1.0, 1.0)]), 7.0), + (Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0)), 7.0), + ] { + let h = bounds(&draw(&brush(mode), &st)).height(); + assert!(near(h, height, 1e-6), "{mode:?}: {h}"); + } + // Fixed, a mode without a second scale, and a second scale equal to the first draw what the + // brush draws without them. + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + let plain = draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &ramp); + for (mode, max) in [(None, Some(300.0)), (Some(Variation::Pressure), None), (Some(Variation::Pressure), Some(50.0))] { + assert_eq!(draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, mode, max), &ramp), plain, "{mode:?} {max:?}"); + } + let saved = serde_json::to_value(scaled_pattern(PatternFit::Stretch, false, 50.0, None, None)).unwrap(); + assert!(saved.get("scale_mode").is_none() && saved.get("scale_max").is_none(), "{saved}"); + // A mode the scale does not take is read as Fixed, and the second scale is kept within range. + let lib = parse_library(&serde_json::json!([ + {"name": "a", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "random", "scale_max": 1e308}, + {"name": "b", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "stylusWheel", "scale_max": 0.0}, + ])); + let [BrushKind::Pattern(a), BrushKind::Pattern(b)] = [&lib[0].kind, &lib[1].kind] else { panic!("{lib:?}") }; + assert_eq!((a.scale_mode, a.scale_max, b.scale_mode, b.scale_max), (None, Some(10000.0), Some(Variation::StylusWheel), Some(1.0))); + // A stroke sets its own mode and second scale. + let mut own = serde_json::Map::new(); + own.insert("scale_mode".into(), serde_json::json!("pressure")); + own.insert("scale_max".into(), serde_json::json!(300.0)); + let edited = scaled_pattern(PatternFit::Stretch, false, 100.0, None, None).with_stroke_options(&own).unwrap(); + assert!(matches!(&edited.kind, BrushKind::Pattern(p) if p.scale_range() == (100.0, 300.0)), "{edited:?}"); +} + +/// A pattern brush whose scale follows the pen keeps its start, end and corner tiles at the scale +/// where they are, on open and closed paths, and stays finite at the ends of the scale's range. +#[test] +fn pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles() { + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + let doc = Document::new(1.0, 1.0); + // Start and end tiles, 6 × 4 pt: the start tile at the light end is smaller than the end tile. + let mut ends = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Pattern(p) = &mut ends.kind { + (p.start, p.end) = (Some(rect_art(6.0, 4.0)), Some(rect_art(6.0, 4.0))); + } + let out = stroke_pieces(&doc, &ends, &line(0.0, 0.0, 200.0, 0.0), &ramp); + let (start, end) = (out[0].geometric_bounds().unwrap(), out[1].geometric_bounds().unwrap()); + assert!(near(start.x0, 0.0, 1e-6) && near(end.x1, 200.0, 1e-6), "{start:?} {end:?}"); + assert!(start.width() < 3.5 && end.width() > 17.0 && start.height() < end.height() / 4.0, "{start:?} {end:?}"); + // A closed rectangle with corner tiles, on each Fit, and the scale's range at its ends. + let mut rect = BezPath::new(); + rect.move_to((0.0, 0.0)); + rect.line_to((100.0, 0.0)); + rect.line_to((100.0, 60.0)); + rect.line_to((0.0, 60.0)); + rect.close_path(); + for fit in [PatternFit::Stretch, PatternFit::AddSpace, PatternFit::Approximate] { + for (scale, max) in [(50.0, 300.0), (1.0, 10000.0), (10000.0, 1.0)] { + for bp in [&rect, &line(0.0, 0.0, 3.0, 0.0)] { + let b = scaled_pattern(fit, true, scale, Some(Variation::Pressure), Some(max)); + let out = stroke_pieces(&doc, &b, bp, &ramp); + assert!(!out.is_empty(), "{fit:?} {scale} {max}"); + let r = bounds(&out); + assert!([r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()), "{fit:?} {scale} {max}: {r:?}"); + } + } + } + // On the rectangle the corner tiles grow with the pressure: the first corner's tile is smaller + // than the last one's. + let b = scaled_pattern(PatternFit::Stretch, true, 50.0, Some(Variation::Pressure), Some(300.0)); + let out = stroke_pieces(&doc, &b, &rect, &ramp); + let fixed = stroke_pieces(&doc, &scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &rect, &ramp); + assert_ne!(out, fixed); + let corner = |n: &Node| n.geometric_bounds().map_or(0.0, |r| r.width().max(r.height())); + let corners: Vec = out.iter().take(4).map(corner).collect(); + assert!(corners[0] < corners[3], "{corners:?}"); + // The side tiles start half the corner tile beside them away from the corner: 1.5 pt from the + // first corner, where the 6 pt corner tile is drawn at 50 %, not half the largest corner tile. + let first_side = out.get(4).and_then(Node::geometric_bounds); + assert!(first_side.is_some_and(|r| near(r.x0, 1.5, 1e-3)), "{first_side:?}"); +} + +/// A start or end tile whose scale follows the pen is placed where it is as long as the scale at +/// its middle, even when the scale rises again further along and the tile would not fit at the +/// whole run's length. +#[test] +fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_falls_back() { + let doc = Document::new(1.0, 1.0); + let bp = line(0.0, 0.0, 100.0, 0.0); + // From 100 % to 10000 %: 300 % from 5 to 20 pt, 10000 % from 50 pt on; mirrored for the end. + let q = 2.0 / 99.0; + for (start, points, span) in [ + (true, vec![(0.0, 0.0), (0.05, q), (0.2, q), (0.5, 1.0), (1.0, 1.0)], (0.0, 18.0)), + (false, vec![(0.0, 1.0), (0.5, 1.0), (0.8, q), (0.95, q), (1.0, 0.0)], (82.0, 100.0)), + ] { + let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(10000.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + let tile = Some(rect_art(6.0, 4.0)); + (p.start, p.end) = if start { (tile, None) } else { (None, tile) }; + } + // The 6 pt tile at 300 %: 18 pt long, its middle where the scale is 300 %. + let out = stroke_pieces(&doc, &b, &bp, &pressed(points)); + let r = out.first().and_then(Node::geometric_bounds); + assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}"); + } + // 400 % at the start, 100 % from 15 to 20 pt, 400 % from 40 pt on, mirrored for the end: a 30 pt + // tile at 100 % fits at its middle, although at the scale at its first length's middle it is as + // long as that length. + for (start, points, span) in [ + (true, vec![(0.0, 1.0), (0.15, 0.0), (0.2, 0.0), (0.4, 1.0), (1.0, 1.0)], (0.0, 30.0)), + (false, vec![(0.0, 1.0), (0.6, 1.0), (0.8, 0.0), (0.85, 0.0), (1.0, 1.0)], (70.0, 100.0)), + ] { + let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(400.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + let tile = Some(rect_art(30.0, 4.0)); + (p.start, p.end) = if start { (tile, None) } else { (None, tile) }; + } + let out = stroke_pieces(&doc, &b, &bp, &pressed(points)); + let r = out.first().and_then(Node::geometric_bounds); + assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}"); + } +} + +/// How far from y = 0 the outlines under `nodes` reach where they cross the vertical line at `x`. +fn reach_at(nodes: &[Node], x: f64) -> f64 { + let mut reach = 0.0f64; + for n in nodes { + n.walk(&mut |c| { + for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) { + for i in 0..sp.segment_count() { + let s = sp.segment(i); + let (a, b, c, d) = (s.p0.x, s.p1.x, s.p2.x, s.p3.x); + let roots = kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (c - 2.0 * b + a), d - 3.0 * c + 3.0 * b - a); + for t in roots.into_iter().filter(|t| (-1e-9..=1.0 + 1e-9).contains(t)) { + reach = reach.max(kurbo::ParamCurve::eval(&s, t.clamp(0.0, 1.0)).y.abs()); + } + } + } + }); + } + reach +} + +/// A pattern tile whose scale follows the pen is as tall as the scale at a short peak of the +/// pressure, even where the peak falls between the positions the bent outline is checked at. +#[test] +fn pattern_brush_scale_from_the_pen_keeps_a_short_peak() { + let doc = Document::new(1.0, 1.0); + let b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(300.0)); + // One 10 × 4 pt tile on a 10 pt path: 100 % (2 pt either side) but for a peak at 2.2 pt, where + // the scale reaches 300 % (6 pt either side). + let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]); + let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 10.0, 0.0), &peak); + // At the peak 300 %, half way up it 200 %, and 100 % on either side of it. + for (x, want) in [(2.2, 6.0), (2.15, 4.0), (2.25, 4.0), (1.0, 2.0), (2.05, 2.0), (2.4, 2.0), (8.0, 2.0)] { + assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x)); + } +} + +/// An art brush whose width follows the pen is as wide as the pen gives at a short peak of the +/// pressure, even where the peak falls between the positions the bent outline is checked at. +#[test] +fn art_brush_width_from_the_pen_keeps_a_short_peak() { + let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + if let BrushKind::Art(a) = &mut b.kind { + (a.width, a.width_mode, a.width_max) = (100.0, Some(Variation::Pressure), Some(300.0)); + } + // 4 pt art on a 100 pt path: 2 pt either side but for a peak at 22 pt, where it is 6 pt. + let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]); + let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &peak); + for (x, want) in [(22.0, 6.0), (21.5, 4.0), (22.5, 4.0), (10.0, 2.0), (20.5, 2.0), (24.0, 2.0), (80.0, 2.0)] { + assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x)); + } +} + +/// A pen recording sampled many times along a straight ramp draws as many anchors as the ramp's +/// two ends do: samples that leave the scale on the same straight course are not split at. +#[test] +fn pen_samples_on_a_straight_ramp_add_no_anchors() { + let doc = Document::new(1.0, 1.0); + let bp = line(0.0, 0.0, 1000.0, 0.0); + let ramp = |n: usize| pressed((0..=n).map(|i| (i as f64 / n as f64, i as f64 / n as f64)).collect()); + let anchors = |out: &[Node]| { + let mut count = 0; + for n in out { + n.walk(&mut |c| count += c.path_data().map_or(0, |p| p.subpaths.iter().map(|s| s.anchors.len()).sum::())); + } + count + }; + let pattern = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)); + let mut art = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + if let BrushKind::Art(a) = &mut art.kind { + (a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::Pressure), Some(300.0)); + } + for b in [&pattern, &art] { + let (few, many) = (stroke_pieces(&doc, b, &bp, &ramp(1)), stroke_pieces(&doc, b, &bp, &ramp(2000))); + assert_eq!(anchors(&many), anchors(&few), "{}", b.name); + } +} + +/// On a closed path, a tile that Approximate Path starts before the path's start takes the scale +/// recorded at the end of the stroke there, where the tile is drawn. +#[test] +fn pattern_brush_scale_from_the_pen_wraps_before_a_closed_paths_start() { + let doc = Document::new(1.0, 1.0); + let b = scaled_pattern(PatternFit::Approximate, false, 50.0, Some(Variation::Pressure), Some(300.0)); + // Light over the first 90 % of the stroke, heavy at its end. + let st = pressed(vec![(0.0, 0.0), (0.9, 0.0), (1.0, 1.0)]); + let mut before = 0; + for r in (100..=120).map(f64::from) { + // A circle of radius `r` as 720 sides, from (r, 0) on towards +y. + let mut bp = BezPath::new(); + bp.move_to((r, 0.0)); + for i in 1..720 { + let a = std::f64::consts::TAU * f64::from(i) / 720.0; + bp.line_to((r * a.cos(), r * a.sin())); + } + bp.close_path(); + let out = stroke_pieces(&doc, &b, &bp, &st); + let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("{r}: no tiles") }; + if first.y0 < -0.5 { + // The 4 pt tall tile is 2 pt tall at the light 50 % and nearly 12 pt at the heavy end. + before += 1; + assert!(first.x1 > r + 3.0, "{r}: {first:?}"); + } + } + assert!(before > 0, "no first tile starts before the path's start"); +} + +/// On a closed path, a tile over the path's start follows the scale on both sides of the start, +/// even when the scale is the same at the tile's ends, its middle and every pen sample within it. +#[test] +fn pattern_brush_scale_from_the_pen_changes_where_a_closed_path_wraps_round() { + let doc = Document::new(1.0, 1.0); + let mut b = scaled_pattern(PatternFit::Approximate, false, 100.0, Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + p.side = rect_art(54.0, 4.0); + } + // A closed path 256 pt long without corners, from (0, 0) along +x: its sides in each quarter + // turn, and the same turned three more times. + let quarter = [(28.0, 0.0), (12.0, 5.0), (4.0, 3.0), (3.0, 4.0), (5.0, 12.0)]; + let mut bp = BezPath::new(); + let mut at = (0.0, 0.0); + bp.move_to(at); + for turn in 0..4 { + for &(x, y) in &quarter { + let (dx, dy) = match turn { + 0 => (x, y), + 1 => (-y, x), + 2 => (-x, -y), + _ => (y, -x), + }; + at = (at.0 + dx, at.1 + dy); + if at != (0.0, 0.0) { + bp.line_to(at); + } + } + } + bp.close_path(); + // 100 % up to 4 pt before the end, rising to 300 % at the end. Approximate Path places five + // 54 pt tiles, the first from 7 pt before the start: at 100 % at both its ends, its middle and + // the samples at 4 pt before the start and at the start, but larger from 4 pt before it. + let st = pressed(vec![(0.0, 0.0), (252.0 / 256.0, 0.0), (1.0, 1.0)]); + let out = stroke_pieces(&doc, &b, &bp, &st); + let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("no tiles") }; + // The 4 pt tall tile is 2 pt either side of the path at 100 %, and 5 pt at 1 pt before the + // start, where the scale is 250 %. + assert!(first.y0 < -3.5, "{first:?}"); +} + /// Definitions from files and commands are kept within their ranges. #[test] fn sanitize_keeps_values_within_their_ranges() { diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 7659c96330..3cfa54db21 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -40,23 +40,32 @@ const MASK_STEPS: usize = 32; /// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document /// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than /// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord -/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`. -/// Text, images and symbol instances can't bend and are dropped. The art of a linked opacity mask -/// bends with the object it masks. -pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option { +/// is longer than `max_du` along x, as it always was. Both routes also split the art where it +/// crosses each of `breaks` (art x, in order), so a turn of the map there is not stepped over. +/// Stroke widths scale by `width_scale`. Text, images and symbol instances can't bend and are +/// dropped. The art of a linked opacity mask bends with the object it masks. +pub(crate) fn warp_node( + n: &Node, + f: &dyn Fn(Point) -> Point, + flat_tol: f64, + max_du: f64, + doc_tol: f64, + width_scale: f64, + breaks: &[f64], +) -> Option { let mut out = n.clone(); out.appearance.scale_strokes(width_scale); match &mut out.kind { NodeKind::Path { path, live, .. } => { *live = None; - *path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol)); + *path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol), breaks); if path.is_empty() { return None; } } NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => { let kids: Vec> = - children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect(); + children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale, breaks)).map(Arc::new).collect(); if kids.is_empty() { return None; } @@ -64,7 +73,7 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max } _ => return None, } - map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale)); + map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale, breaks)); Some(out) } @@ -80,12 +89,13 @@ fn map_mask(n: &mut Node, map: impl FnOnce(&Node) -> Option) { } /// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords -/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords. -fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData { +/// would, else the chords, both split at `breaks` ([`warp_node`]). Points `f` cannot place (not +/// finite) are left out of the chords. +fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64, breaks: &[f64]) -> PathData { let mut subs = vec![]; for sp in &p.subpaths { - let Some(dense) = densified(sp, flat_tol, max_du) else { continue }; - if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) { + let Some(dense) = densified(sp, flat_tol, max_du, breaks) else { continue }; + if let Some(fit) = fitted(sp, f, fit_tol, dense.len(), breaks) { subs.push(fit); continue; } @@ -98,8 +108,9 @@ fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f6 } /// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along -/// x, in art space: the points the chord route maps. `None` below two points. -fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option> { +/// x, in art space, with a point where a chord crosses each of `breaks` (art x, in order): the +/// points the chord route maps. `None` below two points. +fn densified(sp: &SubPath, flat_tol: f64, max_du: f64, breaks: &[f64]) -> Option> { let mut bp = BezPath::new(); sp.to_bezpath_into(&mut bp); let mut pts = vec![]; @@ -118,16 +129,57 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option> { let mut dense = vec![*pts.first()?]; for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() { let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB); + // The breaks the chord crosses, as parameters along it in order, go in among the even ones. + let mut cuts: Vec = crossed(breaks, a.x, b.x).iter().map(|&x| (x - a.x) / (b.x - a.x)).collect(); + cuts.sort_by(f64::total_cmp); + let mut cuts = cuts.into_iter().peekable(); for j in 1..=k { + let even = j as f64 / k as f64; + while let Some(t) = cuts.next_if(|&t| t < even) { + dense.push(a.lerp(b, t)); + } if sp.closed && i == segs - 1 && j == k { break; } - dense.push(a.lerp(b, j as f64 / k as f64)); + dense.push(a.lerp(b, even)); } } Some(dense) } +/// The values of `breaks` (in order) strictly between `a` and `b`, either way round. +fn crossed(breaks: &[f64], a: f64, b: f64) -> &[f64] { + let (lo, hi) = (a.min(b), a.max(b)); + let from = breaks.partition_point(|&x| x <= lo); + let to = from + breaks[from..].partition_point(|&x| x < hi); + &breaks[from..to] +} + +/// The parameters of `c` (in order, strictly between its ends) where its x is one of `breaks`; +/// `line` when `c` is a line with its handles at thirds, whose x runs evenly. +fn crossings(c: &CubicBez, line: bool, breaks: &[f64]) -> Vec { + let xs = [c.p0.x, c.p1.x, c.p2.x, c.p3.x]; + let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| (lo.min(x), hi.max(x))); + let inside = crossed(breaks, lo, hi); + if inside.is_empty() { + return vec![]; + } + let [a, b, cc, d] = xs; + let mut ts: Vec = vec![]; + for &x in inside { + if line { + ts.push((x - a) / (d - a)); + } else { + ts.extend(kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (cc - 2.0 * b + a), d - 3.0 * cc + 3.0 * b - a)); + } + } + // Pieces are no shorter than the step the fit reads their ends' directions over. + ts.retain(|t| t.is_finite() && *t > FIT_DT && *t < 1.0 - FIT_DT); + ts.sort_by(f64::total_cmp); + ts.dedup_by(|t, prev| *t - *prev <= FIT_DT); + ts +} + /// Times an art segment is halved at most while looking for cubics that fit it. const FIT_DEPTH: u32 = 12; /// Parameter step of the finite differences that stand in for the bend's derivative. @@ -156,7 +208,10 @@ fn fit_tol(doc_tol: f64) -> f64 { /// bend at the same parameters, so the distance measured is never less than the true one. The /// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out /// on a map that never fits; the depth and the anchor count bound this one. -fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option { +/// +/// A segment is first split where its x crosses one of `breaks` (art x, in order), so a turn of +/// the map there lands on an anchor rather than between the checked positions. +fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize, breaks: &[f64]) -> Option { if !(tol.is_finite() && tol > 0.0) { return None; } @@ -174,7 +229,11 @@ fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Op // A line's handles sit on its ends, which stalls its parameter there; thirds keep it even. let c = if line { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c }; let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite()); - fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?; + let mut t0 = 0.0; + for t1 in crossings(&c, line, breaks).into_iter().chain([1.0]) { + fit_into(&at, (t0, t1), line, tol, FIT_DEPTH, &mut bp, &mut room)?; + t0 = t1; + } } if sp.closed { bp.close_path(); @@ -316,6 +375,16 @@ impl AlongMap { fn max_scale(&self) -> f64 { (0..3).map(|i| self.slope(i).abs()).fold(1e-6, f64::max) } + + /// The art x (offset from the art's left edge) that [`AlongMap::at`] takes to arc length `s`, + /// when a piece with width spans it. + fn x_at(&self, s: f64) -> Option { + (0..3).find_map(|i| { + let ((x0, x1), (s0, s1)) = ((self.xs[i], self.xs[i + 1]), (self.ss[i], self.ss[i + 1])); + let spans = x1 - x0 > 1e-12 && (s1 - s0).abs() > 1e-12 && s0.min(s1) <= s && s <= s0.max(s1); + spans.then(|| x0 + (s - s0) / (s1 - s0) * (x1 - x0)) + }) + } } /// The affine that reproduces `f` over `b` to within `tol`, if one does. @@ -414,12 +483,14 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option f64) -> Option { +/// of each object in the art take the factor at the middle of the object. `marks` are the arc +/// lengths (in order) of the recorded pen samples `widen` runs in a straight line between; the art +/// is split where `widen` turns at one by more than the bent outline's tolerance ([`pen_breaks`]). +fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64, marks: &[f64]) -> Option { let cy = b.center().y; let x0 = b.x0; let f = move |p: Point| { @@ -430,7 +501,45 @@ fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, wid let art = widen_strokes(art, &factor); let scale = along.max_scale().max(cross.abs()).max(1e-6); let flat_tol = tolerance(b.height().max(b.width()) * scale) / scale; - warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs()) + // A change of `dw` in `widen` moves the art's top and bottom edges `dw × reach` across. + let reach = b.height() / 2.0 * cross.abs(); + let mut breaks: Vec = + pen_breaks(marks, along.span(), widen, fit_tol(flat_tol * scale) / reach).into_iter().filter_map(|s| along.x_at(s)).map(|x| x + x0).collect(); + breaks.sort_by(f64::total_cmp); + breaks.dedup(); + warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &breaks) +} + +/// The arc lengths among `marks` (in order) strictly within `(s0, s1)` at which the art is split: +/// those where `widen` is more than `tol` from the straight line between the ones kept on either +/// side (the span's ends to begin with), chosen by splitting at the farthest one until every +/// sample left out is within `tol` of that line. `widen` runs straight between samples, so it +/// is then within `tol` of the line between kept samples all along, and samples on a straight +/// course add no splits. +fn pen_breaks(marks: &[f64], (s0, s1): (f64, f64), widen: &dyn Fn(f64) -> f64, tol: f64) -> Vec { + if !(s1 > s0 && tol > 0.0) { + return vec![]; + } + let inside = { + let from = marks.partition_point(|&s| s <= s0); + &marks[from..from + marks[from..].partition_point(|&s| s < s1)] + }; + if inside.is_empty() { + return vec![]; + } + let pts: Vec<(f64, f64)> = std::iter::once(s0).chain(inside.iter().copied()).chain([s1]).map(|s| (s, widen(s))).collect(); + let mut keep = vec![false; pts.len()]; + let mut spans = vec![(0, pts.len() - 1)]; + while let Some((i, j)) = spans.pop() { + let ((sa, wa), (sb, wb)) = (pts[i], pts[j]); + let off = |&(s, w): &(f64, f64)| (w - if sb > sa { wa + (wb - wa) * (s - sa) / (sb - sa) } else { wa }).abs(); + let far = (i + 1..j).map(|k| (k, off(&pts[k]))).filter(|&(_, d)| d > tol).max_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((k, _)) = far { + keep[k] = true; + spans.extend([(i, k), (k, j)]); + } + } + pts.iter().zip(keep).filter(|&(_, k)| k).map(|(p, _)| p.0).collect() } /// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they @@ -465,8 +574,17 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> { bounds.windows(2).map(|w| (w[0], w[1])).collect() } -/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1. -fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, Rect), cross: f64, widen: &dyn Fn(f64) -> f64) -> Option { +/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1 (`marks` +/// as [`bend_widened`] takes them). +fn art_on_run( + t: &Track, + (s0, s1): (f64, f64), + a: &ArtBrush, + (art, b): (&Node, Rect), + cross: f64, + widen: &dyn Fn(f64) -> f64, + marks: &[f64], +) -> Option { let l = s1 - s0; if l <= 1e-9 { return None; @@ -489,7 +607,7 @@ fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, R } } }; - bend_widened(t, art, b, along, cross, widen) + bend_widened(t, art, b, along, cross, widen, marks) } /// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing @@ -515,9 +633,13 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5); (light + (heavy - light) * p) / width }; + let marks = match a.width_mode { + Some(m) if light != heavy && width > 0.0 => pen_marks(stroke, m, l), + _ => vec![], + }; let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] }; for run in runs { - if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen) { + if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen, &marks) { out.push(n); } } @@ -649,6 +771,253 @@ fn tile_on(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, cross: f64) -> Opti bend(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), cross) } +/// A tile placed on [s0, s1] of the track, `k(s)` across at arc length `s` when the scale varies +/// (`marks`: the arc lengths of the recorded pen samples in order, between which the scale runs +/// in a straight line), else `k` at the middle of the span across all of it ([`tile_on`]), as it +/// is too when the scale is the same at both ends of the span, at every sample within it and, at +/// a closed track's start within it, on both sides of the start. +fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) -> f64, marks: Option<&[f64]>) -> Option { + let mid = k((s0 + s1) / 2.0); + // Only the samples within the span are looked at. + let within = |marks: &[f64]| { + let from = marks.partition_point(|&s| s <= s0); + let to = from + marks[from..].partition_point(|&s| s < s1); + marks[from..to].iter().all(|&s| k(s) == mid) + }; + // A closed track's scale goes from the one at its end to the one at its start where it wraps + // round, so a span over its start (or a track's length before or after it) takes both. + let l = t.len(); + let seam = t.closed && l > 0.0 && (s0 / l).ceil() <= (s1 / l).floor(); + let ends = || !seam || (k(0.0) == mid && k(l) == mid); + let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && within(marks) && ends(); + if mid <= 0.0 || marks.is_none_or(even) { + return tile_on(t, tile, s0, s1, mid); + } + bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid, marks.unwrap_or_default()) +} + +/// The most side tiles a run of a pattern brush places. +const MAX_TILES: usize = 20000; + +/// How many times a pattern brush whose scale varies measures its side tiles again where the fit +/// puts them. +const REFITS: usize = 3; + +/// How many times a pattern brush whose scale varies halves the range a start or end tile's +/// length lies in. +const END_SOLVE_STEPS: usize = 48; + +/// How many evenly spaced lengths a pattern brush whose scale varies tries for a start or end +/// tile before it halves the range the tile's length lies in. +const END_SCAN_STEPS: usize = 64; + +/// The side tiles of a pattern brush on a run `avail` long from `a` when the scale varies along +/// it: each tile's length and the gap after it, as `natural` gives them at the tile's start, and +/// how many tiles fit whole and what fraction of the next one fits after them. The tiles include +/// that next one when there is room for part of it. +fn varied_tiles(a: f64, avail: f64, natural: &dyn Fn(f64) -> (f64, f64)) -> (Vec<(f64, f64)>, f64) { + let mut tiles = vec![]; + let mut pos = 0.0; + while tiles.len() < MAX_TILES { + let (w, g) = natural(a + pos); + if !(w > 1e-9 && w.is_finite() && g.is_finite() && g >= 0.0) { + break; + } + tiles.push((w, g)); + if pos + w > avail { + let whole = (tiles.len() - 1) as f64; + return (tiles, whole + ((avail - pos + g) / (w + g)).clamp(0.0, 1.0)); + } + pos += w + g; + } + let whole = tiles.len() as f64; + (tiles, whole) +} + +/// The size factor of a pattern brush's tiles at `weight` where its scale's pen input is `p` +/// (0 at the first scale, 1 at the second). +fn pattern_scale_at(pb: &PatternBrush, weight: f64, p: f64) -> f64 { + let (light, heavy) = pb.scale_range(); + weight * (light + (heavy - light) * p).max(1.0) / 100.0 +} + +/// A pattern brush's size factor on `stroke` at `weight`, and whether it varies along the stroke. +/// A stroke with no recording of the input the scale follows is drawn at one scale, the one that +/// input's missing value gives. +fn pattern_scale(pb: &PatternBrush, weight: f64, stroke: &StrokeLayer) -> (f64, bool) { + let (light, heavy) = pb.scale_range(); + match pb.scale_mode { + Some(m) if light != heavy && pen_recorded(stroke, m) => (weight * pb.scale.max(1.0) / 100.0, true), + Some(m) if light != heavy => (pattern_scale_at(pb, weight, PenAt::of(stroke, 0.0).control(m).unwrap_or(0.5)), false), + _ => (weight * pb.scale.max(1.0) / 100.0, false), + } +} + +/// The length of a start or end tile `width` wide at its art's size, at the scale `k_mid(w)` at +/// the middle of the tile when it is `w` long: the shortest length that is as long as the scale at +/// its own middle. The scale can rise and fall along the stroke, so the lengths up to `room` are +/// tried in order (evenly spaced ones, and `breaks`, the lengths whose middle falls on a recorded +/// pen sample), and the range between the last one the tile is too long for and the first one it +/// fits is halved. A tile that fits at no length up to `room` gets the length it needs at `room`, +/// longer than `room`. `breaks` is `None` when the scale is the same along the whole track, and +/// the tile then takes its length at that scale. +fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64, breaks: Option<&[f64]>) -> f64 { + let length = |w: f64| width * k_mid(w); + let first = length(0.0); + let Some(breaks) = breaks.filter(|_| !room.is_nan() && room > 0.0) else { + return first; + }; + let mut tries: Vec = (1..=END_SCAN_STEPS).map(|i| room * i as f64 / END_SCAN_STEPS as f64).collect(); + tries.extend(breaks.iter().copied().filter(|&w| w > 0.0 && w < room)); + tries.sort_by(f64::total_cmp); + let Some(i) = tries.iter().position(|&w| length(w) <= w) else { + return length(room); + }; + let (mut short, mut long) = (if i == 0 { 0.0 } else { tries[i - 1] }, tries[i]); + for _ in 0..END_SOLVE_STEPS { + let mid = (short + long) / 2.0; + if length(mid) > mid { + short = mid; + } else { + long = mid; + } + } + long +} + +/// Where along a track `l` long `stroke` recorded the pen input `mode` follows: each sample at its +/// arc length, and again a track's length before and after it, for tiles of a closed track that +/// wrap round, in order. +fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec { + let points = match mode { + Variation::Fixed | Variation::Random => None, + Variation::Pressure => stroke.pressure.as_ref().map(|p| &p.points), + Variation::Tilt => stroke.tilt.as_ref().map(|p| &p.points), + Variation::Bearing => stroke.bearing.as_ref().map(|p| &p.points), + Variation::Rotation => stroke.rotation.as_ref().map(|p| &p.points), + Variation::StylusWheel => stroke.wheel.as_ref().map(|p| &p.points), + }; + let mut marks: Vec = points.into_iter().flatten().flat_map(|&(f, _)| [f * l - l, f * l, f * l + l]).collect(); + marks.sort_by(f64::total_cmp); + marks +} + +/// Whether `stroke` recorded the pen input `mode` follows. +fn pen_recorded(stroke: &StrokeLayer, mode: Variation) -> bool { + match mode { + Variation::Fixed | Variation::Random => false, + Variation::Pressure => stroke.pressure.is_some(), + Variation::Tilt => stroke.tilt.is_some(), + Variation::Bearing => stroke.bearing.is_some(), + Variation::Rotation => stroke.rotation.is_some(), + Variation::StylusWheel => stroke.wheel.is_some(), + } +} + +/// Leaves out or adds tiles at the end of `tiles` (each a length and the gap after it) once they +/// have been measured again: with `add_space` as many as fit in `avail` with the gaps between +/// them, at least one, otherwise the count whose lengths and gaps between them come nearest to +/// `avail`. An added tile is +/// `natural(s)` long at `s` from the run's start. +fn recount(tiles: &mut Vec<(f64, f64)>, avail: f64, add_space: bool, natural: &dyn Fn(f64) -> (f64, f64)) { + let mut length: f64 = tiles.iter().map(|t| t.0).sum(); + let mut gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum()); + // How much of the run the tiles and the spacing between them take. + let run = |length: f64, gaps: f64| length + gaps; + while let [.., (_, before), (w, _)] = tiles.as_slice() { + let (w, before) = (*w, *before); + let (now, without) = (run(length, gaps), run(length - w, gaps - before)); + let drop = if add_space { now > avail } else { (without - avail).abs() < (now - avail).abs() }; + if !drop { + break; + } + tiles.pop(); + length -= w; + gaps -= before; + } + while tiles.len() < MAX_TILES { + let last_gap = tiles.last().map_or(0.0, |t| t.1); + let now = run(length, gaps); + let (w, g) = natural(run(length, gaps + last_gap)); + if w.is_nan() || w <= 1e-9 { + break; + } + let with = run(length + w, gaps + last_gap); + let add = if add_space { with <= avail } else { (with - avail).abs() < (now - avail).abs() }; + if !add { + break; + } + tiles.push((w, g)); + length += w; + gaps += last_gap; + } +} + +/// A pattern brush's side tiles on the run `avail` long from `a` of `t` (`marks` as +/// [`tile_scaled`] takes them), at the scale `k(s)` at +/// arc length `s` ([`varied_tiles`]), fitted as `pb.fit` says: Stretch scales the lengths and gaps +/// to fill the run, Add Space keeps the lengths and shares out what is left between the tiles +/// (around a lone tile), and Approximate keeps both and centers the tiles on the run. +fn varied_side_tiles( + out: &mut Budget, + t: &Track, + pb: &PatternBrush, + side: &(Node, Rect), + (a, avail): (f64, f64), + k: &dyn Fn(f64) -> f64, + marks: &[f64], +) { + let tw = side.1.width(); + // Each side tile and the gap after it as long as the scale at the tile's middle. + let natural = |s: f64| { + let w = tw * k(s + tw * k(s) / 2.0); + (w, w * pb.spacing.max(0.0) / 100.0) + }; + let (tiles, count) = varied_tiles(a, avail, &natural); + let n = match pb.fit { + PatternFit::AddSpace => count.floor(), + PatternFit::Stretch | PatternFit::Approximate => count.round(), + } + .max(1.0) as usize; + let mut tiles = tiles[..n.min(tiles.len())].to_vec(); + // How far the fit stretches the tiles and gaps, where the first tile starts, and the space + // between tiles when the fit sets it. + let fitted = |tiles: &[(f64, f64)]| { + let length: f64 = tiles.iter().map(|t| t.0).sum(); + // The gaps between the tiles: after every tile but the last. + let gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum()); + match pb.fit { + PatternFit::Stretch => (avail / (length + gaps), 0.0, None), + PatternFit::AddSpace if tiles.len() > 1 => (1.0, 0.0, Some(((avail - length) / (tiles.len() - 1) as f64).max(0.0))), + PatternFit::AddSpace => (1.0, (avail - tiles.first().map_or(0.0, |t| t.0)) / 2.0, None), + PatternFit::Approximate => (1.0, (avail - length - gaps) / 2.0, None), + } + }; + // The fit moves the tiles from where they were measured, so each is measured again at the + // middle of where the fit puts it, and the fit worked out again, a few times over. + for _ in 0..REFITS { + let (stretch, lead, space) = fitted(&tiles); + let mut s0 = a + lead; + for tile in &mut tiles { + let placed = tile.0 * stretch; + let w = tw * k(s0 + placed / 2.0); + s0 += placed + space.unwrap_or(tile.1 * stretch); + *tile = (w, w * pb.spacing.max(0.0) / 100.0); + } + recount(&mut tiles, avail, pb.fit == PatternFit::AddSpace, &|s| natural(a + s)); + } + let (stretch, lead, space) = fitted(&tiles); + let mut s0 = a + lead; + for &(w, g) in &tiles { + let w = w * stretch; + out.take(tile_scaled(t, side, s0, s0 + w, k, Some(marks))); + if out.full() { + break; + } + s0 += w + space.unwrap_or(g * stretch); + } +} + /// What a pattern brush draws at a corner: corner tile art (oriented, with its bounds), or what /// [`CornerSource`] gives. #[derive(Clone, Copy)] @@ -719,7 +1088,7 @@ fn auto_corner(t: &Track, i: usize, source: CornerSource, side: &(Node, Rect), k } let s = if tw > 1e-9 { len / tw } else { 1.0 }; let max_du = MAX_SEG / (2.0 * k * s.max(1.0)); - let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k); + let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k, &[]); // Art point → (distance along from the left edge, stretched to `len`, and offset across). let along = move |q: Point| { let (x, y) = local(q); @@ -803,10 +1172,15 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option { Some(Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(n)], clip: true })) } -pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec { +/// A pattern brush's tiles along `bp`. With a scale that follows the pen (its pressure, tilt, +/// bearing, rotation or wheel), the tiles are as tall as what `stroke` recorded at each point gives +/// (half way without a recording), each tile and the gap after it as long as the scale at its +/// middle, and each corner tile at the scale at its corner. +pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec { let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across); let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] }; - let k = weight * pb.scale.max(1.0) / 100.0; + let scale_at = |p: f64| pattern_scale_at(pb, weight, p); + let (k, varies) = pattern_scale(pb, weight, stroke); let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame)); let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame)); let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame)); @@ -825,6 +1199,17 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec if l <= 1e-9 { continue; } + // The scale at arc length `s` of the track; on a closed track a point before its start or + // past its end wraps round as `Track::frame` places it (its end itself keeps the scale at + // the end), and on an open track a point past either end takes the scale at that end. + let ks = |s: f64| { + if !varies { + return k; + } + let at = if t.closed && !(0.0..=l).contains(&s) { s.rem_euclid(l) } else { s.clamp(0.0, l) }; + scale_at(pb.scale_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5)) + }; + let marks = pb.scale_mode.filter(|_| varies).map(|m| pen_marks(stroke, m, l)); let corners = t.corner_positions(); // Corner tiles, centred on the corner and turned to the bisector. The path on each side of // a corner is shortened by `trims` (`None`: half the widest corner tile art). @@ -848,17 +1233,18 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec }; before.min(after) }; - for (ci, &(i, _)) in corners.iter().enumerate() { + for (ci, &(i, at)) in corners.iter().enumerate() { if out.full() { break; } + let kc = ks(at); let (a, b) = t.in_out(i); // Turning towards the left normal puts the tile's +y side on the inside. let tile = if a.cross(b) > 0.0 { inner_tile.or(outer.as_ref().map(Corner::Art)) } else { outer_tile.or(inner.as_ref().map(Corner::Art)) }; let (art, bb) = match tile { Some(Corner::Art(tile)) => tile, Some(Corner::Source(source)) => { - let (pieces, trim) = auto_corner(&t, i, source, &side, k, room(ci)); + let (pieces, trim) = auto_corner(&t, i, source, &side, kc, room(ci)); for n in pieces { out.take(Some(n)); } @@ -870,8 +1256,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec continue; } }; - trims.push(None); - corner_half = corner_half.max(bb.width() * k / 2.0); + // With a scale that varies, each corner's tile is its own size, so the path beside it + // is shortened by half of that tile. + trims.push(varies.then_some(bb.width() * kc / 2.0)); + corner_half = corner_half.max(bb.width() * kc / 2.0); // Inner and outer corner art is the corner that joins a side tile on its right to one // below it, so its arms point along +x and +y (as the flips leave them). The tile is // turned so that the line halving its arms lies on the line halving the sides at the @@ -881,7 +1269,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 }); let sides = b - a; let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x); - let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2()); + let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(kc) * Affine::translate(-bb.center().to_vec2()); let mut n = art.clone(); n.transform(xf, true); out.take(Some(n)); @@ -914,9 +1302,11 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec && ri == 0 && let Some(st) = &start { - let w = st.1.width() * k; + // As long as the scale at its middle. + let breaks: Option> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (m - a)).collect()); + let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0), breaks.as_deref()); if b - a > w { - out.take(tile_on(&t, st, a, a + w, k)); + out.take(tile_scaled(&t, st, a, a + w, &ks, marks.as_deref())); a += w; } } @@ -924,9 +1314,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec && ri + 1 == nruns && let Some(en) = &end { - let w = en.1.width() * k; + let breaks: Option> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (b - m)).collect()); + let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0), breaks.as_deref()); if b - a > w { - out.take(tile_on(&t, en, b - w, b, k)); + out.take(tile_scaled(&t, en, b - w, b, &ks, marks.as_deref())); b -= w; } } @@ -934,6 +1325,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec if avail <= 1e-6 { continue; } + if let Some(marks) = &marks { + varied_side_tiles(&mut out, &t, pb, &side, (a, avail), &ks, marks); + continue; + } let unit = tw + gap; match pb.fit { PatternFit::Stretch => { @@ -1120,7 +1515,7 @@ mod tests { let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy); let tol = tolerance(b.height().max(b.width())); let exact = traced(art, &f, 1000); - let chords: Vec = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect(); + let chords: Vec = densified(art, tol, MAX_SEG, &[]).expect("the tile flattens").into_iter().map(f).collect(); let curves = traced(sp, &|p| p, 200); let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact)); // Checked at eight points a piece, so a little room between them. @@ -1146,7 +1541,7 @@ mod tests { let allowed: usize = path .subpaths .iter() - .filter_map(|sp| densified(sp, 0.25, 1.5)) + .filter_map(|sp| densified(sp, 0.25, 1.5, &[])) .map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len()) .sum(); let finite = |n: &Node| match &n.kind { @@ -1168,7 +1563,7 @@ mod tests { calls.set(calls.get() + 1); if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) } }; - let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0); + let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0, &[]); assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get()); match (i, &out) { (3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"), @@ -1218,7 +1613,7 @@ mod tests { let mask = out.extras().mask.as_ref().expect("the mask is kept"); assert_eq!(*mask.art, stroked(1), "{name} run: an unlinked mask stays where it was"); - let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5).expect("the art is drawn"); + let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5, &[]).expect("the art is drawn"); let mask = out.extras().mask.as_ref().expect("the mask is kept"); assert_eq!(mask.art.kind, out.kind, "{name} run, widened: the mask's art bends with the art"); assert_eq!(mask.art.appearance, out.appearance, "{name} run, widened: the mask's strokes narrow with the art's"); diff --git a/crates/cad/src/expansion_test.rs b/crates/cad/src/expansion_test.rs new file mode 100644 index 0000000000..f5ae09e915 --- /dev/null +++ b/crates/cad/src/expansion_test.rs @@ -0,0 +1,22 @@ +use std::cell::Cell; + +thread_local! { + static USED: Cell = const { Cell::new(0) }; +} + +pub(crate) fn initial_used() -> u64 { + USED.with(Cell::get) +} + +pub(crate) fn with_used(used: u64, action: impl FnOnce() -> T) -> T { + struct Reset<'a>(&'a Cell, u64); + impl Drop for Reset<'_> { + fn drop(&mut self) { + self.0.set(self.1); + } + } + USED.with(|value| { + let _reset = Reset(value, value.replace(used)); + action() + }) +} diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index d951e92681..d46275a74c 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -588,6 +588,9 @@ impl<'a> Walk<'a> { clip_tests: 0, warnings: vec![], nest: 0, + #[cfg(test)] + symbol_nodes: crate::expansion_test::initial_used(), + #[cfg(not(test))] symbol_nodes: 0, generated: 0, scratch: None, @@ -740,7 +743,6 @@ impl<'a> Walk<'a> { } Some(None) => {} None => { - self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES; self.warn(SYMBOLS_LEFT_OUT); } } diff --git a/crates/cad/src/hpgl/write/tests.rs b/crates/cad/src/hpgl/write/tests.rs index b371c832db..12bfd93c7d 100644 --- a/crates/cad/src/hpgl/write/tests.rs +++ b/crates/cad/src/hpgl/write/tests.rs @@ -870,6 +870,31 @@ fn symbols_nested_too_deep_are_left_out_with_a_warning() { assert_eq!(text(&out), "IN;PU;SP0;"); } +#[test] +fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() { + let mut d = doc_with(|_| vec![]); + let leaf = stroked(&mut d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK); + let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) }); + let mut first = None; + for name in ["big", "small"] { + let id = d.alloc_id(); + first.get_or_insert(id); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); + } + let mut expected = d.clone(); + expected.remove(first.unwrap()).unwrap(); + crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || { + let actual = plot(&d, &opts(&d)); + let control = plot(&expected, &opts(&expected)); + assert!(actual.warnings.iter().any(|w| w == SYMBOLS_LEFT_OUT), "{:?}", actual.warnings); + assert_ne!(text(&control), "IN;PU;SP0;"); + assert_eq!(text(&actual), text(&control), "HP-GL keeps the later fitting instance"); + }); +} + /// A symbol instance stained by its fill draws in the stained color. #[test] fn a_stained_symbol_instance_takes_its_stain() { diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index 8aefe61a0d..b54d9022bf 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -23,6 +23,8 @@ //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. mod aci; +#[cfg(test)] +mod expansion_test; pub mod hpgl; pub mod import; mod scene; diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 700632313e..26025f2544 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -561,8 +561,10 @@ impl<'a> Scene<'a> { extents: None, opacity: 1.0, nest: 0, - // Tests spend all but a million of it up front. - symbol_nodes: if cfg!(test) { vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000 } else { 0 }, + #[cfg(test)] + symbol_nodes: crate::expansion_test::initial_used(), + #[cfg(not(test))] + symbol_nodes: 0, } } @@ -711,7 +713,6 @@ impl<'a> Scene<'a> { } Some(None) => {} None => { - self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES; self.warn(SYMBOLS_LEFT_OUT); } } diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index b2d5d4db3e..dd80644279 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1503,11 +1503,36 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() { let art = Node::group(d.alloc_id(), children); d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(art) }); } - let out = export(&d, &opts(&d)).unwrap(); + let out = crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000, || export(&d, &opts(&d)).unwrap()); assert!(entities(&out).is_empty()); assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings); } +#[test] +fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() { + let mut d = doc_with(|_| vec![]); + let leaf = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 40.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) }); + let mut first = None; + for name in ["big", "small"] { + let id = d.alloc_id(); + first.get_or_insert(id); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); + } + let mut expected = d.clone(); + expected.remove(first.unwrap()).unwrap(); + crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || { + let actual = export(&d, &opts(&d)).unwrap(); + let control = export(&expected, &opts(&expected)).unwrap(); + assert!(actual.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", actual.warnings); + assert!(!entities(&control).is_empty()); + assert_eq!(kinds(&actual), kinds(&control), "DXF keeps the later fitting instance"); + }); +} + #[test] fn export_bytes_match_shared_writer_goldens() { use std::path::PathBuf; diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs new file mode 100644 index 0000000000..24c274846b --- /dev/null +++ b/crates/color/src/css.rs @@ -0,0 +1,443 @@ +//! Color text in the forms CSS Color 4 defines: hex colors with or without an alpha +//! (), `rgb()` and `rgba()` +//! (), `hsl()` and `hsla()` +//! () and `oklch()` +//! (). The functions take the +//! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also +//! take the comma-separated legacy form (). +//! Hues take the angle units of CSS Values 4 (). A hex +//! color may leave out its `#`. +//! +//! The module reads a subset of CSS. A function's arguments are literal numbers, percentages, +//! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`, +//! `var()`, `color-mix()`, relative color syntax and every other nested function are refused, as are +//! named colors and the other color spaces and functions (`hwb()`, `lab()`, `oklab()`, `color()`). + +use crate::oklab::{self, CHROMA_FULL}; + +/// The most characters a color text may have, spaces around it not counted. +pub const MAX_CHARS: usize = 48; + +/// The space a parsed color's red, green and blue are in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Space { + /// The numbers as written: a hex color, `rgb()` or `hsl()`. + Srgb, + /// sRGB converted from `oklch()`. + Oklch, +} + +/// A color read from CSS text. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CssColor { + /// Red, green and blue from 0 to 1. + pub rgb: [f32; 3], + /// The alpha from 0 to 1, when the text gives one (CSS reads a missing alpha as 1). + pub alpha: Option, + pub space: Space, +} + +/// The color `text` gives, or `None` when it is not one of the module's forms or has more than +/// [`MAX_CHARS`] characters. Values are clamped where CSS clamps them when it parses them: red, green +/// and blue to 0..=255 (0..=100 %), alpha to 0..=1, a negative HSL saturation to 0, OKLCH lightness +/// to 0..=1 and chroma to 0 or more. `none` reads as 0, as CSS reads a missing component when it +/// converts a color. Spaces, tabs, line breaks and form feeds may surround the text and its +/// arguments; other whitespace is not CSS whitespace and makes the text invalid. An `hsl()` color whose red, green or +/// blue falls outside 0..=1 has that channel clipped, and an `oklch()` color outside sRGB keeps its +/// lightness and hue and takes the largest chroma that fits ([`oklab::from_oklch`]); CSS maps such +/// colors into the gamut by its own rules instead. An `hsl()` color whose saturation and lightness +/// are so large that a channel overflows to an infinity is refused. +pub fn parse(text: &str) -> Option { + let text = css_trim(text); + if text.chars().nth(MAX_CHARS).is_some() { + return None; + } + match text.find('(') { + None => hex(text), + Some(open) => { + // CSS allows no space between a function's name and its `(`. + let name = text.get(..open)?.to_ascii_lowercase(); + let args = text.get(open + 1..)?.strip_suffix(')')?; + if args.contains(['(', ')']) { + return None; + } + match name.as_str() { + "rgb" | "rgba" => rgb(args), + "hsl" | "hsla" => hsl(args), + "oklch" => oklch(args), + _ => None, + } + } + } +} + +/// `s` without the CSS whitespace (spaces, tabs, line breaks and form feeds, which CSS reads as line +/// breaks) around it (, +/// ). +fn css_trim(s: &str) -> &str { + s.trim_matches(|c: char| c.is_ascii_whitespace()) +} + +/// `#rrggbb` of red, green and blue from 0 to 1, each rounded to the nearest of 256 steps. +pub fn hex_of(rgb: [f32; 3]) -> String { + let [r, g, b] = rgb.map(byte); + format!("#{r:02x}{g:02x}{b:02x}") +} + +/// `v` (0 to 1) as one of 256 steps. +fn byte(v: f32) -> u8 { + (v.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +/// A hex color of 3, 4, 6 or 8 digits, with or without `#`. +fn hex(text: &str) -> Option { + let digits = text.strip_prefix('#').unwrap_or(text); + if !digits.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let nibbles: Vec = digits.bytes().filter_map(|b| (b as char).to_digit(16)).map(|d| d as u8).collect(); + let values: Vec = match nibbles.len() { + 3 | 4 => nibbles.iter().map(|n| n * 17).collect(), + 6 | 8 => nibbles.chunks(2).map(|p| p.iter().fold(0, |v, n| v * 16 + n)).collect(), + _ => return None, + }; + let unit = |i: usize| values.get(i).map(|v| f32::from(*v) / 255.0); + Some(CssColor { rgb: [unit(0)?, unit(1)?, unit(2)?], alpha: unit(3), space: Space::Srgb }) +} + +/// One argument of a color function. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Arg { + Number(f64), + Percent(f64), + /// An angle, in degrees. + Angle(f64), + None, +} + +/// The arguments of a color function, `args` being the text inside its parentheses: the three +/// components and the alpha, if any, and whether they were separated by commas (the legacy form). +fn split(args: &str, legacy_allowed: bool) -> Option<([Arg; 3], Option, bool)> { + let (parts, alpha, legacy): (Vec<&str>, Option<&str>, bool) = if args.contains(',') { + if !legacy_allowed || args.contains('/') { + return None; + } + let mut parts: Vec<&str> = args.split(',').map(css_trim).collect(); + let alpha = if parts.len() == 4 { parts.pop() } else { None }; + (parts, alpha, true) + } else { + let mut halves = args.split('/'); + let colors = halves.next().unwrap_or_default(); + let alpha = halves.next(); + if halves.next().is_some() { + return None; + } + (colors.split_ascii_whitespace().collect(), alpha.map(css_trim), false) + }; + let [a, b, c] = parts.as_slice() else { return None }; + let one = |s: &str| { + let arg = arg(s)?; + // The legacy form has no `none`. + (!(legacy && arg == Arg::None)).then_some(arg) + }; + let alpha = match alpha { + Some(s) => Some(one(s)?), + None => None, + }; + Some(([one(a)?, one(b)?, one(c)?], alpha, legacy)) +} + +/// One argument: `none`, a number, a percentage or an angle (`deg`, `grad`, `rad`, `turn`), with no +/// spaces inside it. +fn arg(s: &str) -> Option { + if s.eq_ignore_ascii_case("none") { + return Some(Arg::None); + } + let end = number_end(s)?; + let n: f64 = s.get(..end)?.parse().ok().filter(|n: &f64| n.is_finite())?; + let unit = s.get(end..)?.to_ascii_lowercase(); + let arg = match unit.as_str() { + "" => Arg::Number(n), + "%" => Arg::Percent(n), + "deg" => Arg::Angle(n), + "grad" => Arg::Angle(n * 0.9), + "rad" => Arg::Angle(n.to_degrees()), + "turn" => Arg::Angle(n * 360.0), + _ => return None, + }; + match arg { + Arg::Angle(a) if !a.is_finite() => None, + _ => Some(arg), + } +} + +/// The byte length of the CSS number at the start of `s`: an optional sign, digits with an +/// optional fraction (at least one digit, and digits after a `.`), and an optional exponent. +fn number_end(s: &str) -> Option { + let b = s.as_bytes(); + let digits = |from: usize| b.get(from..).map_or(0, |rest| rest.iter().take_while(|c| c.is_ascii_digit()).count()); + let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-'))); + let whole = digits(i); + i += whole; + let mut fraction = 0; + if b.get(i) == Some(&b'.') { + fraction = digits(i + 1); + if fraction == 0 { + return None; + } + i += 1 + fraction; + } + if whole + fraction == 0 { + return None; + } + if matches!(b.get(i), Some(b'e' | b'E')) { + let sign = usize::from(matches!(b.get(i + 1), Some(b'+' | b'-'))); + let exp = digits(i + 1 + sign); + if exp > 0 { + i += 1 + sign + exp; + } + } + Some(i) +} + +/// The alpha argument from 0 to 1. +fn alpha(a: Option) -> Option> { + let v = match a { + None => return Some(None), + Some(Arg::Number(n)) => n, + Some(Arg::Percent(p)) => p / 100.0, + Some(Arg::None) => 0.0, + Some(Arg::Angle(_)) => return None, + }; + Some(Some(v.clamp(0.0, 1.0) as f32)) +} + +/// A hue argument in degrees from 0 to 360. +fn hue(a: Arg) -> Option { + match a { + Arg::Number(d) | Arg::Angle(d) => Some(d.rem_euclid(360.0)).filter(|d| d.is_finite()), + Arg::None => Some(0.0), + Arg::Percent(_) => None, + } +} + +fn rgb(args: &str) -> Option { + let (comps, a, legacy) = split(args, true)?; + let percents = comps.iter().filter(|c| matches!(c, Arg::Percent(_))).count(); + if legacy && percents != 0 && percents != 3 { + return None; + } + let unit = |c: Arg| match c { + Arg::Number(n) => Some(n / 255.0), + Arg::Percent(p) => Some(p / 100.0), + Arg::None => Some(0.0), + Arg::Angle(_) => None, + }; + let [r, g, b] = comps; + let rgb = [unit(r)?, unit(g)?, unit(b)?].map(|v| v.clamp(0.0, 1.0) as f32); + Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb }) +} + +fn hsl(args: &str) -> Option { + let (comps, a, legacy) = split(args, true)?; + let [h, s, l] = comps; + let percent = |c: Arg| match c { + Arg::Percent(v) => Some(v), + Arg::Number(v) if !legacy => Some(v), + Arg::None => Some(0.0), + _ => None, + }; + // CSS clamps a negative saturation to 0 and nothing else. + let (h, s, l) = (hue(h)?, percent(s)?.max(0.0) / 100.0, percent(l)? / 100.0); + // CSS Color 4's hslToRgb (https://www.w3.org/TR/css-color-4/#hsl-to-rgb); a channel outside + // 0..=1 is clipped. + let f = |n: f64| { + let k = (n + h / 30.0) % 12.0; + let amount = s * l.min(1.0 - l); + l - amount * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0) + }; + // Huge saturation and lightness values overflow to an infinity or NaN, which is refused. + let rgb = [f(0.0), f(8.0), f(4.0)]; + if rgb.iter().any(|v| !v.is_finite()) { + return None; + } + let rgb = rgb.map(|v| v.clamp(0.0, 1.0) as f32); + Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb }) +} + +fn oklch(args: &str) -> Option { + let (comps, a, _) = split(args, false)?; + let [l, c, h] = comps; + let l = match l { + Arg::Number(v) => v, + Arg::Percent(p) => p / 100.0, + Arg::None => 0.0, + Arg::Angle(_) => return None, + }; + let c = match c { + Arg::Number(v) => v, + Arg::Percent(p) => p / 100.0 * CHROMA_FULL, + Arg::None => 0.0, + Arg::Angle(_) => return None, + }; + let (rgb, _) = oklab::from_oklch(l.clamp(0.0, 1.0), c.max(0.0), hue(h)?); + Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Oklch }) +} + +#[cfg(test)] +mod tests { + use super::*; + use proptest::prelude::*; + + fn bytes(text: &str) -> ([u8; 3], Option) { + let c = parse(text).unwrap_or_else(|| panic!("{text} should parse")); + (c.rgb.map(byte), c.alpha.map(|a| (a * 255.0).round() as u8)) + } + + #[test] + fn hex_colors_take_three_four_six_or_eight_digits_with_or_without_the_hash() { + assert_eq!(bytes("#336699"), ([0x33, 0x66, 0x99], None)); + assert_eq!(bytes("33669980"), ([0x33, 0x66, 0x99], Some(0x80))); + assert_eq!(bytes("#369"), ([0x33, 0x66, 0x99], None)); + assert_eq!(bytes("#3698"), ([0x33, 0x66, 0x99], Some(0x88))); + assert_eq!(bytes(" #AbCdEf "), ([0xab, 0xcd, 0xef], None)); + for bad in ["", "#", "#12", "#12345", "#1234567", "#123456789", "#ggg", "##123", "#+12", "#12 3", "123"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn rgb_reads_the_modern_and_the_legacy_forms() { + assert_eq!(bytes("rgb(51 102 153)"), ([51, 102, 153], None)); + assert_eq!(bytes("rgb(51 102 153 / 50%)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("RGBA(51 102 153/0.5)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("rgb(20% 40% 60%)"), ([51, 102, 153], None)); + assert_eq!(bytes("rgb(20% 102 none)"), ([51, 102, 0], None), "the modern form mixes numbers and percentages"); + assert_eq!(bytes("rgb(51, 102, 153)"), ([51, 102, 153], None)); + assert_eq!(bytes("rgba(51,102,153,.5)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("rgb(51, 102, 153, 50%)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("rgb(300 -20 1e2)"), ([255, 0, 100], None), "components are clamped"); + assert_eq!(bytes("rgb(0 0 0 / 2)"), ([0, 0, 0], Some(255)), "the alpha is clamped"); + assert_eq!(bytes("rgb(0 0 0 / none)"), ([0, 0, 0], Some(0))); + for bad in [ + "rgb(51, 102%, 153)", + "rgb(51, 102, none)", + "rgb(51 102)", + "rgb(51 102 153 0.5)", + "rgb(51, 102 153)", + "rgb(51, 102, 153 / 0.5)", + "rgb(51 102 153 / 0.5 / 1)", + "rgb(51 102 153deg)", + "rgb(1. 2 3)", + "rgb(1e999 0 0)", + "rgb(51 102 153", + "rgb(51 102 153))", + "rgb(51 102 153) x", + "rgb(calc(1) 2 3)", + "rgb(,,)", + "rgb (1 2 3)", + "rgb()", + "rgbx(1 2 3)", + ] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn only_spaces_tabs_and_line_breaks_are_whitespace() { + assert_eq!(bytes("\t rgb(51,\n102 ,\t153)\r\n"), ([51, 102, 153], None)); + assert_eq!(bytes("rgb(51 102 153 /\t0.5 )"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("\u{c}#336699\u{c}"), ([51, 102, 153], None), "CSS reads a form feed as a line break"); + assert_eq!(bytes("rgb(51\u{c}102\u{c}153)"), ([51, 102, 153], None)); + for bad in ["rgb(51,\u{a0}102,153)", "rgb(51,102,153\u{3000})", "\u{a0}#336699", "#336699\u{2003}", "rgb(0 0 0 /\u{a0}1)", "\u{b}#336699"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn hsl_reads_hues_in_every_angle_unit() { + assert_eq!(bytes("hsl(210 50% 40%)"), ([51, 102, 153], None)); + assert_eq!(bytes("hsl(210deg 50 40 / 25%)"), ([51, 102, 153], Some(64))); + assert_eq!(bytes("hsla(210, 50%, 40%, 0.5)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("hsl(-150 50% 40%)"), ([51, 102, 153], None), "a hue is normalized"); + assert_eq!(bytes("hsl(0.5turn 100% 50%)"), ([0, 255, 255], None)); + assert_eq!(bytes("hsl(200grad 100% 50%)"), ([0, 255, 255], None)); + assert_eq!(bytes("hsl(3.14159265rad 100% 50%)"), ([0, 255, 255], None)); + assert_eq!(bytes("hsl(120 -20% 50%)"), ([128, 128, 128], None), "a negative saturation is 0"); + assert_eq!(bytes("hsl(15 150% 50%)"), ([255, 32, 0], None), "a saturation over 100 % is kept and the channels are clipped"); + assert_eq!(bytes("hsl(0 50% 150%)"), ([255, 255, 255], None)); + assert_eq!(bytes("hsl(none 0% 100%)"), ([255, 255, 255], None)); + for bad in + ["hsl(210, 50, 40)", "hsl(210% 50% 40%)", "hsl(210 50% 40% 1)", "hsl(210deg, 50%, none)", "hsl(1e999deg 0% 0%)", "hsl(1e306turn 0% 0%)"] + { + assert_eq!(parse(bad), None, "{bad:?}"); + } + // Saturation and lightness this large overflow to an infinity or NaN. + for bad in ["hsl(90 1e308% 1e308%)", "hsl(90 1e308 -1e308)"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn oklch_converts_through_srgb_and_has_no_legacy_form() { + let c = parse("oklch(62.8% 0.2577 29.23)").unwrap(); + assert_eq!((c.rgb.map(byte), c.alpha, c.space), ([255, 0, 0], None, Space::Oklch)); + let c = parse("oklch(0.628 64.4% 29.23 / 0.5)").unwrap(); + assert_eq!((c.rgb.map(byte), c.alpha), ([255, 0, 0], Some(0.5))); + assert_eq!(parse("oklch(1 0 0)").map(|c| c.rgb.map(byte)), Some([255, 255, 255])); + assert_eq!(parse("oklch(2 -1 none)").map(|c| c.rgb.map(byte)), Some([255, 255, 255]), "L and C are clamped"); + let wide = parse("oklch(0.7 0.4 150)").unwrap(); + assert!(wide.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a color outside sRGB is brought inside: {:?}", wide.rgb); + let huge = parse("oklch(0.5 1e308 30)").unwrap(); + assert!(huge.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a huge chroma is brought inside: {:?}", huge.rgb); + for bad in ["oklch(0.6, 0.1, 30)", "oklch(0.6 0.1 30% )", "oklch(0.6deg 0.1 30)", "oklch(0.6 0.1)"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn text_longer_than_the_limit_is_refused() { + let at_limit = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 15)); + assert_eq!(at_limit.chars().count(), MAX_CHARS); + assert!(parse(&at_limit).is_some()); + let over = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 14)); + assert_eq!(parse(&over), None); + assert_eq!(parse(&format!(" {at_limit} ")).map(|c| c.rgb.map(byte)), Some([51, 102, 153]), "spaces around it are not counted"); + assert_eq!(parse(&"(".repeat(100_000)), None); + } + + #[test] + fn hex_of_rounds_each_component() { + assert_eq!(hex_of([0.2, 0.4, 0.6]), "#336699"); + assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00"); + } + + proptest! { + #[test] + fn random_text_never_panics(text in "\\PC{0,60}") { + // `contains` is false for NaN, so these also check that every channel is finite. + if let Some(c) = parse(&text) { + prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v))); + prop_assert!(c.alpha.is_none_or(|a| (0.0..=1.0).contains(&a))); + } + } + + #[test] + fn function_shaped_text_never_panics( + name in "(rgb|rgba|hsl|hsla|oklch|RGB)", + args in "[-+0-9.eE%a-z ,/]{0,40}", + ) { + if let Some(c) = parse(&format!("{name}({args})")) { + prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v))); + } + } + + #[test] + fn eight_digit_hex_round_trips(r: u8, g: u8, b: u8, a: u8) { + let c = parse(&format!("#{r:02x}{g:02x}{b:02x}{a:02x}")).unwrap(); + prop_assert_eq!(c.rgb.map(byte), [r, g, b]); + prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a)); + prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}")); + } + } +} diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 1fdcab123d..5bb4c88985 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -6,6 +6,7 @@ pub mod blend; pub mod cms; +pub mod css; pub mod freeform; pub mod gradient; pub mod harmony; diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 6d1f33dd5c..10adb09199 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -28,6 +28,8 @@ tiff = { workspace = true } craft-stream-codecs = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } +# The hash of a generated art object's art, which its file holds (`generated`). +sha2 = { version = "0.10", default-features = false } thiserror = { workspace = true } chrono = { workspace = true } diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs index 7a39d6cbb2..4038d04b42 100644 --- a/crates/doc/src/appearance/stroke_style.rs +++ b/crates/doc/src/appearance/stroke_style.rs @@ -192,14 +192,18 @@ pub enum Arrowhead { /// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as /// the other heads. LineArrow, + /// A slender filled head, a little over half as wide as it is long, whose sides bend in + /// halfway back, with a V-shaped notch in its back: the arrow of mathematical diagrams. + NotchedArrow, /// A head the user drew, with its art. Custom(Arc), } impl Arrowhead { /// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks). - pub const ALL: [Arrowhead; 41] = [ + pub const ALL: [Arrowhead; 42] = [ Arrowhead::Arrow, + Arrowhead::NotchedArrow, Arrowhead::ArrowOpen, Arrowhead::LineArrow, Arrowhead::Barbed, @@ -322,6 +326,7 @@ impl Arrowhead { Arrowhead::TriangleBar => "Triangle to Bar", Arrowhead::Oval => "Oval", Arrowhead::LineArrow => "Line Arrow", + Arrowhead::NotchedArrow => "Notched Arrow", Arrowhead::Custom(_) => "Custom", } } diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index c91348d57f..787c864b2f 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -316,7 +316,7 @@ fn profile_presets_round_trip_their_ids() { #[test] fn arrowhead_names_are_stable_and_every_one_is_listed_once() { // Saved files store these names: they may only ever be appended to. - const SAVED: [&str; 41] = [ + const SAVED: [&str; 42] = [ "Triangle", "TriangleOpen", "Circle", @@ -358,6 +358,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() { "TriangleBar", "Oval", "LineArrow", + "NotchedArrow", ]; for name in SAVED { let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap(); diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 3e08f96977..537a1d6e60 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -394,6 +394,11 @@ pub enum DimensionSource { /// it is vertical. Versions without this source do not open the file. Extent { node: NodeId, + /// Placed with Use Preview Bounds on: the points are moved out to the outside of the + /// strokes the path paints ([`preview_extents`]), the width or height that W and H show. + /// Versions without it measure between the outermost points themselves. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + preview: bool, }, } @@ -402,7 +407,7 @@ impl DimensionSource { match self { Self::Segment { edge } | Self::Arc { edge } => vec![edge.node], Self::Angle { first, second } => vec![first.node, second.node], - Self::Circle { node } | Self::Extent { node } => vec![*node], + Self::Circle { node } | Self::Extent { node, .. } => vec![*node], Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex] .into_iter() .filter_map(|p| p.as_ref().map(|r| r.node)) @@ -425,10 +430,18 @@ impl DimensionSource { }) } /// Whether a path it measures differs between `before` and `after`, or is in only one of them. - /// A node without a path, or missing from both, counts as changed. + /// A node without a path, or missing from both, counts as changed. For a dimension of a whole + /// path placed with Use Preview Bounds on, so does a change to the strokes the path paints + /// ([`stroked_by`]): their appearance, the node they come from, or which arrowheads they draw + /// on it, and the path being made into a guide or released from one. pub fn art_changed(&self, before: &Document, after: &Document) -> bool { + let strokes = matches!(self, Self::Extent { preview: true, .. }); self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) { - (Some(old), Some(new)) => old.path_data().is_none() || (!std::ptr::eq(old, new) && old.path_data() != new.path_data()), + (Some(old), Some(new)) => { + old.path_data().is_none() + || (!std::ptr::eq(old, new) && old.path_data() != new.path_data()) + || (strokes && (old.is_guide() != new.is_guide() || stroked_by(before, id) != stroked_by(after, id))) + } _ => true, }) } @@ -845,7 +858,9 @@ impl Dimension { let (a, b) = (self.a.to_vec2().dot(n), self.b.to_vec2().dot(n)); let (low, high) = (a.min(b), a.max(b)); match (doc, &self.source) { - (Some(doc), Some(DimensionSource::Extent { node })) => reach(doc, *node, n).map_or((low, high), |(l, h)| (low.min(l), high.max(h))), + (Some(doc), Some(DimensionSource::Extent { node, preview })) => { + reach(doc, *node, n, *preview).map_or((low, high), |(l, h)| (low.min(l), high.max(h))) + } _ => (low, high), } } @@ -891,8 +906,8 @@ impl Dimension { }; } next.orientation = orientation; - if let Some(DimensionSource::Extent { node }) = &next.source { - (next.a, next.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?; + if let Some(DimensionSource::Extent { node, preview }) = &next.source { + (next.a, next.b) = extent(doc, *node, orientation == Orientation::Vertical, *preview).ok_or("Measured path no longer exists")?; } // Along the new normal, relative to the new first point, so that the result is the offset. let n = next.normal(); @@ -1020,8 +1035,8 @@ impl Dimension { let (center, radius) = arc(doc, edge).ok_or("Choose a circle or a perfect arc")?; self.set_radial(center, radius); } - Some(DimensionSource::Extent { node }) => { - let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?; + Some(DimensionSource::Extent { node, preview }) => { + let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical, *preview).ok_or("Measured path no longer exists")?; self.a = a; self.b = b; self.length = self.measured(); @@ -1176,14 +1191,86 @@ fn same_extents(before: &Document, after: &Document, id: NodeId) -> bool { } /// [`extents`] along one axis: the leftmost and the rightmost points, or with `vertical` the -/// topmost and the bottommost. -pub fn extent(doc: &Document, id: NodeId, vertical: bool) -> Option<(Point, Point)> { - extents(doc, id).map(|ends| ends[usize::from(vertical)]) +/// topmost and the bottommost. With `preview`, the points of [`preview_extents`]. +pub fn extent(doc: &Document, id: NodeId, vertical: bool, preview: bool) -> Option<(Point, Point)> { + let ends = if preview { preview_extents(doc, id) } else { extents(doc, id) }; + ends.map(|ends| ends[usize::from(vertical)]) +} + +/// [`extents`] moved out to the box the path paints, its strokes included ([`painted_box`]), as Use +/// Preview Bounds measures it: the leftmost and the rightmost points move out to that box's left +/// and right sides at the same height, and the topmost and the bottommost to its top and bottom at +/// the same place across. A path that paints no stroke keeps the points of [`extents`]. None for a +/// node without a path or without segments. +pub fn preview_extents(doc: &Document, id: NodeId) -> Option<[(Point, Point); 2]> { + let [(left, right), (top, bottom)] = extents(doc, id)?; + let Some(b) = painted_box(doc, id) else { return Some([(left, right), (top, bottom)]) }; + Some([ + (Point::new(left.x.min(b.x0), left.y), Point::new(right.x.max(b.x1), right.y)), + (Point::new(top.x, top.y.min(b.y0)), Point::new(bottom.x, bottom.y.max(b.y1))), + ]) +} + +/// The node whose strokes a path paints with: the compound path that holds it, or the path itself. +fn painter(doc: &Document, id: NodeId) -> Option<&crate::Node> { + let n = doc.node(id)?; + match doc.parent_of(id).and_then(|p| doc.node(p)) { + Some(c) if matches!(c.kind, crate::NodeKind::Compound { .. }) => Some(c), + _ => Some(n), + } +} + +/// What the strokes a path paints with depend on, besides its own shape: the node they come from +/// ([`painter`]), its appearance, and which arrowheads they draw on the path ([`heads_on`]). +fn stroked_by(doc: &Document, id: NodeId) -> Option<(NodeId, &crate::Appearance, (bool, bool))> { + painter(doc, id).map(|p| (p.id, &*p.appearance, heads_on(p, id))) +} + +/// The box a path paints, its strokes included, measured along its own shape as +/// [`crate::Node::visual_bounds`] measures a path: a member of a compound path is stroked with the +/// compound path's strokes, with only the arrowheads the compound path paints on it. None for a +/// node without a path or without anything drawn, and for a path made into a guide, which paints +/// no strokes. +fn painted_box(doc: &Document, id: NodeId) -> Option { + let n = doc.node(id)?; + if n.is_guide() { + return None; + } + let path = n.path_data()?; + let painter = painter(doc, id)?; + let a = &painter.appearance; + // A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath. + let dots = a.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square)); + let b = path.drawn_bounds(dots).or_else(|| n.geometric_bounds())?; + let (start, end) = heads_on(painter, id); + let mut shape = None; + Some(a.stroked_bounds_by(b, |s| { + let bp = shape.get_or_insert_with(|| n.stroke_path().unwrap_or_default()); + if (s.start_arrow.is_some() && !start) || (s.end_arrow.is_some() && !end) { + let mut s = s.clone(); + s.start_arrow = s.start_arrow.filter(|_| start); + s.end_arrow = s.end_arrow.filter(|_| end); + s.bounds_on(bp, b) + } else { + s.bounds_on(bp, b) + } + })) +} + +/// Whether the start and the end arrowheads of `painter`'s strokes can be drawn on its member +/// `id`. A compound path's strokes put the start head on its first subpath and the end head on its +/// last, so a member gets the start head only when it holds the first subpath with anchors and +/// the end head only when it holds the last one. A path that is its own painter gets both. +fn heads_on(painter: &crate::Node, id: NodeId) -> (bool, bool) { + let Some(members) = painter.children().filter(|_| painter.id != id) else { return (true, true) }; + let drawn = |c: &&std::sync::Arc| c.path_data().is_some_and(|p| p.subpaths.iter().any(|sp| !sp.anchors.is_empty())); + (members.iter().find(drawn).is_some_and(|c| c.id == id), members.iter().rfind(drawn).is_some_and(|c| c.id == id)) } /// How far a path's outline reaches along the unit direction `u`: the lowest and the highest -/// `p · u` over the points of its segments. None for a node without a path or without segments. -pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> { +/// `p · u` over the points of its segments, and with `preview` over the corners of the box it +/// paints too ([`painted_box`]). None for a node without a path or without segments. +pub fn reach(doc: &Document, id: NodeId, u: Vec2, preview: bool) -> Option<(f64, f64)> { use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema}; let path = doc.node(id)?.path_data()?; // Turns `u` onto the x axis, so the turned curve's extrema include those along `u`. @@ -1204,6 +1291,15 @@ pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> { } } } + if preview + && let Some((low, high)) = span.as_mut() + && let Some(b) = painted_box(doc, id) + { + for corner in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)] { + let v = corner.to_vec2().dot(u); + (*low, *high) = (low.min(v), high.max(v)); + } + } span } diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 3e5743aec3..dc1e082ac0 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -314,8 +314,14 @@ impl Document { self.renumber_stored_duplicates(); } - /// Find a node anywhere in the tree. + /// Find a node anywhere in the tree. With the lookup cache built, the node comes from the place the cache has for + /// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as + /// [`Document::index_path`] finds it. pub fn node(&self, id: NodeId) -> Option<&Node> { + if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) { + crate::id_index::note_path_lookup(); + return Some(n); + } self.index_path(id).and_then(|p| self.node_at(&p)) } diff --git a/crates/doc/src/generated.rs b/crates/doc/src/generated.rs new file mode 100644 index 0000000000..30ef8fd250 --- /dev/null +++ b/crates/doc/src/generated.rs @@ -0,0 +1,597 @@ +//! Generated art objects: a group whose children a generator plug-in drew from its parameters +//! (`plugin.generate`). The group keeps the plug-in's id and name, the parameters it was drawn with +//! and the transform its art has had since, so `plugin.editGenerated` can run the plug-in again and +//! replace the art. Its children are ordinary objects for every renderer and exporter, so the art +//! draws, prints and exports whether or not the plug-in is installed. +//! +//! A file holds the fields beside a SHA-256 of the art as it was written ([`art_hash`]). Reading +//! never runs a plug-in. A field that can't be read (an id that is not a plug-in id, parameters +//! that are not an object or are past [`MAX_PARAMS_BYTES`], a transform that is not one) marks the +//! object [`State::Damaged`], and art that doesn't match the hash marks it [`State::Changed`]: the +//! art stays as it was read either way. A damaged object is saved with `damaged: true`, so it stays +//! damaged when the file is opened again. +//! +//! A generated art object inside another one's art (anywhere in its children or their opacity +//! masks) is written and read as plain art: its settings are left out of the file, and a file that +//! has them there anyway loses them when it is read, its outer object marked [`State::Changed`] +//! without hashing. So each object's art is written and hashed once, whatever the nesting. + +use std::cell::Cell; +use std::sync::Arc; + +use serde::Serialize; +use serde_json::{Map, Value}; +use vectorcraft_geom::Affine; + +use crate::Effect; +use crate::node::{Node, NodeKind, Scaling}; + +/// Most bytes a generated art object's parameters take, written as JSON. +pub const MAX_PARAMS_BYTES: usize = 64 << 10; + +/// Most bytes the art of a generated art object takes when a generator draws it, written as JSON. +pub const MAX_ART_BYTES: usize = 16 << 20; + +/// Longest plug-in id, in bytes, as plug-in manifests limit it. +pub const MAX_ID: usize = 64; + +/// Longest plug-in name kept, in characters, as plug-in manifests limit it. +pub const MAX_NAME: usize = 64; + +/// How the fields of a generated art object were read. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum State { + /// Made in this session, or read with every field and the art's hash intact. + #[default] + Intact, + /// A field could not be read: the plug-in id is not one, or the parameters or the transform + /// are not usable. The art can't be drawn again. + Damaged, + /// The fields were read, but the art doesn't match the hash the file gave for it. + Changed, +} + +/// The settings of a generated art object ([`crate::NodeExtras::generated`]). +#[derive(Clone, Debug, PartialEq)] +pub struct GeneratedArt { + /// The id of the plug-in that drew it. + pub plugin: String, + /// The plug-in's name when it drew it, to name the plug-in while it is not installed. + pub name: String, + /// The plug-in's parameters it was drawn with, each one given. + pub params: Map, + /// The transform its art has had since it was drawn (moves, scales, rotations, reflections + /// and shears). + pub transform: Affine, + /// What its art's stroke weights and dashes have been scaled by since it was drawn (the + /// transforms made with Scale Strokes & Effects on). + pub stroke_scale: f64, + /// What its art's effect distances have been scaled by since it was drawn. + pub effect_scale: f64, + /// The transform its art's pattern tiles have had since it was drawn (the transforms made with + /// Transform Patterns on). + pub pattern_transform: Affine, + /// How it was read; not written to files. + pub state: State, +} + +impl GeneratedArt { + /// The settings of art drawn by plug-in `plugin` (named `name`) with `params`, not transformed + /// since. + pub fn new(plugin: &str, name: &str, params: Map) -> Self { + Self { + plugin: plugin.into(), + name: name.chars().take(MAX_NAME).collect(), + params, + transform: Affine::IDENTITY, + stroke_scale: 1.0, + effect_scale: 1.0, + pattern_transform: Affine::IDENTITY, + state: State::Intact, + } + } + + /// Its art transformed by `a`, with what `sc` says scales besides its geometry. + pub fn transform(&mut self, a: Affine, sc: &Scaling) { + self.transform = a * self.transform; + if let Some(k) = Scaling::factor(a) + && sc.strokes + { + self.stroke_scale *= k; + if sc.effects.is_some() { + self.effect_scale *= k; + } + } + if sc.patterns { + self.pattern_transform = a * self.pattern_transform; + } + } + + /// Places `art`, drawn by the generator as it is drawn untransformed, as the object's art has + /// been transformed since it was drawn: its geometry, stroke weights, effect distances and + /// pattern tiles. `scale` scales an effect's distance parameters (the effects catalogue's). + pub fn place(&self, art: &mut Node, scale: fn(&mut Effect, f64)) { + if self.transform != Affine::IDENTITY { + art.transform(self.transform, false); + } + self.restyle(art, scale); + } + + /// Scales the strokes and effects of `n` and its descendants, and transforms their pattern + /// tiles, as [`Self::place`] says. + fn restyle(&self, n: &mut Node, scale: fn(&mut Effect, f64)) { + if self.stroke_scale != 1.0 { + n.appearance.scale_strokes(self.stroke_scale); + } + if self.effect_scale != 1.0 { + n.appearance.scale_effects(self.effect_scale, scale); + } + if self.pattern_transform != Affine::IDENTITY { + crate::pattern::transform_pattern_paints(n, self.pattern_transform); + } + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + self.restyle(std::sync::Arc::make_mut(c), scale); + } + } + } + + /// Can its art be drawn again: are its fields intact or only its art changed? + pub fn redrawable(&self) -> bool { + self.state != State::Damaged + } +} + +/// Is `id` shaped as a plug-in id: 1 to [`MAX_ID`] characters from `A-Z a-z 0-9 . _ -`? +pub fn valid_id(id: &str) -> bool { + (1..=MAX_ID).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) +} + +std::thread_local! { + /// Is a generated art object's art being written on this thread ([`Inside`])? + static INSIDE: Cell = const { Cell::new(false) }; +} + +#[cfg(test)] +std::thread_local! { + /// The bytes [`art_hash`] has hashed on this thread. + static HASHED: Cell = const { Cell::new(0) }; +} + +/// While it lives, objects written on this thread are part of a generated art object's art, and +/// the generated art objects among them are written as plain art ([`written`]). +pub(crate) struct Inside(bool); + +impl Inside { + pub(crate) fn enter() -> Self { + Self(INSIDE.with(|i| i.replace(true))) + } +} + +impl Drop for Inside { + fn drop(&mut self) { + INSIDE.with(|i| i.set(self.0)); + } +} + +/// The settings `g` an object writes: none while a generated art object's art is being written. +pub(crate) fn written(g: Option<&GeneratedArt>) -> Option<&GeneratedArt> { + g.filter(|_| !INSIDE.with(Cell::get)) +} + +/// The SHA-256 of `children` written as JSON, in lower-case hexadecimal: what a file holds as the +/// hash of a generated art object's art. Generated art objects among them are written as plain +/// art. +pub fn art_hash(children: &[Arc]) -> String { + use sha2::{Digest, Sha256}; + let bytes = { + let _inside = Inside::enter(); + serde_json::to_vec(children).unwrap_or_default() + }; + #[cfg(test)] + HASHED.with(|h| h.set(h.get() + bytes.len())); + Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect() +} + +/// The bytes `children` take written as JSON, generated art objects among them as plain art +/// ([`MAX_ART_BYTES`]). +pub fn art_bytes(children: &[Arc]) -> usize { + let _inside = Inside::enter(); + serde_json::to_vec(children).map_or(usize::MAX, |b| b.len()) +} + +/// Drops the settings of the generated art objects in `nodes`, among their descendants and in +/// their opacity masks' art, which become plain art; returns whether there were any. It doesn't +/// look among the children of such an object, which reading it already made plain art, only at +/// its opacity mask's art. +fn plain_art(nodes: &mut [Arc]) -> bool { + let mut found = false; + for a in nodes { + let generated = a.extras().generated.is_some(); + if !generated && a.children().is_none_or(Vec::is_empty) && a.extras().mask.is_none() { + continue; + } + let n = Arc::make_mut(a); + if generated { + n.extras_mut().generated = None; + found = true; + } else if let Some(ch) = n.children_mut() { + found |= plain_art(ch); + } + if n.extras().mask.is_some() + && let Some(m) = n.extras_mut().mask.as_mut() + { + found |= plain_art(std::slice::from_mut(&mut m.art)); + } + } + found +} + +/// How a file holds a generated art object's settings, borrowed from the node. +#[derive(Serialize)] +pub(crate) struct Wire<'a> { + plugin: &'a str, + name: &'a str, + params: &'a Map, + #[serde(skip_serializing_if = "is_identity")] + transform: &'a Affine, + #[serde(rename = "strokeScale", skip_serializing_if = "is_one")] + stroke_scale: f64, + #[serde(rename = "effectScale", skip_serializing_if = "is_one")] + effect_scale: f64, + #[serde(rename = "patternTransform", skip_serializing_if = "is_identity")] + pattern_transform: &'a Affine, + hash: String, + #[serde(skip_serializing_if = "std::ops::Not::not")] + damaged: bool, +} + +fn is_identity(a: &&Affine) -> bool { + **a == Affine::IDENTITY +} + +fn is_one(k: &f64) -> bool { + *k == 1.0 +} + +impl<'a> Wire<'a> { + /// The settings `g` of node `n`, with the hash of its art. + pub(crate) fn of(g: &'a GeneratedArt, n: &Node) -> Self { + let hash = art_hash(n.children().map_or(&[][..], Vec::as_slice)); + Wire { + plugin: &g.plugin, + name: &g.name, + params: &g.params, + transform: &g.transform, + stroke_scale: g.stroke_scale, + effect_scale: g.effect_scale, + pattern_transform: &g.pattern_transform, + hash, + damaged: g.state == State::Damaged, + } + } +} + +/// A saved transform `t` (absent: none): `None` when it is not six finite numbers. +fn read_affine(t: Option) -> Option { + match t { + None => Some(Affine::IDENTITY), + Some(t) => serde_json::from_value::(t).ok().filter(|a| a.as_coeffs().iter().all(|c| c.is_finite())), + } +} + +/// A saved scale `k` (absent: 1): `None` when it is not a finite number of 0 or more. A transform +/// that flattens the art to a line or a point scales its strokes and effects by 0. +fn read_scale(k: Option) -> Option { + match k { + None => Some(1.0), + Some(k) => k.as_f64().filter(|k| k.is_finite() && *k >= 0.0), + } +} + +/// The settings a file gives (`v`, its `generated` field) for a node of `kind`: `None` for anything +/// but a group, else what could be read, marked [`State::Damaged`] or [`State::Changed`] when a +/// field or the art's hash doesn't hold up. A field that can't be read is kept empty: an id is +/// kept only when it is a plug-in id, a name at most [`MAX_NAME`] characters long. Generated art +/// objects in the group's art become plain art ([`plain_art`]), and the art is then not hashed. +pub(crate) fn read(v: Value, kind: &mut NodeKind) -> Option> { + let NodeKind::Group { children, .. } = kind else { return None }; + let nested = plain_art(children); + let Value::Object(mut o) = v else { + return Some(Box::new(GeneratedArt { state: State::Damaged, ..GeneratedArt::new("", "", Map::new()) })); + }; + let mut damaged = !matches!(o.remove("damaged"), None | Some(Value::Bool(false))); + let plugin = match o.remove("plugin") { + Some(Value::String(id)) if valid_id(&id) => id, + _ => { + damaged = true; + String::new() + } + }; + let name: String = match o.remove("name") { + Some(Value::String(n)) => n.chars().filter(|c| !c.is_control()).take(MAX_NAME).collect(), + _ => String::new(), + }; + let params = match o.remove("params") { + Some(Value::Object(p)) if serde_json::to_vec(&p).is_ok_and(|b| b.len() <= MAX_PARAMS_BYTES) => p, + _ => { + damaged = true; + Map::new() + } + }; + let mut affine = |key: &str| { + read_affine(o.remove(key)).unwrap_or_else(|| { + damaged = true; + Affine::IDENTITY + }) + }; + let transform = affine("transform"); + let pattern_transform = affine("patternTransform"); + let mut scale = |key: &str| { + read_scale(o.remove(key)).unwrap_or_else(|| { + damaged = true; + 1.0 + }) + }; + let stroke_scale = scale("strokeScale"); + let effect_scale = scale("effectScale"); + let intact = !nested && matches!(o.get("hash"), Some(Value::String(h)) if *h == art_hash(children)); + let state = if damaged { + State::Damaged + } else if intact { + State::Intact + } else { + State::Changed + }; + Some(Box::new(GeneratedArt { plugin, name, params, transform, stroke_scale, effect_scale, pattern_transform, state })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::node::NodeId; + use serde_json::json; + use std::sync::Arc; + use vectorcraft_geom::{Rect, shapes}; + + fn art() -> Node { + let square = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Default::default()); + let mut g = Node::group(NodeId(1), vec![Arc::new(square)]); + let mut params = Map::new(); + params.insert("size".into(), json!(10)); + g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", params))); + g + } + + fn reread(v: &Value) -> Node { + serde_json::from_value(v.clone()).unwrap() + } + + /// `depth` generated art objects, each the only child of the one around it, the innermost + /// [`art`]. + fn nested(depth: usize) -> Node { + let mut n = art(); + for i in 1..depth { + let mut g = Node::group(NodeId(10 + i as u64), vec![Arc::new(n)]); + g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", Map::new()))); + n = g; + } + n + } + + /// The bytes [`art_hash`] hashes while `f` runs. + fn hashed(f: impl FnOnce() -> T) -> (T, usize) { + HASHED.with(|h| h.set(0)); + let out = f(); + (out, HASHED.with(Cell::get)) + } + + /// The generated art objects in `n` and below it, outermost first, as (depth, state). + fn generated_in(n: &Node) -> Vec<(usize, State)> { + let mut out = vec![]; + let mut at = Some((n, 0)); + while let Some((n, d)) = at { + if let Some(g) = &n.extras().generated { + out.push((d, g.state)); + } + at = n.children().and_then(|c| c.first()).map(|c| (&**c, d + 1)); + } + out + } + + /// Generated art objects nested in one another are written with the outermost one's settings + /// alone, so writing and reading them hash each object's art once, however deep they nest; a + /// file that has settings on the inner ones anyway loses them, without hashing. + #[test] + fn nested_generated_art_is_written_and_read_with_its_art_hashed_once() { + crate::depth::with_deep_stack(|| { + for depth in [16, 200] { + let n = nested(depth); + let (bytes, writing) = hashed(|| serde_json::to_vec(&n).unwrap()); + assert!(writing <= bytes.len(), "{depth} deep: {writing} bytes hashed to write {}", bytes.len()); + assert_eq!(String::from_utf8_lossy(&bytes).matches("\"generated\"").count(), 1, "{depth} deep"); + let v = serde_json::to_value(&n).unwrap(); + let (back, reading) = hashed(|| reread(&v)); + assert!(reading <= bytes.len(), "{depth} deep: {reading} bytes hashed to read {}", bytes.len()); + assert_eq!(generated_in(&back), vec![(0, State::Intact)], "{depth} deep"); + // Settings on every level, each with a hash: none is hashed, the inner ones are + // dropped, and the outermost reads as changed. + let mut crafted = v.clone(); + let settings = v["generated"].clone(); + let mut at = crafted.pointer_mut("/kind/children/0"); + while let Some(c) = at { + if c.pointer("/kind/children/0").is_some() { + c["generated"] = settings.clone(); + } + at = c.pointer_mut("/kind/children/0"); + } + let (crafted_back, reading) = hashed(|| reread(&crafted)); + assert!(reading <= bytes.len(), "{depth} deep, crafted: {reading} bytes hashed to read {}", bytes.len()); + assert_eq!(generated_in(&crafted_back), vec![(0, State::Changed)], "{depth} deep, crafted"); + assert_eq!(crafted_back.children(), back.children(), "{depth} deep, crafted"); + } + }); + } + + /// A generated art object inside another one's art, whose opacity mask's art is a generated art + /// object too, reads as plain art with plain mask art. + #[test] + fn a_nested_generated_art_objects_mask_art_reads_as_plain_art() { + let mut inner = art(); + inner.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(art(), true))); + let mut outer = Node::group(NodeId(20), vec![Arc::new(inner)]); + outer.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", Map::new()))); + let v = serde_json::to_value(&outer).unwrap(); + assert!(v.pointer("/kind/children/0/generated").is_none() && v.pointer("/kind/children/0/mask/art/generated").is_none()); + let mut crafted = v.clone(); + let settings = v["generated"].clone(); + crafted["kind"]["children"][0]["generated"] = settings.clone(); + crafted["kind"]["children"][0]["mask"]["art"]["generated"] = settings; + let back = reread(&crafted); + assert_eq!(back.extras().generated.as_ref().map(|g| g.state), Some(State::Changed)); + let inner = &back.children().unwrap()[0]; + assert!(inner.extras().generated.is_none()); + assert!(inner.extras().mask.as_ref().is_some_and(|m| m.art.extras().generated.is_none())); + assert_eq!(back.children(), reread(&v).children()); + } + + /// A generated art object inside plain groups is still checked against its hash: intact as + /// written, changed when its art is tampered with. + #[test] + fn a_generated_art_object_deep_in_plain_groups_keeps_its_hash_check() { + crate::depth::with_deep_stack(|| { + let mut n = art(); + for i in 1..200 { + n = Node::group(NodeId(10 + i as u64), vec![Arc::new(n)]); + } + let v = serde_json::to_value(&n).unwrap(); + let state = |v: &Value| generated_in(&reread(v)).into_iter().map(|(_, s)| s).collect::>(); + assert_eq!(state(&v), vec![State::Intact]); + let mut tampered = v.clone(); + let mut at = tampered.pointer_mut("/kind/children/0"); + while let Some(c) = at { + if c.get("generated").is_some() { + c["kind"]["children"][0]["name"] = json!("tampered"); + break; + } + at = c.pointer_mut("/kind/children/0"); + } + assert_eq!(state(&tampered), vec![State::Changed]); + }); + } + + /// A generated art object writes its plug-in, name, parameters and the hash of its art, and + /// reads back the same, intact. + #[test] + fn a_generated_art_object_round_trips_with_the_hash_of_its_art() { + let g = art(); + let v = serde_json::to_value(&g).unwrap(); + let saved = &v["generated"]; + assert_eq!((&saved["plugin"], &saved["name"], &saved["params"]), (&json!("org.example.gen"), &json!("Squares"), &json!({"size": 10}))); + assert_eq!(saved["hash"], json!(art_hash(g.children().unwrap()))); + assert!(saved.get("transform").is_none()); + let back = reread(&v); + assert_eq!(back, g); + assert_eq!(back.extras().generated.as_ref().map(|a| a.state), Some(State::Intact)); + // A moved object keeps its transform. + let mut moved = g.clone(); + moved.transform(Affine::translate((5.0, 0.0)), false); + let back = reread(&serde_json::to_value(&moved).unwrap()); + assert_eq!(back.extras().generated.as_ref().map(|a| (a.transform, a.state)), Some((Affine::translate((5.0, 0.0)), State::Intact))); + // A scale with Scale Strokes & Effects and Transform Patterns keeps what it scaled. + let mut scaled = g.clone(); + let sc = Scaling { strokes: true, patterns: true, ..Scaling::default() }; + scaled.transform(Affine::scale(2.0), sc); + scaled.transform(Affine::scale(3.0), false); + let back = reread(&serde_json::to_value(&scaled).unwrap()); + let a = back.extras().generated.as_deref().unwrap(); + assert_eq!((a.stroke_scale, a.effect_scale, a.pattern_transform, a.state), (2.0, 1.0, Affine::scale(2.0), State::Intact)); + assert_eq!(a.transform, Affine::scale(6.0)); + // A transform that flattens it to a point, with Scale Strokes & Effects on, scales its + // strokes and effects by 0, and it reads back intact with those scales. + let mut flat = g.clone(); + flat.transform(Affine::new([0.0; 6]), Scaling { strokes: true, effects: Some(|_, _| {}), ..Scaling::default() }); + let back = reread(&serde_json::to_value(&flat).unwrap()); + let a = back.extras().generated.as_deref().unwrap(); + assert_eq!((a.stroke_scale, a.effect_scale, a.state), (0.0, 0.0, State::Intact)); + } + + /// Art that doesn't match the file's hash, and fields that can't be read, keep the art and say + /// how the object was read; a garbled id is never kept. + #[test] + fn damaged_fields_and_changed_art_keep_the_art() { + let g = art(); + let v = serde_json::to_value(&g).unwrap(); + let state = |v: &Value| reread(v).extras().generated.as_ref().map(|a| (a.plugin.clone(), a.state)); + // The art edited, with the hash of the art before. + let mut edited = g.clone(); + if let Some(c) = edited.children_mut().and_then(|c| c.first_mut()) { + Arc::make_mut(c).transform(Affine::translate((1.0, 0.0)), false); + } + let mut changed = serde_json::to_value(&edited).unwrap(); + changed["generated"]["hash"] = v["generated"]["hash"].clone(); + assert_eq!(state(&changed), Some(("org.example.gen".into(), State::Changed))); + let mut no_hash = v.clone(); + no_hash["generated"].as_object_mut().unwrap().remove("hash"); + assert_eq!(state(&no_hash), Some(("org.example.gen".into(), State::Changed))); + for (field, bad) in [ + ("plugin", json!("../evil")), + ("plugin", json!("x".repeat(65))), + ("plugin", json!("")), + ("plugin", json!("a\u{0}b")), + ("plugin", json!(7)), + ("params", json!([1, 2])), + ("params", json!({"blob": "x".repeat(MAX_PARAMS_BYTES)})), + ("transform", json!("sideways")), + ("transform", Value::Null), + ("strokeScale", json!(-2.0)), + ("strokeScale", Value::Null), + ("strokeScale", json!("big")), + ("effectScale", json!(-0.5)), + ("patternTransform", json!([1, 0, 0, 1, 0])), + ("patternTransform", Value::Null), + ("effectScale", Value::Null), + ("damaged", json!(true)), + ("damaged", json!("no")), + ] { + let mut w = v.clone(); + w["generated"][field] = bad; + let back = reread(&w); + let a = back.extras().generated.as_ref().unwrap(); + assert_eq!(a.state, State::Damaged, "{field}"); + assert!(a.plugin.is_empty() || a.plugin == "org.example.gen", "{field}: {}", a.plugin); + assert_eq!(back.children(), g.children(), "{field}"); + // Saved again and read back, it stays damaged. + let again = reread(&serde_json::to_value(&back).unwrap()); + assert_eq!(again.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged), "{field} saved again"); + } + // Not an object at all. + let mut w = v.clone(); + w["generated"] = json!("art"); + assert_eq!(state(&w), Some((String::new(), State::Damaged))); + // A null field is read as a field that can't be read, not as an absent one, from a value + // and from a file's text; the art stays, and saved again the object stays damaged. + let mut w = v.clone(); + w["generated"] = Value::Null; + assert_eq!(state(&w), Some((String::new(), State::Damaged))); + let back: Node = serde_json::from_str(&w.to_string()).unwrap(); + assert_eq!(back.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged)); + assert_eq!(back.children(), g.children()); + let again = reread(&serde_json::to_value(&back).unwrap()); + assert_eq!(again.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged)); + // On a path the field is dropped, and the path stays as it was. + let path = g.children().unwrap()[0].clone(); + let mut p = serde_json::to_value(&*path).unwrap(); + p["generated"] = v["generated"].clone(); + let back = reread(&p); + assert!(back.extras().generated.is_none()); + assert_eq!(back, *path); + // A name is cut to its limit and loses control characters. + let mut w = v.clone(); + w["generated"]["name"] = json!(format!("A\u{202e}\n{}", "n".repeat(100))); + let back = reread(&w); + let name = &back.extras().generated.as_ref().unwrap().name; + assert_eq!(name.chars().count(), MAX_NAME); + assert!(!name.chars().any(char::is_control)); + } +} diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index 34453234ec..0e1673580a 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -82,6 +82,7 @@ impl Paths { /// isn't in the table or it, or a node it is in, was removed. pub(crate) fn get(&self, id: &NodeId) -> Option>> { let e = (*self.table.ids.get(id)?)?; + note_path_copy(); let mut path = Vec::new(); let mut cur = e; // Each step goes to a parent entry, made before its children: at most `at.len()` steps. @@ -96,6 +97,29 @@ impl Paths { } Some(None) } + /// The node with `id` in `layers` at the place the table has for it, found without copying its index path: `None` + /// when the table does not have one place for `id`, its path is deeper than [`NODE_IN_DEPTH`], or the node there + /// does not have the id (the tree changed). The caller then looks it up as [`crate::Document::index_path`] does. + pub(crate) fn node_in<'a>(&self, layers: &'a [Arc], id: NodeId) -> Option<&'a Node> { + let mut cur = (*self.table.ids.get(&id)?)?; + let mut steps = [0u32; NODE_IN_DEPTH]; + let mut depth = 0; + loop { + let &(parent, i) = self.table.at.get(cur as usize)?; + *steps.get_mut(depth)? = self.shifted(parent, i)?; + depth += 1; + if parent == u32::MAX { + break; + } + cur = parent; + } + let mut path = steps[..depth].iter().rev(); + let mut node: &Node = layers.get(*path.next()? as usize)?; + for &i in path { + node = node.children()?.get(i as usize)?; + } + (node.id == id).then_some(node) + } /// Where the table has `id` as it was built: its parent's entry and its index among its /// siblings then; `None` when the id isn't in the table or appears more than once. pub(crate) fn table_place(&self, id: &NodeId) -> Option<(u32, u32)> { @@ -170,6 +194,25 @@ pub(crate) fn note_path_lookup() { PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1)); } +/// The deepest index path [`Paths::node_in`] follows without copying it. +const NODE_IN_DEPTH: usize = 32; + +thread_local! { + /// [`path_copies`] of this thread. + static PATH_COPIES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many index paths the lookup cache has copied out on this thread, one for each [`crate::Document::index_path`] +/// that it answered. [`crate::Document::node`] reads the node from the cache without one. +pub fn path_copies() -> u64 { + PATH_COPIES.get() +} + +/// Adds one to [`path_copies`]. +fn note_path_copy() { + PATH_COPIES.set(PATH_COPIES.get().saturating_add(1)); +} + /// The cache, shared by clones of a document (each checks every path it uses against its own tree), /// the lookups that missed it, and the nodes removed from the tree since it was built. #[derive(Default)] diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index dfe6e22e73..470b0a94c4 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -18,12 +18,13 @@ pub mod decode; pub mod depth; pub mod dimension; pub mod flare; +pub mod generated; pub mod graph; mod halftone_radii; pub mod hit; mod id_index; pub mod image_quad; -pub use id_index::{path_lookups, tree_walks}; +pub use id_index::{path_copies, path_lookups, tree_walks}; pub mod inks; mod inline; pub mod intertwine; diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index 2fda2934b9..f557b5cb1f 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -385,26 +385,53 @@ fn find_type(n: &Node, typed: &mut std::collections::HashSet) -> bool { /// those axes. A character's strokes reach as far past its glyphs as past the laid-out box. Type /// that draws nothing has its laid-out box with `blank_type_box`, and no box without it. fn content_box(n: &Arc, stroked: bool, to: Affine, blank_type_box: bool) -> Option { - let mut typed = std::collections::HashSet::new(); - find_type(n, &mut typed); + let mut typed = Typed::default(); + find_type(n, &mut typed.holds); content_box_in(n, stroked, to, &typed, blank_type_box) } -/// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]). -fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collections::HashSet, blank_type_box: bool) -> Option { - // `n` in the axes of `to`. - let moved = || { - if to == Affine::IDENTITY { - return std::borrow::Cow::Borrowed(&**n); - } - let mut m = (**n).clone(); - m.transform(to, true); - std::borrow::Cow::Owned(m) - }; - let own = |m: &Node| if stroked { m.visual_bounds() } else { m.geometric_bounds() }; - if !typed.contains(&(Arc::as_ptr(n) as usize)) { - return own(&moved()); +/// The objects in an envelope's contents that hold type ([`find_type`]), by address, and the +/// boxes [`content_box_in`] has measured for them with their strokes, so that measuring a +/// container's own strokes along its members ([`container_strokes_in`]) does not measure them +/// again. +#[derive(Default)] +struct Typed { + holds: std::collections::HashSet, + stroked: std::cell::RefCell>>, +} + +/// `n` in the axes of `to`, with its strokes scaled as [`Node::transform`] scales them. +fn moved_into(n: &Node, to: Affine) -> std::borrow::Cow<'_, Node> { + if to == Affine::IDENTITY { + return std::borrow::Cow::Borrowed(n); } + let mut m = n.clone(); + m.transform(to, true); + std::borrow::Cow::Owned(m) +} + +/// [`content_box`], with the objects in `n` that hold type ([`Typed`]). +fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &Typed, blank_type_box: bool) -> Option { + let key = Arc::as_ptr(n) as usize; + if !typed.holds.contains(&key) { + let m = moved_into(n, to); + return if stroked { m.visual_bounds() } else { m.geometric_bounds() }; + } + if !stroked { + return typed_box_in(n, false, to, typed, blank_type_box); + } + if let Some(b) = typed.stroked.borrow().get(&key) { + return *b; + } + let b = typed_box_in(n, true, to, typed, blank_type_box); + typed.stroked.borrow_mut().insert(key, b); + b +} + +/// [`content_box_in`] of `n`, which holds type. +fn typed_box_in(n: &Arc, stroked: bool, to: Affine, typed: &Typed, blank_type_box: bool) -> Option { + let moved = || moved_into(n, to); + let own = |m: &Node| if stroked { m.visual_bounds() } else { m.geometric_bounds() }; match &n.kind { NodeKind::Text(t) => { // Type in perspective: its outlines as its projection draws them. @@ -445,11 +472,16 @@ fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collect let members = n.editing_children().iter(); if stroked { // The container's own strokes, scaled by `to` as `Node::transform` scales them, - // without copying its members. + // measured along its members as in `Node::visual_bounds`. let mut own_strokes = Node::new(n.id, NodeKind::Group { children: Vec::new(), clip: false }); own_strokes.appearance = n.appearance.clone(); own_strokes.transform(to, true); - own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed, blank_type_box))) + let painted = own_strokes.appearance.painted_strokes().next().is_some(); + members.fold(None, |acc, c| { + let b = content_box_in(c, true, to, typed, blank_type_box); + let own = if painted { container_strokes_in(c, &own_strokes.appearance, Some(b), to, typed, blank_type_box) } else { None }; + vectorcraft_geom::union_opt(vectorcraft_geom::union_opt(acc, b), own) + }) } else { members .filter(|c| c.visible || !layer) @@ -460,6 +492,44 @@ fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collect } } +/// The box the strokes of `appearance`, the appearance of a group or layer that holds `n` scaled +/// by `to`, paint along `n` in the axes of `to`, as [`Node::painted_by_container`] measures them; +/// `measured` is the box [`content_box_in`] gives `n` with its strokes, when known. Type, alone or +/// in a clip group, has that box grown by the farthest the strokes can reach +/// ([`crate::Appearance::outset`]); the strokes paint nothing round hidden members and guides. +fn container_strokes_in( + n: &Arc, + appearance: &crate::Appearance, + measured: Option>, + to: Affine, + typed: &Typed, + blank_type_box: bool, +) -> Option { + if !n.visible || n.is_guide() { + return None; + } + if !typed.holds.contains(&(Arc::as_ptr(n) as usize)) { + if to == Affine::IDENTITY { + return n.painted_by_container(appearance, None); + } + // Moved with its own strokes scaled, as `content_box_in` moves it, for a member measured + // by its visual box. + let mut m = (**n).clone(); + m.transform(to, true); + return m.painted_by_container(appearance, None); + } + match &n.kind { + NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } if !n.is_compound_shape() => n + .editing_children() + .iter() + .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, container_strokes_in(c, appearance, None, to, typed, blank_type_box))), + _ => { + let o = appearance.outset(); + measured.unwrap_or_else(|| content_box_in(n, true, to, typed, blank_type_box)).map(|b| b.inflate(o, o)) + } + } +} + /// The lengths the top, bottom, left and right [`EnvelopeOptions::bounds_margin`] of content with /// geometric bounds `plain` are shares of: its height for the top and bottom and its width for the /// left and right. A side shorter than 1e-6 pt takes the other side's length, so a stroked straight @@ -881,6 +951,57 @@ mod tests { assert!(content_box(&nested, false, Affine::IDENTITY, true).is_some()); } + /// A group of type and a square with its own 10 pt miter-joined stroke reaches 5 pt past the + /// square in a scaled frame, as the group moved into the frame does ([`Node::visual_bounds`]), + /// not the 50 pt a miter spike could reach. Round a clip group they reach that far past its + /// box, with the clipping path's own stroke scaled into the frame, and in nested groups too. + #[test] + fn a_groups_own_miter_stroke_is_measured_along_its_members_with_type() { + let paint = |fill, stroke, w| crate::Appearance::basic(fill, stroke, w); + let path = |id, r: Rect| { + let square = vectorcraft_geom::shapes::rectangle(r); + Arc::new(Node::path(NodeId(id), square, paint(vectorcraft_color::Paint::solid(Color::BLACK), vectorcraft_color::Paint::None, 0.0))) + }; + let text = type_node(1, "Type"); + let mut group = Node::group(NodeId(2), vec![text, path(3, Rect::new(100.0, 100.0, 200.0, 200.0))]); + group.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into(); + assert_eq!(group.appearance.outset(), 50.0, "a 10 pt miter-joined stroke can reach 50 pt"); + let group = Arc::new(group); + let to = Affine::scale(0.5); + let mut moved = (*group).clone(); + moved.transform(to, true); + let want = moved.visual_bounds(); + // The square's lower right corner, 100 pt in the frame, with half the 5 pt scaled stroke. + assert_eq!(want.map(|b| (b.x1, b.y1)), Some((102.5, 102.5))); + assert_eq!(content_box(&group, true, to, true), want); + // A clip group whose clipping path has a 40 pt stroke, which the group's own strokes grow + // by their reach, measured with that stroke scaled into the frame. + let mut clip = (*path(5, Rect::new(300.0, 300.0, 400.0, 400.0))).clone(); + clip.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 40.0).into(); + let clipped = + Node::new(NodeId(4), NodeKind::Group { children: vec![Arc::new(clip), path(6, Rect::new(320.0, 320.0, 380.0, 380.0))], clip: true }); + let mut group = Node::group(NodeId(2), vec![type_node(1, "Type"), Arc::new(clipped)]); + group.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into(); + let group = Arc::new(group); + let mut moved = (*group).clone(); + moved.transform(to, true); + let want = moved.visual_bounds(); + // 200 pt in the frame, with half the 20 pt scaled clip stroke and the 25 pt scaled reach. + assert_eq!(want.map(|b| (b.x1, b.y1)), Some((235.0, 235.0))); + assert_eq!(content_box(&group, true, to, true), want); + // Stroked groups of type nested in plain groups, each measured once. + let mut nested = group; + for i in 0..50 { + let plain = Arc::new(Node::group(NodeId(100 + 2 * i), vec![nested])); + let mut stroked = Node::group(NodeId(101 + 2 * i), vec![type_node(1, "Type"), plain]); + stroked.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into(); + nested = Arc::new(stroked); + } + let mut moved = (*nested).clone(); + moved.transform(to, true); + assert_eq!(content_box(&nested, true, to, true), moved.visual_bounds()); + } + /// A warp envelope of `style` at `bend` with map `version` around a 200×100 rectangle at /// (100, 50). fn warp_node(style: &str, bend: f64, h: f64, version: u32) -> Node { diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index a1bfaefe7d..685d4dcec5 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -286,6 +286,10 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> u .map_or(0, |m| ALLOC + size_of::() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3); b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::() + json_bytes(t)); b += e.flare.as_ref().map_or(0, |f| ALLOC + size_of::() + json_bytes(&f.params)); + b += e + .generated + .as_ref() + .map_or(0, |g| ALLOC + size_of::() + g.plugin.capacity() + g.name.capacity() + map_bytes(&g.params)); b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::() + path_bytes(a)); if e.intertwine_tiers.capacity() > 0 { b += ALLOC + e.intertwine_tiers.capacity() * size_of::() + e.intertwine_tiers.iter().map(path_bytes).sum::(); diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 0eed9c7829..9dbb409706 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -96,6 +96,9 @@ pub struct NodeExtras { /// (top left, top right, bottom right, bottom left in pixel space) stand on the page when they /// do not make a parallelogram, which its transform alone could place ([`crate::image_quad`]). pub image_quad: Option>, + /// Generated art object: the generator plug-in and parameters its group's children were drawn + /// with (`plugin.generate`); its ordinary group children hold its art ([`crate::generated`]). + pub generated: Option>, } /// No extras: what [`Node::extras`] gives for a node without any. @@ -129,6 +132,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { warp_piece: false, clip_pieces: false, image_quad: None, + generated: None, }; /// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 0e15c90e94..39b39fc294 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -463,14 +463,76 @@ impl Node { self.visual(Some(symbols)) } - /// The visual box of a group or layer without a clipping path, from the visual boxes of its - /// [`Node::editing_children`]: for a walk that measures the members as well. + /// A box round a group or layer without a clipping path, from boxes round its + /// [`Node::editing_children`], grown by the farthest its own strokes can reach from any path + /// ([`Appearance::outset`]): for boxes measured where the members' shapes are not at hand. + /// [`Node::visual_of_measured_members`] measures the strokes along the members. pub fn visual_of_members(&self, members: impl Iterator>) -> Option { // The container's own strokes paint around its members. let o = self.appearance.outset(); members.fold(None, vectorcraft_geom::union_opt).map(|b| b.inflate(o, o)) } + /// The visual box of a group or layer without a clipping path, from its + /// [`Node::editing_children`] paired with their visual boxes: for a walk that measures the + /// members as well. The container's own strokes are measured along the shape of each member + /// path and compound path, at any depth in its groups; they paint nothing round images, symbol + /// instances, guides and hidden members, and grow the box of any other member by the farthest + /// they can reach ([`Appearance::outset`]), measured with `symbols` as in + /// [`Node::visual_bounds_with`]. + pub fn visual_of_measured_members<'a>( + &self, + members: impl Iterator)>, + symbols: Option<&SymbolBoxes>, + ) -> Option { + let stroked = self.appearance.painted_strokes().next().is_some(); + members.fold(None, |acc, (c, b)| { + let own = if stroked { c.strokes_of_container(&self.appearance, Some(b), symbols) } else { None }; + vectorcraft_geom::union_opt(vectorcraft_geom::union_opt(acc, b), own) + }) + } + + /// The box the strokes of `appearance`, the appearance of a group or layer that holds this + /// object, paint along it, measured with `symbols` as in [`Node::visual_bounds_with`]: the box + /// [`Node::visual_of_measured_members`] takes in for this member besides its own visual box. + pub fn painted_by_container(&self, appearance: &Appearance, symbols: Option<&SymbolBoxes>) -> Option { + appearance.painted_strokes().next()?; + self.strokes_of_container(appearance, None, symbols) + } + + /// The box the strokes of `appearance`, a container's, paint along this member, whose visual + /// box is `measured` when known: along the shape of a path or compound path, as it measures its + /// own strokes ([`Appearance::stroked_bounds`]); along the members of a group or layer without + /// a clipping path that is not a compound shape; nothing for a hidden member, a guide, an image + /// or a symbol instance, which the strokes do not paint; and the member's visual box grown by + /// the farthest the strokes can reach ([`Appearance::outset`]) for anything else. + fn strokes_of_container(&self, appearance: &Appearance, measured: Option>, symbols: Option<&SymbolBoxes>) -> Option { + if !self.visible || self.is_guide() { + return None; + } + match &self.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } => self.stroked_by(appearance, symbols), + NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } if !self.is_compound_shape() => self + .editing_children() + .iter() + .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.strokes_of_container(appearance, None, symbols))), + NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => None, + _ => { + let o = appearance.outset(); + measured.unwrap_or_else(|| self.visual(symbols)).map(|b| b.inflate(o, o)) + } + } + } + + /// The visual box of this path or compound path painted with the strokes of `appearance`, + /// measured along its shape ([`Appearance::stroked_bounds`]). + fn stroked_by(&self, appearance: &Appearance, symbols: Option<&SymbolBoxes>) -> Option { + // A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath. + let dots = appearance.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square)); + let b = self.drawn(symbols, dots).or_else(|| self.geometric(symbols))?; + Some(appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default())) + } + /// The box of [`Node::visual_bounds`], or of [`Node::visual_bounds_with`] when `symbols` is /// given. pub(crate) fn visual(&self, symbols: Option<&SymbolBoxes>) -> Option { @@ -485,7 +547,9 @@ impl Node { } } NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))), - NodeKind::Layer { .. } | NodeKind::Group { .. } => self.visual_of_members(self.editing_children().iter().map(|c| c.visual(symbols))), + NodeKind::Layer { .. } | NodeKind::Group { .. } => { + self.visual_of_measured_members(self.editing_children().iter().map(|c| (c.as_ref(), c.visual(symbols))), symbols) + } NodeKind::Blend { children, spec } => { let b = children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))); let o = crate::live::max_outset(children, symbols); @@ -495,12 +559,7 @@ impl Node { let o = crate::live::max_outset(content, symbols); self.geometric(symbols).map(|b| b.inflate(o, o)) } - NodeKind::Path { .. } | NodeKind::Compound { .. } => { - // A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath. - let dots = self.appearance.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square)); - let b = self.drawn(symbols, dots).or_else(|| self.geometric(symbols))?; - Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default())) - } + NodeKind::Path { .. } | NodeKind::Compound { .. } => self.stroked_by(&self.appearance, symbols), NodeKind::SymbolInstance { symbol, xf } => { let b = match symbols.and_then(|s| Some((s, s.art(symbol)?))) { Some((s, art)) if !s.art_strokes() => xf.transform_rect_bbox(art.geometric), @@ -552,19 +611,23 @@ impl Node { 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() - && let Some(dimension) = &mut e.dimension - { + /// Moves what `a` moves in the node's extras: a dimension's measurement, a flare's center and + /// end point, and the place a generator's art is drawn again at, with what `sc` scales. + fn transform_extras(&mut self, a: Affine, sc: &Scaling) { + let Some(e) = self.extras_if_any() else { return }; + if let Some(dimension) = &mut e.dimension { dimension.transform(a); } - // So does a flare's center and end point. - if let Some(e) = self.extras_if_any() - && let Some(flare) = &mut e.flare - { + if let Some(flare) = &mut e.flare { flare.transform(a); } + if let Some(generated) = &mut e.generated { + generated.transform(a, sc); + } + } + + fn transform_scaled(&mut self, a: Affine, sc: &Scaling) { + self.transform_extras(a, sc); // The path the objects are attached to, before it is transformed. let on_path_before = self.on_path_data().cloned(); // A distorted image's placement nearest its corners, before they are transformed (`None` diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index a7cd7986c4..8d6520265a 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -537,6 +537,52 @@ fn visual_of_members_unions_the_members_and_grows_by_the_group_stroke() { assert_eq!(g.visual_of_members([].into_iter()), None); } +/// A group's or layer's own miter-joined stroke is measured along its members' shapes, as a +/// path's is: a 10 pt stroke round a square reaches 5 pt past it, not the 50 pt a miter spike +/// could reach, through nested groups and in a turned frame too. It paints nothing round a hidden +/// member or an image. +#[test] +fn a_containers_own_miter_stroke_is_measured_along_its_members() { + use vectorcraft_color::{Color, Paint}; + let path = |id, r: Rect| Arc::new(Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0))); + let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0); + assert_eq!(stroke.outset(), 50.0, "a 10 pt miter-joined stroke can reach 50 pt"); + let stroked = |mut n: Node| { + n.appearance = stroke.clone().into(); + n + }; + let square = Rect::new(100.0, 100.0, 200.0, 200.0); + let around = Some(Rect::new(95.0, 95.0, 205.0, 205.0)); + assert_eq!(stroked(Node::group(NodeId(1), vec![path(2, square)])).visual_bounds(), around, "a group"); + let nested = Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(3), vec![path(2, square)]))]); + assert_eq!(stroked(nested.clone()).visual_bounds(), around, "a nested group"); + // Measured in a turned frame, as a box square to a turned selection is. + let turned = stroked(nested).bounds_in(&crate::Document::new(400.0, 400.0).symbol_boxes(), Affine::rotate(std::f64::consts::FRAC_PI_2), true); + let want = Rect::new(-205.0, 95.0, -95.0, 205.0); + assert!( + turned.is_some_and(|b| (b.x0 - want.x0).abs() + (b.y0 - want.y0).abs() + (b.x1 - want.x1).abs() + (b.y1 - want.y1).abs() < 1e-9), + "{turned:?}" + ); + let mut layer = Node::layer(NodeId(1), "Layer 1", LayerColor::Preset(0)); + if let NodeKind::Layer { children, .. } = &mut layer.kind { + children.push(path(2, square)); + } + assert_eq!(stroked(layer).visual_bounds(), around, "a layer"); + let mut hidden = (*path(3, Rect::new(100.0, 300.0, 200.0, 400.0))).clone(); + hidden.visible = false; + let image = ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: Affine::translate((500.0, 100.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let kids = vec![path(2, square), Arc::new(hidden), Arc::new(Node::new(NodeId(4), NodeKind::Image(Box::new(image))))]; + assert_eq!(stroked(Node::group(NodeId(1), kids)).visual_bounds(), Some(Rect::new(95.0, 95.0, 510.0, 400.0)), "a hidden member and an image"); +} + /// Type's visual bounds grow by how far its character strokes paint past the glyphs: half the /// weight centred, the whole weight outside, nothing inside; scaled with the type. #[test] diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index d9642e7866..d543c9d9e1 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -18,6 +18,7 @@ impl Serialize for Node { use crate::skip::{is_default, is_one, is_true}; use serde::ser::SerializeStruct; let e = self.extras(); + let generated = crate::generated::written(e.generated.as_deref()); // As the derive did: the fields written, then each field written or skipped in order. let skips = [ false, @@ -61,6 +62,7 @@ impl Serialize for Node { is_default(&e.warp_piece), is_default(&e.clip_pieces), e.image_quad.is_none(), + generated.is_none(), ]; let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; let mut skip = skips.into_iter(); @@ -87,6 +89,8 @@ impl Serialize for Node { field!("type_outlines", &e.type_outlines); field!("pixelated", &e.pixelated); field!("shaper", &e.shaper); + // A generated art object's art, written while this lives, holds plain art only. + let _inside = generated.map(|_| crate::generated::Inside::enter()); field!("kind", &self.kind); field!("graphic_style", &e.graphic_style); field!("attrs", &e.attrs); @@ -110,6 +114,7 @@ impl Serialize for Node { field!("warp_piece", &e.warp_piece); field!("clip_pieces", &e.clip_pieces); field!("image_quad", &e.image_quad); + field!("generated", &generated.map(|g| crate::generated::Wire::of(g, self))); st.end() } } @@ -265,6 +270,14 @@ pub(super) struct NodeWire { clip_pieces: bool, #[serde(default, deserialize_with = "image_corners")] image_quad: Option>, + /// Read as it is and checked against the node's kind and art ([`crate::generated`]). + #[serde(default, deserialize_with = "present_value")] + generated: Option, +} + +/// A field's value as a file holds it, a null included: only an absent field is none. +fn present_value<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + serde_json::Value::deserialize(d).map(Some) } /// A distorted image's corners as a file holds them: a list of exactly four points, else none (the @@ -455,7 +468,7 @@ fn image_corners<'de, D: serde::Deserializer<'de>>(d: D) -> Result for Node { - fn from(w: NodeWire) -> Self { + fn from(mut w: NodeWire) -> Self { // Corners an image cannot take are dropped, so a later transform cannot make them its own. let image_quad = match &w.kind { NodeKind::Image(im) => w.image_quad.filter(|q| crate::image_quad::check_for(im, q).is_ok()), @@ -491,6 +504,7 @@ impl From for Node { warp_piece: w.warp_piece, clip_pieces: w.clip_pieces, image_quad, + generated: w.generated.and_then(|g| crate::generated::read(g, &mut w.kind)), }; Node { id: w.id, diff --git a/crates/doc/src/orient.rs b/crates/doc/src/orient.rs index a2ff76d83f..c3a87988bc 100644 --- a/crates/doc/src/orient.rs +++ b/crates/doc/src/orient.rs @@ -121,10 +121,16 @@ impl Node { pub fn bounds_in(&self, symbols: &SymbolBoxes, a: Affine, visual: bool) -> Option { match &self.kind { NodeKind::Group { clip: false, .. } => { - let b = self.editing_children().iter().fold(None, |acc, c| union_opt(acc, c.bounds_in(symbols, a, visual))); - // The group's own strokes paint around its members (as in `visual_bounds`). - let o = if visual { self.appearance.outset() } else { 0.0 }; - b.map(|b| b.inflate(o, o)) + // The group's own strokes paint along its members, placed by `a` (as in `visual_bounds`). + let stroked = visual && self.appearance.painted_strokes().next().is_some(); + self.editing_children().iter().fold(None, |acc, c| { + let own = stroked.then(|| { + let mut placed = (**c).clone(); + placed.transform(a, false); + placed.painted_by_container(&self.appearance, Some(symbols)) + }); + union_opt(union_opt(acc, c.bounds_in(symbols, a, visual)), own.flatten()) + }) } NodeKind::Group { children, clip: true } => { let clip = children.first()?; diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs index b2c00d8ab3..f4c0bfb614 100644 --- a/crates/doc/src/pattern.rs +++ b/crates/doc/src/pattern.rs @@ -425,9 +425,13 @@ pub fn uses_pattern(n: &Node, name: Option<&str>) -> bool { } /// Transform Patterns without Transform Objects: `m` moves the pattern tiles of `n` and of -/// everything inside it, and the art stays where it is. +/// everything inside it, and the art stays where it is. A generated art object keeps the move, so +/// its art drawn again has its tiles moved too. pub fn transform_patterns_only(n: &mut Node, m: Affine) { transform_pattern_paints(n, m); + if let Some(g) = n.extras_if_any().and_then(|e| e.generated.as_deref_mut()) { + g.pattern_transform = m * g.pattern_transform; + } for c in n.children_mut().into_iter().flatten() { transform_patterns_only(Arc::make_mut(c), m); } diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index f83b0e9329..9189302bc0 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -600,21 +600,40 @@ pub const SLANT_INSTANCES: usize = 4096; impl crate::Node { /// Does a visible stroke of this object, of an object in it or of an object in a symbol /// instance's art from `symbols`, placed by `a`, stop at the corners of a segment at a slant - /// ([`Appearance::has_slanted_stroke_corners`])? Past [`SLANT_INSTANCES`] instances it answers - /// yes. + /// ([`Appearance::has_slanted_stroke_corners`])? The strokes of a group or layer without a + /// clipping path count along the paths and compound paths in it, which they paint along + /// ([`crate::Node::painted_by_container`]). Past [`SLANT_INSTANCES`] instances it answers yes. pub fn has_slanted_stroke_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool { - self.slanted_corners(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES)) + self.slanted_corners(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES), &[]) } - /// [`Self::has_slanted_stroke_corners`] with `left` instances still to look into. - fn slanted_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell) -> bool { + /// [`Self::has_slanted_stroke_corners`] with `left` instances still to look into, and the + /// appearances of the groups and layers around this object whose strokes paint along it in + /// `around`. + fn slanted_corners( + &self, + symbols: &crate::SymbolBoxes, + a: vectorcraft_geom::Affine, + left: &std::cell::Cell, + around: &[&Appearance], + ) -> bool { if let crate::NodeKind::SymbolInstance { symbol, xf } = &self.kind { let Some(l) = left.get().checked_sub(1) else { return true }; left.set(l); - return symbols.measure_art(symbol, |art| art.slanted_corners(symbols, a * *xf, left)).unwrap_or(false); + return symbols.measure_art(symbol, |art| art.slanted_corners(symbols, a * *xf, left, &[])).unwrap_or(false); } - (self.appearance.has_cornered_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_stroke_corners(&bp, a))) - || self.children().is_some_and(|c| c.iter().any(|c| c.slanted_corners(symbols, a, left))) + let slanted = |ap: &Appearance| ap.has_cornered_stroke() && self.stroke_path().is_some_and(|bp| ap.has_slanted_stroke_corners(&bp, a)); + let shaped = matches!(self.kind, crate::NodeKind::Path { .. } | crate::NodeKind::Compound { .. }); + if slanted(&self.appearance) || shaped && around.iter().any(|ap| slanted(ap)) { + return true; + } + let plain = + matches!(self.kind, crate::NodeKind::Group { clip: false, .. } | crate::NodeKind::Layer { clip: false, .. }) && !self.is_compound_shape(); + let mut inner: Vec<&Appearance> = if plain { around.to_vec() } else { vec![] }; + if plain && self.appearance.has_cornered_stroke() { + inner.push(&self.appearance); + } + self.children().is_some_and(|c| c.iter().any(|c| c.slanted_corners(symbols, a, left, &inner))) } } diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index f0b8a5609f..02c4391921 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -187,6 +187,48 @@ impl Selection { self.key_anchor = None; } } + /// Select `id` itself in place of the selected object around it, keeping the rest of that + /// object selected. The outermost selected object that holds `id` (a group, or a compound path + /// selected whole) and every selected object between it and `id` leave the selection. In their + /// place go, at the outermost one's position, the objects inside them on the way down to `id`, + /// level by level: at each level the objects beside the one that holds `id`, and at the last + /// level `id` and the objects beside it, each level in stacking order. A Shaper Group's + /// original shapes, and objects that are hidden, locked or on a locked artboard + /// ([`Document::is_editable`]), are not taken in. + /// + /// When `id` is also selected itself, it keeps its place in the selection. + /// + /// Returns whether the selection changed. It does not change when `id` is not inside a selected + /// object, is inside one that is partly selected (anchors or segments), is one of a selected + /// Shaper Group's original shapes, or is hidden, locked or on a locked artboard itself. + pub fn expand_to(&mut self, doc: &Document, id: NodeId) -> bool { + let Some(chain) = doc.ancestry(id) else { return false }; + let Some(top) = chain.iter().position(|a| self.contains(*a)) else { return false }; + let holder = chain[top]; + if self.anchors.contains_key(&holder) || self.segments.contains_key(&holder) { + return false; + } + let editable = doc.editable(); + let mut members = Vec::new(); + for pair in chain[top..].windows(2) { + let Some(n) = doc.node(pair[0]) else { return false }; + let originals = usize::from(n.extras().shaper.is_some()); + let children = n.children().map(Vec::as_slice).unwrap_or_default(); + if children.iter().take(originals).any(|c| c.id == pair[1]) { + return false; + } + members.extend(children.iter().skip(originals).map(|c| c.id).filter(|c| editable(*c) && (*c == id || *c != pair[1]))); + } + if !members.contains(&id) { + return false; + } + let around: HashSet = chain[top..chain.len() - 1].iter().copied().collect(); + let at = self.objects.iter().take_while(|o| **o != holder).filter(|o| !around.contains(o)).count(); + self.remove_all(around); + let selected: HashSet = self.objects.iter().copied().collect(); + self.objects.splice(at..at, members.into_iter().filter(|m| !selected.contains(m))); + true + } /// [`Self::add`] for each of `ids` in order, going through the selected objects once. pub fn add_all(&mut self, ids: impl IntoIterator) { self.each(ids, false); diff --git a/crates/doc/src/selection/tests.rs b/crates/doc/src/selection/tests.rs index 60ad1b4328..46f726f1e8 100644 --- a/crates/doc/src/selection/tests.rs +++ b/crates/doc/src/selection/tests.rs @@ -45,6 +45,80 @@ fn remove_all_does_what_removing_each_does() { assert_eq!(none, s); } +/// `expand_to` selects a member of a selected group in the group's place, beside the group's other +/// objects at each level down to it, and leaves a selection it cannot open alone. +#[test] +fn expand_to_selects_a_member_in_place_of_its_selected_group() { + let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let [x, g, e, h, b, c, dd] = [(); 7].map(|_| d.alloc_id()); + let path = |id| Arc::new(Node::path(id, rect(), crate::Appearance::default_art())); + let inner = Node::group(h, vec![path(b), path(c)]); + let group = Node::group(g, vec![path(e), Arc::new(inner), path(dd)]); + d.insert(Some(l), 0, Node::path(x, rect(), crate::Appearance::default_art())).unwrap(); + d.insert(Some(l), 1, group).unwrap(); + let mut s = Selection::default(); + s.set([x, g]); + s.key = Some(g); + assert!(s.expand_to(&d, b)); + assert_eq!(s.objects, [x, e, dd, b, c], "the group's objects beside the inner group, then the inner group's"); + assert_eq!(s.key, None, "the group leaves the selection with its key"); + assert!(!s.expand_to(&d, b), "a member selected itself with nothing selected around it"); + assert!(!s.expand_to(&d, x), "an object inside nothing selected"); + // A member selected beside the group around it keeps its place. + let mut with_member = Selection::default(); + with_member.set([b, g]); + assert!(with_member.expand_to(&d, b)); + assert_eq!(with_member.objects, [b, e, dd, c]); + // An inner group selected beside the group leaves the selection too. + let mut both = Selection::default(); + both.set([h, g]); + assert!(both.expand_to(&d, b)); + assert_eq!(both.objects, [e, dd, b, c]); + // A group with anchors recorded for it is left as it is. + let mut partly = Selection::default(); + partly.set([g]); + partly.anchors.insert(g, BTreeSet::from([(0, 0)])); + let before = partly.clone(); + assert!(!partly.expand_to(&d, b)); + assert_eq!(partly, before); + // A Shaper Group opens to its faces and never to its original shapes. + let [shaper, sources, o1, o2, face] = [(); 5].map(|_| d.alloc_id()); + let mut sources_group = Node::group(sources, vec![path(o1), path(o2)]); + sources_group.name = Some(crate::shaper::SOURCES.into()); + let mut shaper_group = Node::group(shaper, vec![Arc::new(sources_group), path(face)]); + shaper_group.extras_mut().shaper = Some(Box::default()); + d.insert(Some(l), 2, shaper_group).unwrap(); + let mut shaped = Selection::default(); + shaped.set([shaper]); + let before = shaped.clone(); + assert!(!shaped.expand_to(&d, o1), "an original shape"); + assert_eq!(shaped, before); + assert!(shaped.expand_to(&d, face)); + assert_eq!(shaped.objects, [face]); + // Hidden and locked objects beside the member stay out of the selection. + let [k, shown, hidden, locked, last] = [(); 5].map(|_| d.alloc_id()); + let mut hidden_path = Node::path(hidden, rect(), crate::Appearance::default_art()); + hidden_path.visible = false; + let mut locked_path = Node::path(locked, rect(), crate::Appearance::default_art()); + locked_path.locked = true; + let kept = Node::group(k, vec![path(shown), Arc::new(hidden_path), Arc::new(locked_path), path(last)]); + d.insert(Some(l), 3, kept).unwrap(); + let mut with_locked = Selection::default(); + with_locked.set([k]); + assert!(with_locked.expand_to(&d, last)); + assert_eq!(with_locked.objects, [shown, last]); + // A locked or hidden member itself does not open the group. + for target in [locked, hidden] { + let mut s = Selection::default(); + s.set([k]); + let before = s.clone(); + assert!(!s.expand_to(&d, target), "{target:?}"); + assert_eq!(s, before); + } +} + /// A selection with every field set: objects 1 to 6 with 3 listed twice, anchors, segments, a key, /// a key anchor, a target, slices, guides, a key guide, new art, a symbol part and an on-path member. fn seeded() -> Selection { diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 295c347765..4a8f6a9d71 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -579,3 +579,32 @@ fn nearest_finder_reads_one_path_per_object() { assert_eq!(path_lookups() - lookups, 0, "lookups by id"); assert_eq!(tree_walks() - walks, 0, "walks of the tree"); } + +/// `Document::node` reads a node from the lookup cache without copying its index path, in nested groups and after +/// objects were removed, and finds what a walk finds: 10,000 objects looked up one at a time copy no path. +#[test] +fn node_lookups_copy_no_index_path() { + let (mut d, ids) = squares(10_000); + let layer = d.layers[0].id; + let mut nested = vec![]; + for g in 0..50 { + let kids: Vec> = (0..4) + .map(|_| { + let id = d.alloc_id(); + nested.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())) + }) + .collect(); + let (gid, inner) = (d.alloc_id(), d.alloc_id()); + d.insert(Some(layer), g, Node::group(gid, vec![Arc::new(Node::group(inner, kids))])).unwrap(); + } + d.remove_many(&ids[..100]).unwrap(); + d.node(layer); + let copies = path_copies(); + let found = ids[100..].iter().chain(&nested).filter(|id| d.node(**id).is_some_and(|n| n.id == **id)).count(); + assert_eq!(found, ids.len() - 100 + nested.len()); + assert_eq!(path_copies() - copies, 0, "index paths copied"); + assert!(ids[..100].iter().all(|id| d.node(*id).is_none()), "removed objects are not found"); + agree(&d, &ids[..200], "after remove_many"); + agree(&d, &nested, "nested"); +} diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index b3fa27aee1..0efaffafeb 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -1780,6 +1780,44 @@ fn perspective_projects_the_masks_in_a_symbols_art() { assert_eq!(mask, path, "and so is its mask"); } +/// The images in the art of a symbol instance drawn through a projection have their corners where +/// the projection takes them, beside a path, in a group and in the art of a linked mask, and an +/// image's own linked mask is projected with it. +#[test] +fn a_projection_puts_the_corners_of_the_images_in_a_symbols_art_where_it_takes_them() { + let masked = masked_by(white_square(22), image_node(23), true); + let art = Node::group(NodeId(20), vec![Arc::new(image_node(21)), Arc::new(Node::group(NodeId(24), vec![Arc::new(masked)]))]); + // An image with a linked mask of its own, whose path has a linked mask too. + let inner = masked_by(white_square(32), white_square(33), true); + let own = Node::group(NodeId(30), vec![Arc::new(masked_by(image_node(31), inner, true))]); + let at = vectorcraft_doc::PerspectiveAttachment { projection: Some([1.0, 0.2, 3.0, 0.1, 1.0, 2.0, 0.01, 0.02, 1.0]), ..Default::default() }; + let h = at.homography().unwrap(); + let mut instance = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "t".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + instance.extras_mut().perspective = Some(Box::new(at.clone())); + let out = crate::reshape::reshape(None, &instance, Some(&own)).unwrap(); + let mut masks = vec![]; + out.walk(&mut |c| masks.extend(c.image_corners().and(c.extras().mask.as_deref()).map(|m| m.art.clone()))); + let [mask] = masks.as_slice() else { panic!("one masked image: {out:?}") }; + assert!(mask.path_data() != white_square(32).path_data(), "the image's mask is projected"); + let inner = mask.extras().mask.as_deref().map(|m| m.art.path_data().cloned()); + assert_eq!(inner, Some(mask.path_data().cloned()), "and so is the mask on that mask's path"); + let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + instance.extras_mut().perspective = Some(Box::new(at)); + let out = crate::reshape::reshape(None, &instance, Some(&art)).unwrap(); + let want = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(|(x, y)| h.apply(vectorcraft_geom::Point::new(x, y)).unwrap()); + let mut images = vec![]; + out.walk(&mut |c| { + images.extend(c.image_corners()); + images.extend(c.extras().mask.as_deref().and_then(|m| m.art.image_corners())); + }); + assert_eq!(images.len(), 2, "{out:?}"); + for q in images { + for (got, want) in q.iter().zip(want) { + assert!(got.distance(want) < 1e-9, "{q:?} against {want:?}"); + } + } +} + /// A group with `effect` holding `n` vertical then `n` horizontal bars, 2 wide on a 4-unit /// pitch, each crossing every bar of the other direction: n² crossings. fn crossing_bars(n: usize, effect: &str) -> Node { diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 4d1c7b420f..82fcc1fd9d 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -1544,11 +1544,40 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option /// follow it. The type and live objects in the art of those masks are outlined and evaluated /// first ([`outlined_members`], with the symbols of `doc`). fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) { + project_art(art, h, doc, false); +} + +/// [`project_leaves`], the linked opacity mask of `art` itself included when `own`. +fn project_art(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>, own: bool) { project_paths(art, h); - each_linked_mask_mut(art, false, 0, &mut |m| { + each_linked_mask_mut(art, own, 0, &mut |m| { *m = outlined_mask_art(doc, m); project_paths(m, h); + project_image_masks(m, h, doc); }); + project_image_masks(art, h, doc); +} + +/// The art of the linked opacity masks of the images under `art` (`art` itself, and in groups and +/// layers, as [`project_images`] reaches them) projected through `h` as [`project_leaves`] +/// projects art, the linked mask of that art's own root included, so that each mask stays on the +/// object it masks. Unlinked masks stay where they are. +fn project_image_masks(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) { + match &mut art.kind { + NodeKind::Image(_) => { + if let Some(m) = art.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|m| m.linked) { + let a = Arc::make_mut(&mut m.art); + *a = outlined_mask_art(doc, a); + project_art(a, h, doc, true); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + for c in children.iter_mut() { + project_image_masks(Arc::make_mut(c), h, doc); + } + } + _ => {} + } } /// `art`, the art of an opacity mask, with type and live objects in it outlined and evaluated @@ -1584,6 +1613,27 @@ fn project_paths(art: &mut Node, h: &vectorcraft_geom::Homography) { _ => {} } }); + project_images(art, h); +} + +/// Place the corners of every image under `art` (in groups and layers, as [`for_each_leaf`] reaches +/// paths) where the projective map `h` takes them, so that its pixels are drawn in perspective +/// between them ([`Node::set_image_corners`]). An image with a corner that `h` sends past its +/// horizon keeps its place, as the points of a path there do. +fn project_images(n: &mut Node, h: &vectorcraft_geom::Homography) { + match &mut n.kind { + NodeKind::Image(_) => { + if let Some([Some(a), Some(b), Some(c), Some(d)]) = n.image_corners().map(|q| q.map(|p| h.apply(p))) { + let _ = n.set_image_corners([a, b, c, d]); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + for c in children.iter_mut() { + project_images(Arc::make_mut(c), h); + } + } + _ => {} + } } /// The visible geometry effects of `n`'s own effect list, in order. diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index ea5d72f7ef..ef1608a5d9 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -1180,8 +1180,11 @@ impl Placed { } } -/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares; -/// the pairs they have not reached by then keep the order of their depths. +/// The most pairs of faces [`local_order`] compares, together with the steps it takes to break +/// rings of them ([`drawn_in_pairs_order`]), and the most pairs [`cut_stroke_faces`] compares. A +/// pair not compared by then adds no constraint on the order (the pairs that were compared can +/// still move its faces), and once the steps run out the first face left by depth goes next only +/// when no face can. const MAX_LOCAL_CHECKS: usize = 4_000_000; /// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other @@ -1412,11 +1415,11 @@ fn half(p: &[Point], values: &[f64], sign: f64) -> Vec { /// their depths where they overlap: the face nearer the viewer there goes after the other. A fill /// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each /// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays -/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`. +/// where its depth puts it. A cycle of such pairs is broken at one of its own faces +/// ([`drawn_in_pairs_order`]). /// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place: /// no face moves across it. Otherwise `order` as it is. fn local_order(faces: &[Placed], order: Vec) -> Vec { - use std::cmp::Reverse; // The faces of each shape that take part, from left to right for a sweep along x. let mut shapes: Vec> = vec![]; for (k, f) in faces.iter().enumerate() { @@ -1428,7 +1431,7 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { } shapes[f.member].push(k); } - if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) { + if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) || u32::try_from(faces.len()).is_err() { return order; } for list in &mut shapes { @@ -1471,9 +1474,9 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { // faces with a polygon and a plane that overlap goes in the order of their depths there. let mut sweep: Vec = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect(); sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0)); - // For each face, the faces drawn after it, and for each, how many go before it. - let mut after: Vec> = vec![vec![]; faces.len()]; - let mut waits = vec![0usize; faces.len()]; + // Each pair in its order: a face, and a face drawn after it (as `u32`: there are fewer faces + // than that, which is checked above). + let mut pairs: Vec<(u32, u32)> = vec![]; 'pairs: for (i, &k) in sweep.iter().enumerate() { let a = &faces[k]; for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) { @@ -1491,38 +1494,117 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue }; a_nearer }; - let (back, front) = if a_later { (j, k) } else { (k, j) }; - after[back].push(front); - waits[front] += 1; + pairs.push(if a_later { (j as u32, k as u32) } else { (k as u32, j as u32) }); } } - // Each step draws the face that comes first in `order` of those whose faces before are drawn. + // Breaking rings has what is left of the limit. + let last: Vec = faces.iter().map(|f| f.depth >= f64::MAX).collect(); + let mut room = MAX_LOCAL_CHECKS.saturating_sub(checks); + drawn_in_pairs_order(order, &position, &last, pairs, &mut room) +} + +/// `order` with each face after the faces that go before it: each of `pairs` is a face and a face +/// drawn after it, `position` is each face's place in `order`, and `last` says of each face +/// whether it is drawn last. Each step draws the face that comes first in `order` of those whose +/// faces before are drawn. A face drawn last goes only after every face before it in `order`, so +/// a face before it never waits for it or for a face after it: those pairs, with the face drawn +/// last itself or with a face that follows it, are drawn the wrong way round. +/// +/// When no face can go next, some of the faces left go before each other in a ring, or wait for a +/// face drawn last or one that follows it. The faces that go before the first face left in `order` +/// are followed back, among the faces that come before the next face drawn last, to the first +/// group found that waits for no other of them ([`RingFinder::behind`]): a ring, or one face. That +/// group gives up its face that comes first in `order`. So when the first face left is in the +/// group, it goes next, as it would with no ring looked for; when it only waits for the group, a +/// face of the group goes instead, and the only other pairs drawn the wrong way round are pairs of +/// a ring. +/// +/// Every face and pair looked at takes one from `room`. The search is kept from one stop to the +/// next and goes on from where it stopped, and a face that is drawn is dropped from a list the +/// next time the list is looked at, so rings of a few faces take a few steps a face whether they +/// stand apart, all lie behind one face or lie one behind the other. Two costs are not in +/// proportion to the faces. A ring that is still a ring after it gives up a face is walked again +/// from the face the search reached it by, so a large ring can cost about its pairs for each face +/// it gives up: the square of its faces, even when each waits for few others (3,200 faces with +/// four pairs each at random take about 3,000,000 steps). And a face at or +/// after the next face drawn last is passed over again each time a face that waits for it is +/// looked at. Once `room` runs out the first face left in `order` goes next, ring or not. +/// A first face left that waits only for the next face drawn last or faces after it goes next +/// with no search, at no cost. +/// +/// An `order` and `position` that do not agree, or a pair of a face that is not in them, give +/// `order` back. +/// +/// The pairs come at 8 bytes each and are dropped once the lists of the faces after each face +/// are made, 4 bytes a pair; the lists of the faces before each face, as many again, are made +/// when a ring is first looked for, a step a pair not taken from `room`, and only when the room +/// left is at least a quarter of the pairs: with less, no ring is looked for and the first face +/// left goes next. So a solid whose comparing of pairs leaves less than a quarter of its pairs +/// of the limit breaks its rings as before rings were looked for. +fn drawn_in_pairs_order(order: Vec, position: &[usize], last: &[bool], pairs: Vec<(u32, u32)>, room: &mut usize) -> Vec { + use std::cmp::Reverse; + let n = order.len(); + // `order` holds each face once when each face's place in it is the place `position` gives. + let agree = position.len() == n && last.len() == n && order.iter().enumerate().all(|(at, &k)| position.get(k) == Some(&at)); + if !agree || u32::try_from(pairs.len()).is_err() || pairs.iter().any(|&(back, front)| back as usize >= n || front as usize >= n) { + return order; + } + // For each face, how many faces not drawn yet go before it, and the faces drawn after it. + let mut waits = vec![0usize; n]; + for &(_, front) in &pairs { + waits[front as usize] += 1; + } + let after = Lists::from_pairs(n, pairs.iter().map(|&(back, front)| (back as usize, front as usize))); + drop(pairs); let mut ready: std::collections::BinaryHeap> = - (0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect(); + (0..n).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect(); // The faces drawn last, in `order`: each goes only after every face before it in `order`. - let last: Vec = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect(); + let lasts: Vec = order.iter().copied().filter(|&k| last[k]).collect(); let mut next_last = 0usize; - let mut drawn = vec![false; faces.len()]; - let mut out = Vec::with_capacity(order.len()); + let mut drawn = vec![false; n]; + let mut out = Vec::with_capacity(n); let mut first = 0usize; - while out.len() < order.len() { - while last.get(next_last).is_some_and(|&k| drawn[k]) { + let mut rings: Option = None; + // For each face, how many faces not drawn yet go before it among the first `counted` of + // `order`, which keeps up with the next face drawn last. + let mut early = vec![0u32; n]; + let mut counted = 0usize; + while out.len() < n { + while lasts.get(next_last).is_some_and(|&k| drawn[k]) { next_last += 1; } - let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]); + let limit = lasts.get(next_last).map_or(usize::MAX, |&k| position[k]); + while counted < limit.min(n) { + if let Some(&back) = order.get(counted).filter(|&&back| !drawn[back]) { + for &j in after.list(back) { + early[j as usize] += 1; + } + } + counted += 1; + } let k = match ready.peek() { Some(&Reverse((at, k))) if at < limit => { ready.pop(); k } _ => { - // A cycle, or the faces left to draw before a face drawn last wait for faces after - // it: the first face in `order` not drawn yet goes next. while order.get(first).is_some_and(|&k| drawn[k]) { first += 1; } - let Some(&k) = order.get(first) else { break }; - k + let Some(&next) = order.get(first) else { break }; + // The face drawn last goes in its turn, and so does a face that waits only for it or + // faces after it: no face it waits for can go first. Any other face waits for a + // face before the face drawn last: the group behind it gives up a face, while there + // is room to look for one. The lists of the faces before each face take a step a + // pair to make, which is not taken from `room`: they are made only when the room + // left is at least a quarter of the pairs, so making them costs no more than four + // times the room left. + let mut released = None; + let room_for_lists = rings.is_some() || room.saturating_mul(4) >= after.faces.len(); + if *room > 0 && position[next] < limit && early[next] > 0 && room_for_lists { + released = rings.get_or_insert_with(|| RingFinder::new(&after)).behind(next, &drawn, position, limit, room); + } + released.unwrap_or(next) } }; if drawn[k] { @@ -1530,8 +1612,13 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { } drawn[k] = true; out.push(k); - for &j in &after[k] { + let was_counted = position[k] < counted; + for &j in after.list(k) { + let j = j as usize; waits[j] = waits[j].saturating_sub(1); + if was_counted { + early[j] = early[j].saturating_sub(1); + } if waits[j] == 0 && !drawn[j] { ready.push(Reverse((position[j], j))); } @@ -1540,6 +1627,217 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { out } +/// A list of faces for each of some faces, all in one array: the faces after each face, or the +/// faces before it. +struct Lists { + /// The list of face `k` is `faces[starts[k]..starts[k + 1]]`. + starts: Vec, + faces: Vec, +} + +impl Lists { + /// For each of `n` faces, the second faces of the `pairs` it is first in, in the order of + /// `pairs`. There are fewer than 2^32 faces and pairs ([`drawn_in_pairs_order`] checks this); + /// a pair with a face that is not one of the `n` is left out. + fn from_pairs(n: usize, pairs: impl Iterator + Clone) -> Self { + let pairs = pairs.filter(move |&(first, second)| first < n && second < n); + let mut starts = vec![0u32; n + 1]; + for (first, _) in pairs.clone() { + if let Some(count) = starts.get_mut(first + 1) { + *count += 1; + } + } + for k in 1..starts.len() { + starts[k] += starts[k - 1]; + } + let mut filled = starts.clone(); + let mut faces = vec![0u32; starts.last().map_or(0, |&end| end as usize)]; + for (first, second) in pairs { + if let Some(at) = filled.get_mut(first) { + if let Some(slot) = faces.get_mut(*at as usize) { + *slot = second as u32; + } + *at += 1; + } + } + Lists { starts, faces } + } + + /// The list of face `k`; none for a face that is not one of them. + fn list(&self, k: usize) -> &[u32] { + let (Some(&start), Some(&end)) = (self.starts.get(k), self.starts.get(k + 1)) else { return &[] }; + self.faces.get(start as usize..end as usize).unwrap_or_default() + } + + /// Each list's faces and the face it is the list of, as pairs. + fn pairs(&self) -> impl Iterator + Clone + '_ { + (0..self.starts.len().saturating_sub(1)).flat_map(move |k| self.list(k).iter().map(move |&j| (k, j as usize))) + } +} + +#[cfg(test)] +thread_local! { + /// The entries of the lists of faces before each face that [`RingFinder`] has read, counted + /// where they are read, for tests to hold the reading to the room. + pub(super) static LIST_ENTRIES_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// No place among the faces reached, in [`RingFinder`]. +const NONE: usize = usize::MAX; + +/// Finds the ring behind a face for [`drawn_in_pairs_order`], and keeps its search from one stop to +/// the next. +/// +/// Every index it holds is in range: the faces of its lists are faces of the pairs +/// [`drawn_in_pairs_order`] checked against the number of faces, which is the length of the +/// `drawn` and `position` it is given, and the places it keeps are places in its own lists. +struct RingFinder { + /// For each face, the faces that go before it, lowest first. + before: Lists, + /// For each face, where its list in `before` now ends: the faces found drawn are dropped + /// from it, and those left moved up. + ends: Vec, + /// For each face, its place in `reached`; [`NONE`] for a face not reached. + marks: Vec, + /// The faces reached, in the order reached. Every one is in a group not completed yet. + reached: Vec, + /// For each face reached, the earliest place in `reached` it leads back to. + low: Vec, + /// The path from the first face reached to the one being looked at. + path: Vec, + /// The `limit` the faces reached were reached under; `None` with none reached yet. + limit: Option, +} + +/// A face on the path of [`RingFinder`]: its place in `reached`, and the entry of its list being +/// looked at. +struct Step { + place: usize, + entry: usize, +} + +impl RingFinder { + /// A finder for the faces of `after`, the faces drawn after each face. + fn new(after: &Lists) -> Self { + let n = after.starts.len() - 1; + let before = Lists::from_pairs(n, after.pairs().map(|(back, front)| (front, back))); + let ends = before.starts.get(1..).unwrap_or_default().to_vec(); + RingFinder { before, ends, marks: vec![NONE; n], reached: vec![], low: vec![], path: vec![], limit: None } + } + + /// The face to draw next when `start`, the first face not `drawn`, whose `position` is before + /// `limit`, waits for a face. Of the faces that are not drawn and come before `limit`, those + /// that go before `start` are followed back to the first group found whose faces wait for no + /// other such face: a ring of faces that go before each other, or one face. The answer is the + /// face of that group with the lowest `position`. Every face and every pair looked at takes + /// one from `room`; `None` when it runs out. + /// + /// The faces are followed depth first, each face's faces before it lowest first, and the first + /// strongly connected component completed is the group (Tarjan's algorithm, stopped there): + /// it leads to no other component. The search is kept, less that group, and the next call + /// goes on with it: the faces drawn since are the group's own and faces that waited for + /// nothing else, and none of those is in a group with a face still on the path, so what the + /// search knows of the faces left still holds. It starts afresh when `limit` moves, which + /// brings in faces it passed over. + fn behind(&mut self, start: usize, drawn: &[bool], position: &[usize], limit: usize, room: &mut usize) -> Option { + if self.limit != Some(limit) { + self.forget(0); + self.limit = Some(limit); + } + // The end of the path may be drawn: faces that only waited for the last group. + while let Some(place) = self.path.last().map(|step| step.place).filter(|&place| drawn[self.reached[place]]) { + self.forget(place); + } + if self.reached.first() != Some(&start) { + self.forget(0); + if !self.reach(start, drawn, room) { + return None; + } + } + while let Some(step) = self.path.last_mut() { + if *room == 0 { + return None; + } + *room -= 1; + let place = step.place; + let face = self.reached[place]; + if step.entry < self.ends[face] as usize { + let earlier = self.before.faces[step.entry] as usize; + if drawn[earlier] || position[earlier] >= limit { + step.entry += 1; + } else if self.marks[earlier] != NONE { + self.low[place] = self.low[place].min(self.marks[earlier]); + step.entry += 1; + } else { + // The entry is passed once the faces behind it are looked at. + if !self.reach(earlier, drawn, room) { + return None; + } + } + continue; + } + // Every face before this one is looked at: it ends a group when it leads no further + // back than itself. + let leads = self.low[place]; + if leads == place { + let found = self.reached[place..].iter().copied().min_by_key(|&face| position[face]); + // The face before it on the path keeps its entry for this one, to look at what is + // left of the group next time. + self.forget(place); + return found; + } + self.path.pop(); + if let Some(parent) = self.path.last_mut() { + self.low[parent.place] = self.low[parent.place].min(leads); + parent.entry += 1; + } + } + None + } + + /// Adds `face` to the faces reached and to the end of the path, at the start of its list, with + /// the faces now `drawn` dropped from the list: a step from `room` for each face the list held, + /// taken before the list is read. `false`, with `room` emptied and nothing read, when the list + /// is longer than the room left. + fn reach(&mut self, face: usize, drawn: &[bool], room: &mut usize) -> bool { + let (start, end) = (self.before.starts[face] as usize, self.ends[face] as usize); + let Some(left) = room.checked_sub(end - start) else { + *room = 0; + return false; + }; + *room = left; + let mut kept = start; + for entry in start..end { + let earlier = self.before.faces[entry]; + #[cfg(test)] + LIST_ENTRIES_READ.with(|read| read.set(read.get() + 1)); + if !drawn[earlier as usize] { + self.before.faces[kept] = earlier; + kept += 1; + } + } + // `kept` is no more than the end it replaces. + self.ends[face] = kept as u32; + let place = self.reached.len(); + self.marks[face] = place; + self.path.push(Step { place, entry: start }); + self.low.push(place); + self.reached.push(face); + true + } + + /// Takes out the faces reached from `place` on, and their part of the path. + fn forget(&mut self, place: usize) { + for face in self.reached.drain(place.min(self.reached.len())..) { + self.marks[face] = NONE; + } + self.low.truncate(place); + while self.path.last().is_some_and(|step| step.place >= place) { + self.path.pop(); + } + } +} + /// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing, /// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is /// not convex, or when they are at the same depth there. @@ -1673,7 +1971,8 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec { /// of overlapping faces with a convex polygon and a plane goes in the order of its depths there, /// the face nearer the viewer after the other ([`local_order`]), and each step draws the face that /// comes first in the given order of those whose faces before are drawn, so a face without a plane -/// or a convex polygon can also move. Otherwise the order given. +/// or a convex polygon can also move. Faces that lie in front of one another in a ring give up one +/// of the ring's own faces ([`drawn_in_pairs_order`]). Otherwise the order given. pub(crate) fn surface_order<'a>(faces: impl IntoIterator, f64)>) -> Vec { let placed: Vec = faces .into_iter() diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index f3054d85cf..49c301dd75 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -933,10 +933,10 @@ fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() { } } -/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap -/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at -/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer -/// than 0. 3 is the cap. +/// A cycle of overlapping stroke faces is broken at its own face that comes first by depth, and a +/// cap drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; +/// 2 at x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 +/// nearer than 0. 3 is the cap. #[test] fn a_depth_cycle_keeps_the_cap_last() { let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; @@ -964,6 +964,450 @@ fn a_depth_cycle_keeps_the_cap_last() { assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]); } +/// A face that lies in front of a face of a cycle, without being part of the cycle, waits for that +/// face. 0, 1 and 2 overlap in a cycle (as in `a_depth_cycle_keeps_the_cap_last`); 3, at x 16 to +/// 26 and flat at z 2, is nearer than 2 where they overlap, but its center is the farthest of all, +/// so it comes first by depth. The cycle is broken at 0, its first face by depth, and 3 follows 2. +/// Breaking it at the first face by depth of all the faces left drew 3 first, under 2. +#[test] +fn a_face_in_front_of_a_cycle_waits_for_it() { + let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed { + depth, + side: true, + away: false, + bounds: Rect::new(x, 0.0, x + 10.0, 10.0), + member: 0, + paints: Paints::Other, + outline: square(x), + plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + }; + let flat = [0.0, 0.0, 1.0]; + let walls = || [at(1.0, 0.0, flat, 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, flat, 1.0), at(-5.0, 16.0, flat, 2.0)]; + assert_eq!(draw_order(&walls(), true), [0, 2, 3, 1]); + // With the cap of `a_depth_cycle_keeps_the_cap_last` as well, it still goes last. + let cap = + Placed { depth: f64::MAX, side: false, bounds: Rect::new(0.0, 0.0, 26.0, 10.0), outline: vec![], plane: None, ..at(0.0, 0.0, flat, 0.0) }; + let capped: Vec = walls().into_iter().chain([cap]).collect(); + assert_eq!(draw_order(&capped, true), [0, 2, 3, 1, 4]); +} + +/// `order` with the pairs `before` (each first face drawn before the second) in their own order +/// ([`drawn_in_pairs_order`]), within `room` steps of looking for rings, and the steps taken; the +/// faces of `last` are drawn last. +fn in_pairs_order(order: &[usize], before: &[(usize, usize)], last: &[usize], room: usize) -> (Vec, usize) { + let n = order.len(); + let mut position = vec![0; n]; + for (at, &k) in order.iter().enumerate() { + position[k] = at; + } + let last: Vec = (0..n).map(|k| last.contains(&k)).collect(); + let mut left = room; + let drawn = drawn_in_pairs_order(order.to_vec(), &position, &last, narrow(before), &mut left); + (drawn, room - left) +} + +/// What [`drawn_in_pairs_order`] is to give with room enough, worked out plainly: at every stop +/// the faces behind the first face left are followed afresh, with nothing kept and no face taken +/// out of a list. +fn in_pairs_order_plainly(order: &[usize], before: &[(usize, usize)], last: &[usize]) -> Vec { + /// The first group completed behind `face`, among the faces `open`: its faces, or `None` while + /// its group goes on. `earlier` lists the faces before each face, lowest first. + fn group(face: usize, open: &[bool], earlier: &[Vec], reached: &mut Vec, low: &mut Vec) -> Option> { + let place = reached.len(); + reached.push(face); + low.push(place); + for &e in earlier[face].iter().filter(|&&e| open[e]) { + match reached.iter().position(|&f| f == e) { + Some(at) => low[place] = low[place].min(at), + None => { + let found = group(e, open, earlier, reached, low); + if found.is_some() { + return found; + } + low[place] = low[place].min(low[reached.iter().position(|&f| f == e).unwrap()]); + } + } + } + (low[place] == place).then(|| reached[place..].to_vec()) + } + let n = order.len(); + let mut at = vec![0; n]; + for (place, &k) in order.iter().enumerate() { + at[k] = place; + } + let mut earlier = vec![vec![]; n]; + for &(first, then) in before { + earlier[then].push(first); + } + earlier.iter_mut().for_each(|list| list.sort_unstable()); + let mut drawn = vec![false; n]; + let mut out: Vec = vec![]; + while out.len() < n { + let left: Vec = order.iter().copied().filter(|&k| !drawn[k]).collect(); + let limit = left.iter().find(|k| last.contains(k)).map_or(usize::MAX, |&k| at[k]); + let waits = |k: usize| earlier[k].iter().any(|&e| !drawn[e]); + let next = match left.iter().copied().find(|&k| at[k] < limit && !waits(k)) { + Some(ready) => ready, + None if at[left[0]] >= limit => left[0], + None => { + let open: Vec = (0..n).map(|k| !drawn[k] && at[k] < limit).collect(); + let found = group(left[0], &open, &earlier, &mut vec![], &mut vec![]).unwrap(); + found.into_iter().min_by_key(|&k| at[k]).unwrap() + } + }; + drawn[next] = true; + out.push(next); + } + out +} + +/// `pairs` as [`drawn_in_pairs_order`] takes them. +fn narrow(pairs: &[(usize, usize)]) -> Vec<(u32, u32)> { + pairs.iter().map(|&(first, then)| (first as u32, then as u32)).collect() +} + +/// The pairs of `before` that `drawn` draws the wrong way round. +fn broken(drawn: &[usize], before: &[(usize, usize)]) -> Vec<(usize, usize)> { + let mut at = vec![0; drawn.len()]; + for (place, &k) in drawn.iter().enumerate() { + at[k] = place; + } + before.iter().copied().filter(|&(first, then)| at[first] > at[then]).collect() +} + +/// After a ring's face is released, the faces left are looked at afresh: they may be a smaller +/// ring and faces in none. Two rings share face 1: 0 before 1 before 4 before 0, and 1 before 2 +/// before 3 before 1. By depth the order is 3, 2, 0, 4, 1. The five wait for no other face, so the +/// first stop releases 3, the first of them by depth. That leaves the one ring 0, 1, 4 and face +/// 2, which only waits for 1: 0 is released, and 2 follows 1. Only pairs of a ring are drawn the +/// wrong way round. Taking the first face left by depth at each stop drew 2 before 1 as well. +#[test] +fn the_faces_left_are_looked_at_afresh_after_each_face_released() { + let before = [(0, 1), (1, 4), (4, 0), (1, 2), (2, 3), (3, 1)]; + let (drawn, _) = in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], usize::MAX); + assert_eq!(drawn, [3, 0, 1, 2, 4]); + assert_eq!(broken(&drawn, &before), [(4, 0), (2, 3)]); + assert_eq!(broken(&in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], 0).0, &before), [(4, 0), (1, 2), (2, 3)]); +} + +/// A ring is the one behind the first face left by depth that waits for no face outside it: 0 +/// comes first by depth and waits for the ring 1, 2, 3, which waits for the ring 4, 5, 6. The far +/// ring is broken first (at 4) and drawn, then the near one (at 1), and 0 follows 1; one pair of +/// each ring is drawn the wrong way round, and no pair between them. Taking the first face left by +/// depth drew 0 first, under 1. +#[test] +fn the_ring_released_waits_for_no_face_outside_it() { + let before = [(1, 0), (1, 2), (2, 3), (3, 1), (4, 1), (4, 5), (5, 6), (6, 4)]; + let (drawn, _) = in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], usize::MAX); + assert_eq!(drawn, [4, 5, 6, 1, 0, 2, 3]); + assert_eq!(broken(&drawn, &before), [(3, 1), (6, 4)]); + assert_eq!(broken(&in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], 0).0, &before), [(1, 0), (3, 1), (4, 1), (6, 4)]); +} + +/// A ring is looked for among the faces that come before the next face drawn last: 1 comes first +/// by depth and waits for 4, a face of the ring 2, 3, 4, and for 0, which is drawn last. 0 waits +/// for no face, so it is a group of its own behind 1, but no face before it by depth can wait for +/// it. The ring gives up 2, and 1 follows 4; the pair of 1 and 0 cannot be kept. Stopping at 0 +/// drew 1 first, under 4. +#[test] +fn a_ring_is_looked_for_before_the_next_face_drawn_last() { + let before = [(2, 3), (3, 4), (4, 2), (4, 1), (0, 1)]; + let (drawn, _) = in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], usize::MAX); + assert_eq!(drawn, [2, 3, 4, 1, 0]); + assert_eq!(broken(&drawn, &before), [(4, 2), (0, 1)]); + assert_eq!(broken(&in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], 0).0, &before), [(4, 2), (4, 1), (0, 1)]); + // A face that waits only for a face after the one drawn last goes before the faces that wait + // for it: 0 waits for 1, 1 for 3, and 2 is drawn last. + let before = [(1, 0), (3, 1)]; + assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], usize::MAX).0, [1, 0, 2, 3]); + assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], 0).0, [0, 1, 2, 3]); +} + +/// Looking for rings is counted, and past the room given the first face not drawn yet goes next, +/// as before rings were looked for: the pairs of `a_face_in_front_of_a_cycle_waits_for_it`. A +/// face drawn last keeps every face before it by depth before it, ring or not. An order and +/// places in it that do not agree (an order that is not each face once), or a pair of a face that +/// is not in them, give the order back. +#[test] +fn breaking_rings_stops_at_its_room() { + let before = [(1, 0), (0, 2), (2, 1), (2, 3)]; + let order = [3, 0, 1, 2]; + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn, [0, 2, 3, 1]); + // The faces and pairs behind 3. + assert!((4..=16).contains(&steps), "{steps} steps"); + assert_eq!(in_pairs_order(&order, &before, &[], steps), (vec![0, 2, 3, 1], steps)); + for room in [0, 1, steps - 1] { + let (drawn, taken) = in_pairs_order(&order, &before, &[], room); + assert_eq!(drawn, [3, 0, 2, 1], "{room}"); + assert!(taken <= room, "{room}"); + } + // 0 is drawn last: 3, before it by depth, goes before it, and the ring's other faces after. + assert_eq!(in_pairs_order(&order, &before, &[0], usize::MAX).0, [3, 0, 2, 1]); + // 2 is drawn last: every other face is before it by depth, so 3 and 1, which wait only for + // it, go when they come first of the faces behind the first face left, and 0 follows 1. + assert_eq!(in_pairs_order(&order, &before, &[2], usize::MAX).0, [3, 1, 0, 2]); + assert_eq!(in_pairs_order(&order, &before, &[2], 0).0, [3, 0, 1, 2]); + let mut room = usize::MAX; + let position = [1, 2, 3, 0]; + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 3], narrow(&before), &mut room), order); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(9, 0)], &mut room), order); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(0, 4)], &mut room), order); + assert_eq!(drawn_in_pairs_order(order[..3].to_vec(), &position, &[false; 4], narrow(&before), &mut room), order[..3]); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position[..3], &[false; 4], narrow(&before), &mut room), order); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &[1, 2, 0, 3], &[false; 4], narrow(&before), &mut room), order); + assert_eq!(drawn_in_pairs_order(vec![0, 0, 1, 2], &[0, 2, 3, 0], &[false; 4], narrow(&before), &mut room), [0, 0, 1, 2]); + assert_eq!(drawn_in_pairs_order(vec![0, 1, 2, 4], &[0, 1, 2, 3], &[false; 4], narrow(&before), &mut room), [0, 1, 2, 4]); + assert_eq!(room, usize::MAX); +} + +/// A first face left that waits only for the face drawn last goes next with no search: 1,000 +/// such faces before a ring cost nothing, and the ring behind them still has its room. Each face +/// i < 1,000 waits for 1,004, which is drawn last; 1,000 to 1,003 are the pairs of +/// `breaking_rings_stops_at_its_room`, where 1,003 comes first by depth and waits for the ring. +#[test] +fn a_face_that_waits_only_for_the_face_drawn_last_costs_no_search() { + let waiting = 1000usize; + let (r, last) = (waiting, waiting + 4); + let mut before: Vec<(usize, usize)> = (0..waiting).map(|f| (last, f)).collect(); + before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]); + let order: Vec = (0..waiting).chain([r + 3, r, r + 1, r + 2, last]).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[last], usize::MAX); + let expected: Vec = (0..waiting).chain([r, r + 2, r + 3, r + 1, last]).collect(); + assert_eq!(drawn, expected); + assert!(steps < 20, "{steps} steps"); + // The room the ring takes is enough, whatever waits before it. + assert_eq!(in_pairs_order(&order, &before, &[last], before.len().div_ceil(4).max(steps)).0, expected); +} + +/// The lists of the faces before each face are made only when the room left is at least a +/// quarter of the pairs: with less, no ring is looked for, however few steps the ring would take. +/// A ring of three behind 3,000 faces in a chain (each before the next). +#[test] +fn the_lists_for_rings_are_made_only_with_room_for_a_quarter_of_the_pairs() { + let chain = 3000usize; + let r = chain; + let mut before: Vec<(usize, usize)> = (0..chain - 1).map(|f| (f, f + 1)).collect(); + before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]); + // As in `breaking_rings_stops_at_its_room`: 3 comes first by depth of the four and waits for + // the ring. + let order: Vec = (0..chain).chain([r + 3, r, r + 1, r + 2]).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn[chain..], [r, r + 2, r + 3, r + 1]); + assert!(steps < 20, "{steps} steps"); + let quarter = before.len().div_ceil(4); + let (drawn, steps) = in_pairs_order(&order, &before, &[], quarter - 1); + assert_eq!(drawn[chain..], [r + 3, r, r + 2, r + 1]); + assert_eq!(steps, 0); + assert_eq!(in_pairs_order(&order, &before, &[], quarter).0[chain..], [r, r + 2, r + 3, r + 1]); +} + +/// A list of the faces before a face is read only when the room left holds it: with less, no +/// entry of it is read, and the first face left goes next. Face 0 comes first by depth and waits +/// for 1, which waits for 2,000 faces after it in `order`, each waiting for 1: a ring of 1 with +/// each of them. +#[test] +fn a_list_longer_than_the_room_left_is_not_read() { + let wide = 2000usize; + let mut before = vec![(1, 0)]; + before.extend((2..2 + wide).flat_map(|f| [(f, 1), (1, f)])); + let order: Vec = (0..2 + wide).collect(); + // Room for the lists (a quarter of the pairs) but not for 1's list, and room for it. + // With too little room only 0's one-entry list is read; with room for both, 1's list as well. + for (room, want) in [(before.len().div_ceil(4), 1), (wide - 1, 1), (wide + 3, wide + 1)] { + super::LIST_ENTRIES_READ.with(|read| read.set(0)); + let (drawn, taken) = in_pairs_order(&order, &before, &[], room); + let read = super::LIST_ENTRIES_READ.with(|read| read.get()); + assert_eq!(read, want, "room {room}: {read} entries read, {taken} steps"); + assert!(read <= taken && taken <= room, "room {room}: {read} entries read, {taken} steps"); + assert_eq!(drawn.len(), order.len()); + } +} + +/// The steps of breaking rings are counted, not timed, and for rings of a few faces they are a +/// few a face however the rings lie: apart, each with a face in front of it that comes first by +/// depth; all behind one face, itself in a ring whose other faces come first in its list; and one +/// behind the other. The search goes on from where it stopped, and a face drawn is dropped from +/// a list the next time the list is looked at. A ring that is still a ring after it gives up a +/// face is walked again, so a large ring can take about its pairs for each face it gives up, the +/// square of its faces even when each waits for few others. With too little room the rings not +/// reached are broken at the first face left by depth, as before. +#[test] +fn breaking_rings_takes_a_few_steps_a_face_but_for_a_ring_of_many_pairs() { + // Ring r: faces 4r, 4r + 1 and 4r + 2 in a ring, and 4r + 3 after 4r + 2. + let rings = 2000usize; + let mut before = vec![]; + for r in 0..rings { + let f = 4 * r; + before.extend([(f + 1, f), (f, f + 2), (f + 2, f + 1), (f + 2, f + 3)]); + } + // By depth: every fourth face first, then the rings. + let order: Vec = (0..rings).map(|r| 4 * r + 3).chain((0..rings).flat_map(|r| [4 * r, 4 * r + 1, 4 * r + 2])).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(broken(&drawn, &before), (0..rings).map(|r| (4 * r + 1, 4 * r)).collect::>()); + assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings apart"); + // With no room the fourth faces go first, under the faces they are in front of. + assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 2 * rings); + + // Face 0, first by depth, is in a ring with 1 and 2, which come first in its list, and after a + // face of each ring r: faces 3r + 3, 3r + 4 and 3r + 5. + let rings = 3000usize; + let mut before = vec![(1, 0), (0, 2), (2, 1)]; + for r in 0..rings { + let f = 3 * r + 3; + before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f), (f, 0)]); + } + let order: Vec = (0..3 * rings + 3).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + // One pair of each ring, face 0's among them, and no pair of face 0 with another ring's face. + assert_eq!(broken(&drawn, &before), [(1, 0)].into_iter().chain((0..rings).map(|r| (3 * r + 5, 3 * r + 3))).collect::>()); + assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings behind one face"); + // The same with a face drawn last that every ring's first face waits for: it is passed over + // each time, and nothing after it in a list is looked at twice for that. + let cap = 3 * rings + 3; + let capped: Vec<(usize, usize)> = (0..rings).map(|r| (cap, 3 * r + 3)).chain(before.iter().copied()).collect(); + let order: Vec = (0..=cap).collect(); + let (drawn, steps) = in_pairs_order(&order, &capped, &[cap], usize::MAX); + assert_eq!(broken(&drawn, &capped).len(), 2 * rings + 1); + assert!(steps <= 5 * order.len(), "{steps} steps for {rings} rings behind one face, before a face drawn last"); + + // Ring r: faces 3r, 3r + 1 and 3r + 2, the first after the last face of ring r + 1. + let rings = 3000usize; + let mut before = vec![]; + for r in 0..rings { + let f = 3 * r; + before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f)]); + if r + 1 < rings { + before.push((f + 5, f)); + } + } + let order: Vec = (0..3 * rings).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + // One pair of each ring, and no pair between rings. + assert_eq!(broken(&drawn, &before).len(), rings); + assert!(broken(&drawn, &before).iter().all(|&(first, then)| first / 3 == then / 3)); + assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings one behind the other"); + let (short, taken) = in_pairs_order(&order, &before, &[], steps / 2); + assert!(broken(&short, &before).len() > rings && taken <= steps / 2, "{} pairs, {taken} steps", broken(&short, &before).len()); + assert_eq!(short.len(), order.len()); + + // One ring: each of 200 faces before the next 99. + let faces = 200usize; + let before: Vec<(usize, usize)> = (0..faces).flat_map(|f| (1..100).map(move |d| (f, (f + d) % faces))).collect(); + let order: Vec = (0..faces).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn, order); + // Each face it gives up walks the ring again, so it takes many times its pairs (the cost the + // docs name), but no more than about its pairs for each face. + assert!(steps < 2 * faces * before.len(), "{steps} steps for a ring of {} pairs", before.len()); + + // Pairs at random, about four a face: one large ring and faces around it. + let steps_of = |faces: usize| { + let mut next = numbers(faces as u64); + let before: Vec<(usize, usize)> = (0..2 * faces) + .map(|_| ((next() * faces as f64) as usize, (next() * faces as f64) as usize)) + .filter(|(first, then)| first != then) + .collect(); + let order: Vec = (0..faces).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn.len(), faces); + steps + }; + // No more than the square of the faces. + let (few, more) = (steps_of(800), steps_of(1600)); + assert!(few < 800 * 800 && more < 1600 * 1600, "{few} steps for 800 faces, {more} for 1,600"); +} + +/// Numbers from 0 to 1 that are the same on every run. +fn numbers(mut seed: u64) -> impl FnMut() -> f64 { + move || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 11) as f64 / (1u64 << 53) as f64 + } +} + +/// A ring gives up its own face that comes first by depth, which draws no more pairs the wrong +/// way round than taking the first face left by depth, ring or not, as before: on 6,000 sets of +/// pairs at random (4 to 30 faces, sparse and dense, agreeing with the depths mostly or half the +/// time, the pairs in any order and some twice, with up to four faces drawn last) none has more, and they have fewer in all. Every face +/// is drawn once, a face drawn last follows every face before it by depth, and the order of every +/// set is the one that looking afresh at every stop gives. One of them is a +/// set where the ring's face that waits for the fewest faces drew 4 pairs wrong against 3. +#[test] +fn breaking_a_ring_draws_no_more_pairs_wrong_than_the_first_face_by_depth() { + let order = [3, 6, 4, 1, 0, 2, 5]; + let before = [ + (1, 0), + (2, 0), + (0, 3), + (0, 4), + (5, 0), + (6, 0), + (1, 2), + (1, 3), + (4, 1), + (5, 1), + (4, 2), + (5, 2), + (6, 2), + (3, 4), + (3, 6), + (5, 4), + (6, 4), + (5, 6), + ]; + assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 3); + assert_eq!(broken(&in_pairs_order(&order, &before, &[], usize::MAX).0, &before).len(), 3); + + let mut next = numbers(7023); + let (mut with_rings, mut without, mut fewer) = (0usize, 0usize, 0usize); + for set in 0..6000 { + let n = 4 + (next() * 27.0) as usize; + let (dense, agrees) = (0.05 + 0.8 * next() * next(), if set % 2 == 0 { 0.5 } else { 0.85 }); + // The order by depth: the faces shuffled. + let mut order: Vec = (0..n).collect(); + for k in (1..n).rev() { + order.swap(k, (next() * (k + 1) as f64) as usize); + } + let mut before = vec![]; + for a in 0..n { + for b in a + 1..n { + if next() < dense { + before.push(if next() < agrees { (order[a], order[b]) } else { (order[b], order[a]) }); + } + } + } + // The pairs in any order, and in every fifth set some of them twice. + for k in (1..before.len()).rev() { + before.swap(k, (next() * (k + 1) as f64) as usize); + } + if set % 5 == 0 { + let again: Vec<(usize, usize)> = before.iter().copied().filter(|_| next() < 0.3).collect(); + before.extend(again); + } + // No face drawn last, or up to four. + let last: Vec = (0..set % 5).map(|_| order[(next() * n as f64) as usize]).collect(); + let (drawn, _) = in_pairs_order(&order, &before, &last, usize::MAX); + // Keeping the search from stop to stop gives what looking afresh at every stop gives. + assert_eq!(drawn, in_pairs_order_plainly(&order, &before, &last), "set {set}: {order:?} {before:?} {last:?}"); + let (plainly, _) = in_pairs_order(&order, &before, &last, 0); + let mut once = drawn.clone(); + once.sort_unstable(); + assert_eq!(once, (0..n).collect::>(), "set {set}"); + for &cap in &last { + let (at, place) = (order.iter().position(|&f| f == cap).unwrap(), drawn.iter().position(|&f| f == cap).unwrap()); + assert!(order[..at].iter().all(|f| drawn[..place].contains(f)), "set {set}"); + } + let (rings, plain) = (broken(&drawn, &before).len(), broken(&plainly, &before).len()); + assert!(rings <= plain, "set {set}: {rings} pairs wrong, {plain} with the first face by depth; {order:?} {before:?} {last:?}"); + with_rings += rings; + without += plain; + fewer += usize::from(rings < plain); + } + assert!(fewer > 500 && with_rings < without, "{with_rings} pairs wrong, {without} with the first face by depth, fewer in {fewer} sets"); +} + /// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a /// face of the same shape's stroke drawn before it: the wall then goes just before that face. A /// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs index 1047e4d0dd..bd1511ab8c 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/effects/src/stroke/arrow.rs @@ -289,6 +289,8 @@ fn local_stop(kind: &Arrowhead) -> Stop { Arrowhead::DoubleSlash => Stop::At(1.05), Arrowhead::DoubleArrow => Stop::At(1.7), Arrowhead::HalfCircle => Stop::At(1.0), + // Between the bend in its sides and its notch, where it is wider than the line at 100 %. + Arrowhead::NotchedArrow => Stop::At(2.7), Arrowhead::Concave => Stop::At(2.6), Arrowhead::Hexagon => Stop::At(HEX / 2.0), _ => Stop::At(2.0), @@ -395,6 +397,9 @@ fn local(kind: &Arrowhead) -> BezPath { let t = FRAC_1_SQRT_2; poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]); } + // Barbs 1.2 out at the back; each side bends in at (2.1, ±0.5), as wide as the line at + // 100 %, so the sides are concave; the notch reaches 0.7 into the back. + Arrowhead::NotchedArrow => poly(&mut p, &[(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)]), Arrowhead::Custom(c) => p = c.path.to_bezpath(), // The first ten are drawn by `shape`. Arrowhead::Triangle diff --git a/crates/effects/src/stroke/tests_arrows.rs b/crates/effects/src/stroke/tests_arrows.rs index a32a70245b..2a54ddb462 100644 --- a/crates/effects/src/stroke/tests_arrows.rs +++ b/crates/effects/src/stroke/tests_arrows.rs @@ -4,20 +4,26 @@ use kurbo::{BezPath, PathEl, Point, Shape}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer}; +use vectorcraft_doc::{ArrowAlign, Arrowhead, LineCap, StrokeLayer}; -use super::stroke_pieces; +use super::{line_outline, stroke_pieces}; /// A 2 pt line along +x ending at (100, 0) with `kind` at its end, tip on the end point: heads /// of weight 2, so 8 long and 8 wide. fn head(kind: Arrowhead) -> super::Arrow { + head_and_line(kind, LineCap::Butt).0 +} + +/// [`head`] and the outline of the line under it, drawn with `cap`. +fn head_and_line(kind: Arrowhead, cap: LineCap) -> (super::Arrow, BezPath) { let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); - st.end_arrow = Some(kind); - st.arrow_align = ArrowAlign::Tip; + (st.end_arrow, st.arrow_align, st.cap) = (Some(kind), ArrowAlign::Tip, cap); let mut l = BezPath::new(); l.move_to((0.0, 0.0)); l.line_to((100.0, 0.0)); - stroke_pieces(&l, &st).heads.remove(0) + let mut p = stroke_pieces(&l, &st); + let line = line_outline(&p.line, &st, st.width, 1e-3); + (p.heads.remove(0), line) } /// The outline's closed contours as polygons (curves flattened). @@ -105,6 +111,53 @@ fn the_line_arrow_is_a_right_angle_of_two_arms_as_thick_as_the_line() { } } +#[test] +fn the_notched_arrow_is_slender_with_concave_sides_and_a_v_notch() { + // Weight 2 at 100 %: a local unit (x back from the tip, y across) is 2 pt. + let h = head(Arrowhead::NotchedArrow); + let at = |x: f64, y: f64| Point::new(100.0 - 2.0 * x, 2.0 * y); + // Six corners: the tip, a bend in each side, a barb on each side and the notch between them. + let pts: Vec = contours(&h.outline).concat(); + let corners = [(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)].map(|(x, y)| at(x, y)); + assert_eq!(pts.len(), corners.len(), "{pts:?}"); + for c in corners { + assert!(pts.iter().any(|p| p.distance(c) < 1e-9), "corner {c:?} in {pts:?}"); + } + for side in [1.0, -1.0] { + // Concave: at the bend, the straight line from the tip to the barb (0.63 out) is outside. + assert_eq!(h.outline.winding(at(2.1, side * 0.6)), 0, "side {side}"); + assert_ne!(h.outline.winding(at(2.1, side * 0.45)), 0, "side {side}"); + // Slender: 2.4 units across at the barbs, not the 4 of the other arrows. + assert_eq!(h.outline.winding(at(3.9, side * 1.2)), 0, "side {side}"); + assert_ne!(h.outline.winding(at(3.9, side * 1.1)), 0, "side {side}"); + } + // Open in the notch, solid in front of it. + assert_eq!(h.outline.winding(at(3.5, 0.0)), 0); + assert_ne!(h.outline.winding(at(3.1, 0.0)), 0); + // The line stops between the bend and the notch, 2.7 units back from the tip. + assert!((h.inset - 5.4).abs() < 1e-9, "inset {}", h.inset); +} + +#[test] +fn the_line_under_the_notched_arrow_stays_inside_it_in_front_of_the_notch() { + // With every cap, no part of the 2 pt line between the notch and the tip shows beside the + // head, though the head is barely wider than the line at its bends. + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + let (h, line) = head_and_line(Arrowhead::NotchedArrow, cap); + let mut covered = 0; + for i in 0..=132 { + for j in -25..=25 { + let p = Point::new(100.0 - 6.6 + f64::from(i) * 0.05, f64::from(j) * 0.04); + if line.winding(p) != 0 { + assert_ne!(h.outline.winding(p), 0, "{cap:?}: the line shows at {p:?}"); + covered += 1; + } + } + } + assert!(covered > 500, "{cap:?}: the line reaches under the head ({covered} samples)"); + } +} + #[test] fn half_arrows_barb_on_their_own_side() { // Pointing along +x on a y-down page, left is −y. diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index afcd052eb2..027ae10251 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -43,6 +43,8 @@ vectorcraft-metafile = { workspace = true } vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } craft-cdr = { workspace = true } +# `.pcraft` documents opened and placed as images (cmd/fileio/pcraftread.rs). +craft-doc = { workspace = true } vectorcraft-scriptcheck = { workspace = true } vectorcraft-js = { workspace = true } # The commands' parameter schemas (schemas.rs). @@ -124,6 +126,8 @@ vectorcraft-testkit = { workspace = true } proptest = { workspace = true } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } +# Holds the installed plug-ins steady while a test counts what a cache keeps. +vectorcraft-plugins = { workspace = true, features = ["test-steady"] } # How many times an open reads a PDF, and the work its import takes. vectorcraft-pdf = { workspace = true, features = ["read-count"] } # The work `.ai` blends take to be checked and made live, and how many included EPS open checks diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 67a760aaa0..ec9abe30b5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -79,6 +79,7 @@ pub mod perspgrid; pub mod place; pub mod plugin; pub(crate) mod plugin_call; +pub mod plugin_generated; mod preflight; pub mod prefscmds; pub mod print; @@ -410,6 +411,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(printpresets::specs()); v.extend(printtiling::specs()); v.extend(plugin::specs()); + v.extend(plugin_generated::specs()); v.extend(scripts::specs()); v.extend(cut::specs()); v.extend(halftone::specs()); @@ -858,7 +860,7 @@ pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, s /// write a resolution and a number of bytes. pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; pub use docmenu::guide_indexes; -pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; +pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; /// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. @@ -871,6 +873,8 @@ pub(crate) use vectorcraft_doc::range::parse_range; /// What the fill and stroke proxies read from the selected objects, kept with the selection /// ([`crate::doc_state::SelectionRecord`]). pub(crate) use paint::SelectionPaints; +#[cfg(test)] +pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ}; /// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see /// [`clock_date`]), `Some(None)` for null (no date), else `Some(Some(seconds))`. diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index 22ac4194c5..b39e2c302a 100644 --- a/crates/engine/src/cmd/addons/pathtools/shape.rs +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Parametric Shape", [], None, - "{center: [x, y], kind?: \"rectangle\"|\"ellipse\"|\"polygon\" (default)|\"star\"|\"ring\"|\"arrow\"|\"cross\"|\"heart\"|\"gear\"|\"bubble\" (a speech bubble), width?, height?: 0.01..16384 pt (100), rotation?: degrees clockwise (0: upright), count?: 3..1000 (a polygon's sides, a star's points, a gear's teeth), a?, b?: the kind's own values (star: inner radius 0.01..1 of the outer, 0.5; ring: hole 0.01..0.99 of the size, 0.5; arrow: head length and shaft width 0.05..0.95, 0.4 and 0.4; cross: bar offset −0.9..0.9 (0, − up) and arm thickness 0.05..0.95 (1/3); heart: notch depth and point roundness 0..1 (0.4 and 0); gear: tooth height 0.01..0.9 (0.2); bubble: tail height 0.05..0.9 (0.25) and tail tip −1..1 across (−0.4)), radius?: corner radius 0..16384 pt (0; no corner rounds past the middle of a side)} draw a parametric shape with the current paint, selected, as one undo step; it stays editable with addon.pathtools.shape.set until its anchors are edited (moving, turning or scaling it keeps it) → {id, shape}", + "{center: [x, y], kind?: \"rectangle\"|\"ellipse\"|\"polygon\" (default)|\"star\"|\"ring\"|\"arrow\"|\"cross\"|\"heart\"|\"gear\"|\"bubble\" (a speech bubble), width?, height?: 0.01..16384 pt (100), rotation?: degrees clockwise (0: upright), count?: 3..1000 (a polygon's sides, a star's points, a gear's teeth), a?, b?: the kind's own values (star: inner radius 0.01..1 of the outer, 0.5; ring: hole 0.01..0.99 of the size, 0.5; arrow: head length and shaft width 0.05..0.95, 0.4 and 0.4; cross: bar offset −0.9..0.9 (0, − up) and arm thickness 0.05..0.95 (1/3); heart: notch depth and point roundness 0..1 (0.4 and 0); gear: tooth height 0.01..0.9 (0.2); bubble: tail height 0.05..0.9 (0.25) and tail tip −1..1 across (−0.4)), radius?: corner radius 0..16384 pt (0; no corner rounds past the middle of a side), sliceStart?, sliceEnd?: 0..360 degrees clockwise from the shape's top (measured as if it were as high as it is wide; 0 and 0: whole; a rectangle, ellipse, polygon, star or ring is cut from the start clockwise to the end and back through the center, a ring back along its hole; other kinds ignore them)} draw a parametric shape with the current paint, selected, as one undo step; it stays editable with addon.pathtools.shape.set until its anchors are edited (moving, turning or scaling it keeps it) → {id, shape}", has_doc, create ), @@ -34,7 +34,7 @@ pub fn specs() -> Vec { "Edit Parametric Shape", [], None, - "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; a new center, size or rotation moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with it, and with `strokes` its strokes and effects scale; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}", + "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, sliceStart?, sliceEnd?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; a new center, size or rotation moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with it, and with `strokes` its strokes and effects scale; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}", has_doc, set ), diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 25572855b2..584f33dc36 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -606,6 +606,42 @@ fn set_takes_a_linked_mask_and_placed_gradient_with_the_shape() { refuses(&mut s, "addon.pathtools.shape.set", &[json!({"id": id.0, "width": 50, "strokes": "yes"})]); } +#[test] +fn a_slice_cuts_the_shape_through_its_center_in_one_step() { + let mut s = session(); + let n = steps(&s); + let r = s + .execute( + "addon.pathtools.shape.create", + &json!({"kind": "ellipse", "center": [200, 150], "width": 100, "height": 60, "sliceStart": 0, "sliceEnd": 90}), + ) + .unwrap(); + let id = id_of(&r); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!((r["shape"]["sliceStart"].clone(), r["shape"]["sliceEnd"].clone()), (json!(0.0), json!(90.0))); + // The top right quarter, from the center. + let b = path(&s, id).bounds().unwrap(); + assert!((b.x0 - 200.0).abs() < 1e-9 && (b.x1 - 250.0).abs() < 1e-9 && (b.y0 - 120.0).abs() < 1e-9 && (b.y1 - 150.0).abs() < 1e-9, "{b:?}"); + assert_eq!(path(&s, id).subpaths[0].anchors[0].p, Point::new(200.0, 150.0)); + // Turned the other way round: the three quarters left, one more step; moving keeps the slice. + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "sliceStart": 90, "sliceEnd": 0})).unwrap(); + assert_eq!(steps(&s), n + 2); + let b = path(&s, id).bounds().unwrap(); + assert!((b.x0 - 150.0).abs() < 1e-9 && (b.y1 - 180.0).abs() < 1e-9, "{b:?}"); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + assert_eq!(shape_of(&s, id).map(|g| (g.slice_start, g.slice_end)), Some((90.0, 0.0))); + // The same start and end: the whole ellipse again. + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "sliceEnd": 90})).unwrap(); + assert_eq!(path(&s, id).anchor_count(), 4); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(path(&s, id).anchor_count() > 4, "undo brings the slice back"); + refuses( + &mut s, + "addon.pathtools.shape.set", + &[json!({"id": id.0, "sliceStart": -10}), json!({"id": id.0, "sliceEnd": 361}), json!({"id": id.0, "sliceEnd": "90"})], + ); +} + #[test] fn bad_shape_params_are_refused() { let mut s = session(); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 4fb4537ee4..d319e0d2a4 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -253,6 +253,8 @@ pub(crate) fn item_target(s: &Session, p: &Value, cmd: &str) -> Result Result { let aligned = aligned(p, cmd)?; + // Read `target` whatever names the objects, so that a bad one is refused with `ids` or `id` too. + let contents = targets_contents(p)?; match p.get(key) { Some(Value::Null) => Ok(ItemTarget::Top), Some(v) => v @@ -260,7 +262,7 @@ pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Re .map(|i| ItemTarget::Item { index: index(i), explicit: true, aligned }) .ok_or_else(|| bad(cmd, format!("`{key}` must be an appearance item index (paint order) or null"))), // The active item is a row of the first selected object's own stack. - None if p.get("ids").is_some() || p.get("id").is_some() || targets_contents(p)? => Ok(ItemTarget::Top), + None if p.get("ids").is_some() || p.get("id").is_some() || contents => Ok(ItemTarget::Top), // A row of a graph design's art in a series stands for nothing: the commands leave that art out. None if s.active().and_then(|st| st.selection.subjects().first().map(|id| super::graph::is_design_art(&st.doc, *id))) == Some(true) => { Ok(ItemTarget::Top) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index c787ba68cd..3828d67d0c 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -170,7 +170,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), @@ -179,7 +179,7 @@ pub fn specs() -> Vec { "Options of Selected Object…", [], None, - "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization, hue_jitter, saturation_jitter, brightness_jitter; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, scale_mode, scale_max, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", has_doc, brush_object_options ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index efcb425091..af71b2dae9 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -33,9 +33,12 @@ pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result { let name = name_param(p, "brush.get")?; let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?; let mut v = serde_json::to_value(&b).unwrap_or_default(); - // A scatter brush saves its hue jitter only when it is not 0; brush.get shows it either way. + // A scatter brush saves its hue, saturation and brightness jitter only when they are not 0; + // brush.get shows them either way. if let (BrushKind::Scatter(sc), Some(o)) = (&b.kind, v.as_object_mut()) { o.entry("hue_jitter").or_insert(json!(sc.hue_jitter)); + o.entry("saturation_jitter").or_insert(json!(sc.saturation_jitter)); + o.entry("brightness_jitter").or_insert(json!(sc.brightness_jitter)); } Ok(v) } @@ -580,7 +583,7 @@ pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result merged.insert(k.clone(), next); } keep_drawn_modes(b, &was, ¶ms, &mut merged); - keep_largest_width(b, &was, ¶ms, &mut merged); + keep_second_value(b, &was, ¶ms, &mut merged); b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? }; options.get_or_insert_with(|| next.clone()); @@ -643,27 +646,34 @@ fn keep_drawn_modes( merged.insert("modes".into(), Value::Array(kept)); } -/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when -/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is -/// the width, so without this a changed width would also change the largest width. -fn keep_largest_width( +/// Keep the second value a stroke of brush `b` draws with (with its own settings `was`) when +/// `params` sets the first and not the second: an art brush's `width` and `width_max`, a pattern +/// brush's `scale` and `scale_max`. Without a second value of its own the second value is the +/// first, so without this a changed first value would also change the second. +fn keep_second_value( b: &Brush, was: &serde_json::Map, params: &serde_json::Map, merged: &mut serde_json::Map, ) { - if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) { + let (first, second) = match b.kind { + BrushKind::Art(_) => ("width", "width_max"), + BrushKind::Pattern(_) => ("scale", "scale_max"), + _ => return, + }; + if params.get(first).is_none_or(Value::is_null) || params.get(second).is_some_and(|m| !m.is_null()) { return; } - let art = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { - Some(BrushKind::Art(a)) => Some(a), + // The first value, the second value of its own, and whether the value follows the pen. + let values = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { + Some(BrushKind::Art(a)) => Some((a.width, a.width_max, a.width_mode.is_some_and(|m| m.follows_pen()))), + Some(BrushKind::Pattern(p)) => Some((p.scale, p.scale_max, p.scale_mode.is_some_and(|m| m.follows_pen()))), _ => None, }; - let (Some(before), Some(after)) = (art(was), art(merged)) else { return }; - let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen()); - // Only a width that followed the pen has a largest width, and only one that still does uses it. - if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width { - merged.insert("width_max".into(), json!(before.width)); + let (Some(before), Some(after)) = (values(was), values(merged)) else { return }; + // Only a value that followed the pen has a second value, and only one that still does uses it. + if before.1.is_none() && before.2 && after.2 && after.0 != before.0 { + merged.insert(second.into(), json!(before.0)); } } diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 56cf4f5b96..9a5be1fc4f 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -758,14 +758,21 @@ impl Relink { } } } - /// Relink a node tree (the mirror of [`node_refs`]). + /// Relink a node tree (the mirror of [`node_refs`]). A pie's legend labels in wedges that now show a color of the + /// other darkness take the contrast a redraw sets there. fn node(&self, n: &mut Node) { + let shades = crate::cmd::graph::wedge_shades(n); + self.links(n); + crate::cmd::graph::follow_wedge_shades(n, &shades); + } + /// [`Self::node`] without the legend labels' contrast. + fn links(&self, n: &mut Node) { self.appearance(&mut n.appearance); if !self.keep_styles { n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied()); } if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { - self.node(Arc::make_mut(&mut m.art)); + self.links(Arc::make_mut(&mut m.art)); } if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) { self.name(Res::Image, &mut cm.key); @@ -831,7 +838,7 @@ impl Relink { _ => {} } for c in n.children_mut().into_iter().flatten() { - self.node(Arc::make_mut(c)); + self.links(Arc::make_mut(c)); } } } @@ -1183,9 +1190,7 @@ impl Imported { /// other darkness take the contrast a redraw sets there. Fonts the copy carries are bound to the faces `d` holds. pub(crate) fn apply(&mut self, n: &mut Node, d: &Document) { if self.relinks { - let shades = super::super::graph::wedge_shades(n); self.relink.node(n); - super::super::graph::follow_wedge_shades(n, &shades); } for note in vectorcraft_text::FontDb::global().bind_node_file_fonts(n, &|key| d.images.get(key)) { if !self.warnings.contains(¬e) { diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index a7827e135b..401879bc91 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -13,6 +13,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::cms::Model; +use vectorcraft_color::css; use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony}; use vectorcraft_color::wcag::{self, Category}; use vectorcraft_color::{BlendMode, Color, Paint, keep_model}; @@ -136,6 +137,15 @@ pub fn specs() -> Vec { always, harmony ), + cmd!( + query "color.parse", + "Parse Color", + [], + None, + "{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in the comma-separated legacy form, or oklch(), as CSS Color 4 defines them: https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch; this is a subset of CSS: a function's arguments are literal numbers, percentages, angles (deg, grad, rad or turn) and none, so calc(), var(), color-mix() and every other function, named colors and the other color spaces are errors; at most 48 characters, the spaces, tabs, line breaks and form feeds around it not counted)} the color the text gives → {color: an RGB color, the numbers written for a hex color, rgb() or hsl() and the sRGB of an oklch() color, whose chroma is lowered to fit sRGB; hex: \"#rrggbb\" of it; opacity: 0..100, the text's alpha, or null when the text gives none (CSS reads that as 100)}; values are clamped where CSS clamps them when it parses them, and an hsl() channel outside 0..255 is clipped; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB", + always, + parse_color + ), cmd!( query "color.contrast", "Contrast", @@ -148,6 +158,21 @@ pub fn specs() -> Vec { ] } +fn parse_color(_: &mut Session, p: &Value) -> Result { + const C: &str = "color.parse"; + let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?; + let parsed = css::parse(text).ok_or_else(|| { + bad(C, "`text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters") + })?; + if parsed.space == css::Space::Oklch && !vectorcraft_color::cms::active().rgb_is_srgb() { + return Err(bad(C, "OKLCH needs sRGB as the working RGB space")); + } + let [r, g, b] = parsed.rgb; + // As paint.proxies answers an opacity: a percentage to two places. + let opacity = parsed.alpha.map(|a| (f64::from(a) * 10_000.0).round() / 100.0); + Ok(json!({ "color": Color::rgb(r, g, b), "hex": css::hex_of(parsed.rgb), "opacity": opacity })) +} + /// The RGB inverse of `c`, expressed in `c`'s colour model. pub(crate) fn invert(c: Color) -> Color { c.invert_keep_model() diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 7a4a4dea07..78c066405d 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -110,7 +110,7 @@ pub fn specs() -> Vec { "Three-Point Arc", [], None, - "{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn", + "{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`), join?: bool (default false)} → {id, cx, cy, radius, sweep, joined?}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. With `join`, an end of the arc on an end of an editable open path (inside the isolated group in isolation mode) joins the arc to that path, which keeps its look and, when one end joins, its direction (a path in the selection comes first); with both ends on open path ends the second path joins too, or the path closes when both are its own ends. The result then has `joined: true` and `id` is the joined path (or its compound path). A `join` that is not true or false is an error. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn", has_doc, three_point_arc ), @@ -747,7 +747,8 @@ fn arc(s: &mut Session, p: &Value) -> Result { } /// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or -/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is. +/// leaving the end `at` names toward `toward`. With `join`, joined to the open paths whose ends +/// its ends lie on ([`super::path::join_arc`]). One undo step, named as an Arc tool drag is. fn three_point_arc(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.threePointArc"; let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]"))); @@ -774,8 +775,32 @@ fn three_point_arc(s: &mut Session, p: &Value) -> Result { } _ => return Err(bad(C, "give exactly one of `through` and `toward`")), }; + let join = match p.get("join") { + None => false, + Some(Value::Bool(on)) => *on, + Some(_) => return Err(bad(C, "`join` must be true or false")), + }; let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?; let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v)); + let ends = if join { + let st = s.doc()?; + let selected = st.selection.objects.clone(); + let find = |at| super::path::open_end_at(&st.doc, st.isolation, &selected, at); + (find(start), find(end)) + } else { + (None, None) + }; + if ends.0.is_some() || ends.1.is_some() { + let sub = path.subpaths.first().cloned().ok_or_else(|| bad(C, "no arc fits these points"))?; + let id = s.edit("Arc", |d, sel| { + let id = super::path::join_arc(d, &sub, ends.0, ends.1)?; + sel.set([id]); + Ok(id) + })?; + return Ok( + json!({ "id": id.0, "joined": true, "cx": arc.center.x, "cy": arc.center.y, "radius": arc.radius, "sweep": arc.sweep.to_degrees() }), + ); + } let look = s.new_art_look( vectorcraft_color::Paint::None, if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() }, diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 4059621e4e..38d46dafa2 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -14,7 +14,7 @@ pub fn specs() -> Vec { "Create Dimension", [], None, - "{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: extent, node} (linear only: a whole path between its outermost points, leftmost and rightmost when horizontal or aligned, topmost and bottommost when vertical)|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits", + "{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: extent, node, preview?: bool} (linear only: a whole path between its outermost points, leftmost and rightmost when horizontal or aligned, topmost and bottommost when vertical; preview, default false, moves them out to the outside of the path's strokes, as Use Preview Bounds measures)|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits", has_doc, create ), diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index c633835697..4fc1b83c29 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -180,7 +180,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), @@ -954,9 +954,43 @@ pub(crate) fn selected_roots(s: &Session) -> Result> { Ok(selection_roots(s.doc()?)) } -/// [`selected_roots`] of one document's selection. +/// [`selected_roots`] of one document's selection, found once for each document version and set of selected +/// objects and kept on this thread: the menus' enabled checks read it many times for one selection. pub(crate) fn selection_roots(st: &crate::DocState) -> Vec { - roots_of(&st.doc, st.selection.in_paint_order(&st.doc)) + let at = Arc::as_ptr(&st.doc); + ROOTS.with_borrow_mut(|kept| { + if let Some((doc, objects, roots)) = kept.as_ref() + && doc.as_ptr() == at + && *objects == st.selection.objects + { + return roots.clone(); + } + #[cfg(test)] + ROOTS_FOUND.set(ROOTS_FOUND.get() + 1); + let roots = roots_of(&st.doc, st.selection.in_paint_order(&st.doc)); + *kept = Some((Arc::downgrade(&st.doc), st.selection.objects.clone(), roots.clone())); + roots + }) +} + +/// The selected objects and roots of the last [`selection_roots`], with the document version they belong to. It is +/// held weakly, so its address is not reused while it is kept, and an edit in place moves it. +type KeptRoots = Option<(std::sync::Weak, Vec, Vec)>; + +thread_local! { + static ROOTS: std::cell::RefCell = const { std::cell::RefCell::new(None) }; +} + +#[cfg(test)] +thread_local! { + /// How many times [`selection_roots`] found the roots on this thread. + static ROOTS_FOUND: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times [`selection_roots`] has found the roots on this thread. +#[cfg(test)] +pub(crate) fn roots_found() -> u64 { + ROOTS_FOUND.get() } /// [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art is selected: diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs index 1e41b0c4ac..7ac2d9c162 100644 --- a/crates/engine/src/cmd/edit/tests.rs +++ b/crates/engine/src/cmd/edit/tests.rs @@ -347,3 +347,26 @@ fn direct_selection_cut_timing() { println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall)); } } + +/// The selected roots are found once for a document version and its selected objects, however many enabled checks +/// read them, and found again after the selection changes, after an edit, and for another selection. +#[test] +fn selected_roots_are_found_once_for_each_document_and_selection() { + let mut s = session(30, square); + let all = selected_roots(&s).unwrap(); + assert_eq!(all.len(), 30); + let before = roots_found(); + for _ in 0..20 { + assert_eq!(selected_roots(&s).unwrap(), all); + } + assert_eq!(roots_found() - before, 0, "reading the same selection again finds nothing"); + s.execute("select.set", &json!({"ids": [all[3].0, all[7].0]})).unwrap(); + assert_eq!(selected_roots(&s).unwrap(), vec![all[3], all[7]]); + assert_eq!(roots_found() - before, 1, "a new selection is found once"); + s.execute("object.group", &json!({})).unwrap(); + let grouped = selected_roots(&s).unwrap(); + assert_eq!(grouped.len(), 1, "the group is the one root: {grouped:?}"); + assert_ne!(grouped, vec![all[3], all[7]]); + selected_roots(&s).unwrap(); + assert_eq!(roots_found() - before, 2, "an edit finds the roots once again"); +} diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index cc5c19adea..e5463f6c44 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -79,7 +79,7 @@ fn effect_specs() -> Vec { "Effect Options", [], None, - "{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (as effect.apply)} → {ids}", + "{index: int, params?: {…} (merged into the current parameters; without a type, style or visibility setting, validated 3D values equal to their current values including defaults change nothing and add no undo step), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (as effect.apply)} → {ids}", has_doc, set_params ), @@ -896,6 +896,15 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { } } } + // Supplying the current 3D values, including omitted defaults and numeric JSON representations, + // must not rewrite the effect or make an otherwise unchanged preview into an Undo step. + if kind.is_none() && warp_id.is_none() && visible.is_none() { + let d = &s.doc()?.doc; + let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect(); + if !fx.is_empty() && fx.iter().all(|e| three_d_edit_changes_nothing(e, ¶ms)) { + return Ok(json!({ "ids": [] })); + } + } // The effect edited, when every target has one at `index` and all are the same: a dialog's // preview names its step after it. let one = edited.first().filter(|e| edited.len() == targets.len() && edited.iter().all(|other| other == *e)).cloned().unwrap_or_default(); @@ -937,6 +946,30 @@ fn bevel_effect(id: &str) -> bool { id == effects::EXTRUDE || id == effects::CLASSIC_EXTRUDE } +/// Whether validated parameters leave a 3D effect unchanged, including values supplied by its defaults. +fn three_d_edit_changes_nothing(effect: &Effect, params: &Value) -> bool { + if !effects::is_three_d(&effect.id) { + return false; + } + let upgraded = effects::upgrade_params(&effect.id, params); + let Some(given) = upgraded.as_object() else { return true }; + let current = effects::merged_params(&effect.id, &effect.params); + given.iter().all(|(key, value)| current.get(key).is_some_and(|stored| same_three_d_value(stored, value))) +} + +/// JSON numbers compare by value; arrays and objects keep their structure and every component. +fn same_three_d_value(stored: &Value, given: &Value) -> bool { + if stored == given { + return true; + } + match (stored, given) { + (Value::Number(a), Value::Number(b)) if a.is_f64() || b.is_f64() => a.as_f64() == b.as_f64(), + (Value::Array(a), Value::Array(b)) => a.len() == b.len() && a.iter().zip(b).all(|(a, b)| same_three_d_value(a, b)), + (Value::Object(a), Value::Object(b)) => a.len() == b.len() && a.iter().all(|(key, a)| b.get(key).is_some_and(|b| same_three_d_value(a, b))), + _ => false, + } +} + /// Does merging `params` into Pathfinder effect `e` leave it drawing as it does: the same Pathfinder /// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their /// defaults is unchanged), each option given equal to the one it stores (a precision that Scale diff --git a/crates/engine/src/cmd/effectcmd/three_d_type_tests.rs b/crates/engine/src/cmd/effectcmd/three_d_type_tests.rs index 5fef229091..122bbff3c3 100644 --- a/crates/engine/src/cmd/effectcmd/three_d_type_tests.rs +++ b/crates/engine/src/cmd/effectcmd/three_d_type_tests.rs @@ -22,6 +22,27 @@ fn undo_len(s: &Session) -> usize { s.doc().unwrap().history.undo.len() } +#[test] +fn unchanged_three_d_parameters_preserve_the_document_revision_and_history() { + for effect_id in ["threeD.extrude", "threeD.classicExtrude"] { + let (mut s, id) = setup(effect_id, json!({"rotationX": 12.345})); + let before = s.doc().unwrap().doc.clone(); + let history = undo_len(&s); + let revision = s.doc().unwrap().revision; + let current = effect(&s, id).1; + let params = vectorcraft_render::effects::merged_params(effect_id, ¤t); + let result = s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": params})).unwrap(); + assert_eq!(result["ids"], json!([]), "an unchanged effect is not an edit"); + assert_eq!(s.doc().unwrap().doc, before, "default values need not be written into the stored effect"); + assert_eq!(s.doc().unwrap().revision, revision); + assert_eq!(undo_len(&s), history); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"rotationX": 25.0}})).unwrap(); + assert_eq!(undo_len(&s), history + 1, "a changed option saves once"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + } +} + #[test] fn three_d_type_turns_the_effect_in_place_keeping_shared_settings_in_one_undo_step() { let types = [("plane", "threeD.rotate"), ("extrude", "threeD.extrude"), ("revolve", "threeD.revolve"), ("inflate", "threeD.inflate")]; diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index d63489fb2e..b5ab256440 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -182,7 +182,7 @@ impl Expandable { n.walk(&mut |c| { let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); e.text |= matches!(c.kind, NodeKind::Text(_)); - e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }) || c.extras().flare.is_some(); + e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }) || c.extras().flare.is_some() || c.extras().generated.is_some(); e.effects |= !c.appearance.effects.is_empty(); e.envelope |= matches!(c.kind, NodeKind::Envelope { .. }); e.blends |= matches!(c.kind, NodeKind::Blend { .. }); @@ -503,7 +503,8 @@ fn end_dimension_links(s: &mut Session, ended: &mut Vec) -> Result<() Ok(()) } -/// Makes the live shapes in `n` plain paths, and the flares plain groups of their parts. +/// Makes the live shapes in `n` plain paths, and the flares and generated art objects plain groups +/// of their parts. fn drop_live(n: &mut Node) { if let NodeKind::Path { live, .. } = &mut n.kind { *live = None; @@ -511,6 +512,9 @@ fn drop_live(n: &mut Node) { if n.extras().flare.is_some() { n.extras_mut().flare = None; } + if n.extras().generated.is_some() { + n.extras_mut().generated = None; + } if let Some(ch) = n.children_mut() { for c in ch.iter_mut() { drop_live(Arc::make_mut(c)); diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index e5515f0fe3..5f66067142 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -51,6 +51,8 @@ mod jp2read; mod metafile; mod naming; mod native; +mod pcraftread; +pub(crate) use pcraftread::is_pcraft; mod pcxread; pub mod pdf; mod pdfimport; @@ -264,6 +266,8 @@ mod tests_heifread; #[cfg(test)] mod tests_jp2read; #[cfg(test)] +mod tests_pcraftread; +#[cfg(test)] mod tests_pcxread; #[cfg(test)] mod tests_pxrread; diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 6ee790d901..4fee998d8e 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -558,6 +558,9 @@ pub const FORMATS: &[Format] = &[ Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS }, // QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images. reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false), + // Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size + // composite, the layers combined, or the preview with a note. Exports don't write them. + reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true), ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -618,6 +621,7 @@ pub const OPEN_EXTS: &[&str] = &[ "cdr", "cdt", "cmx", + "pcraft", ]; /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to @@ -625,10 +629,11 @@ pub const OPEN_EXTS: &[&str] = &[ /// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. -/// The packaging declares no type for HP-GL plot files or PICT pictures either. +/// The packaging declares no type for HP-GL plot files, PICT pictures or layered raster `.pcraft` +/// documents either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", + "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -718,6 +723,7 @@ pub const PLACE_EXTS: &[&str] = &[ "cdr", "cdt", "cmx", + "pcraft", "txt", "rtf", "docx", diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index d89cfa22b7..c578dece5d 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -13,13 +13,16 @@ //! a new document whose artboard is their bounds (or, to place, the art of one group), and nothing //! opens or is placed when the importer fails, declines, is cancelled or returns objects that don't //! pass the checks a filter's output does. +//! An importer at plug-in API level 4 may also return point type, embedded images, top-level +//! layers and artboards (its manifest's `outputKinds`): the artboards it returns replace the one +//! around the art of a new document, and File › Place leaves them out. use std::sync::Arc; use serde_json::Value; -use vectorcraft_doc::{Document, MAX_COORD, NodeId}; -use vectorcraft_geom::Rect; -use vectorcraft_plugins::import::Mode; +use vectorcraft_doc::{CharStyle, Document, ImageObject, LAYER_COLORS, LayerColor, MAX_COORD, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_plugins::import::{ImportObject, Mode}; use vectorcraft_plugins::{Manifest, Plugin, export, import, objects}; use super::super::{Result, bad, str_param}; @@ -210,17 +213,15 @@ pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result> { } } +/// What [`read`] gives: the importer's format, the new document, its objects' ids, the artboards +/// the importer returned and its warnings. +type Read = (&'static Format, Document, Vec, Vec, Vec); + /// The file `name` holding `bytes` read by importer `plugin` for `mode` with command `cmd`'s params /// `p` (`params`: the importer's own parameters) → the importer's format, a new document holding its -/// objects on its first layer, their ids, and its warnings. -fn read( - name: &str, - bytes: &[u8], - plugin: &Plugin, - p: &Value, - cmd: &str, - mode: Mode, -) -> Result<(&'static Format, Document, Vec, Vec)> { +/// objects (on its first layer, or in the layers the importer returned), their ids, the artboards +/// the importer returned, and its warnings. +fn read(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str, mode: Mode) -> Result { let m = plugin.manifest(); let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?; let (ext, stem) = (extension(name), file_stem(name)); @@ -234,15 +235,24 @@ fn read( let mut doc = Document::new(1.0, 1.0); let layer = doc.layers.first().map(|l| l.id); let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(cmd, fx, n); - let ids = objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| failed(mode, name, e))?; - Ok((format, doc, ids, imported.warnings)) + let mut warnings = Vec::new(); + let (ids, artboards) = if imported.paths_only() { + let paths = imported.objects.into_iter().filter_map(|o| if let ImportObject::Path(o) = o { Some(o) } else { None }).collect(); + (objects::apply_output(&mut doc, &[], paths, layer, &admit).map_err(|e| failed(mode, name, e))?, Vec::new()) + } else { + let ids = build(&mut doc, imported.objects, imported.layers, &admit, &mut warnings).map_err(|e| failed(mode, name, e))?; + (ids, imported.artboards) + }; + warnings.splice(0..0, imported.warnings); + Ok((format, doc, ids, artboards, warnings)) } /// The file `name` holding `bytes` read by importer `plugin` to place it, with `file.place`'s params -/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects on its -/// first layer, and its warnings. Importer `plugin`'s manifest must set `place`. +/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects in its +/// layers, and its warnings; artboards the importer returned are left out. Importer `plugin`'s +/// manifest must set `place`. pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str) -> Result<(&'static Format, Document, Vec)> { - let (format, doc, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?; + let (format, doc, _, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?; Ok((format, doc, warnings)) } @@ -250,14 +260,148 @@ pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Valu /// (`params`: the importer's own parameters) into a new document, its artboard the bounds of what /// the importer returned. pub(super) fn load(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value) -> Result { - let (format, mut doc, ids, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?; - if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) { - board.rect = artboard_rect(bounds); + let (format, mut doc, ids, artboards, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?; + if artboards.is_empty() { + if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) { + board.rect = artboard_rect(bounds); + } + } else { + set_artboards(&mut doc, artboards); } doc.title = file_name(name); Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None }) } +/// Puts `objects`, what an importer at plug-in API level 4 returned, into `doc`, a new document of +/// one layer: in `layers`, bottom first, each holding the objects it lists in their order, or all in +/// that one layer when there are none. Paths are made as a filter's new ones are (their effects let +/// in by `admit`), type is laid out, and each image is stored in the document as a PNG of its +/// pixels. A warning for type whose font isn't there, or doesn't have its style, goes to `warnings`. +/// An object that reaches more than [`MAX_COORD`] from the origin is an error. Returns the objects' +/// ids in order. +fn build( + doc: &mut Document, + objects: Vec, + layers: Vec, + admit: objects::AdmitEffects, + warnings: &mut Vec, +) -> std::result::Result, String> { + let count = objects.len(); + let first = doc.layers.first().map(|l| (**l).clone()); + let first = first.unwrap_or_else(|| Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0))); + let mut owner = vec![0usize; count]; + for (li, l) in layers.iter().enumerate() { + for &k in &l.objects { + if let Some(o) = owner.get_mut(k) { + *o = li; + } + } + } + let mut members: Vec>> = vec![Vec::new(); layers.len().max(1)]; + let mut ids = Vec::with_capacity(count); + let mut fonts = std::collections::BTreeSet::new(); + for (i, o) in objects.into_iter().enumerate() { + let at = format!("objects[{i}]"); + let node = match o { + ImportObject::Path(o) => objects::new_object(doc, o, &at, admit).map_err(|e| e.to_string())?, + ImportObject::Type(t) => { + let node = type_node(doc, t); + if let NodeKind::Text(t) = &node.kind { + fonts.extend(t.runs.iter().flat_map(crate::cmd::fonts::run_fonts)); + } + node + } + ImportObject::Image(im) => image_node(doc, im).map_err(|e| e.to_string())?, + }; + if node.geometric_bounds().is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)) { + return Err(format!("plug-in output: {at}: it reaches more than {MAX_COORD} pt from the origin")); + } + ids.push(node.id); + if let Some(list) = owner.get(i).and_then(|&li| members.get_mut(li)) { + list.push(Arc::new(node)); + } + } + let built: Vec> = if layers.is_empty() { + let mut layer = first; + if let Some(children) = layer.children_mut() { + *children = members.into_iter().next().unwrap_or_default(); + } + vec![Arc::new(layer)] + } else { + layers + .into_iter() + .zip(members) + .enumerate() + .map(|(li, (l, children))| { + let mut layer = Node::layer(doc.alloc_id(), &l.name, LayerColor::Preset((li % LAYER_COLORS.len()) as u8)); + layer.visible = l.visible; + layer.locked = l.locked; + if let Some(c) = layer.children_mut() { + *c = children; + } + Arc::new(layer) + }) + .collect() + }; + doc.layers = built; + warnings.extend(crate::cmd::fonts::set_font_warning(fonts)); + Ok(ids) +} + +/// Point type `t` as a new node of `doc`, in [Normal Character Style] with the face, size and fill +/// `t` gives, laid out. +fn type_node(doc: &mut Document, t: import::OutType) -> Node { + let mut style = crate::cmd::textstyles::normal_char_style(doc); + style.font_version = None; + style.font_axes.clear(); + style.font_family = t.font_family; + match t.font_style { + Some(s) => style.font_style = s, + None => { + style.font_style = CharStyle::default().font_style; + crate::cmd::textedit::fit_font_style(&mut style); + } + } + style.size = t.font_size; + if let Some(fill) = t.fill { + style.fill = fill; + } + let mut text = TextObject::point(Point::ZERO, &t.text, style); + text.xf = t.transform; + text.para = crate::cmd::create::new_type_para(); + text.system_layout = doc.setup.system_layout; + crate::cmd::typecmd::refresh_bounds(&mut text); + let mut n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(text))); + n.name = t.name; + n +} + +/// Image `im` as a new node of `doc`, its pixels stored in `doc` as a PNG. +fn image_node(doc: &mut Document, im: import::OutImage) -> Result { + let pixels = image::RgbaImage::from_raw(im.width, im.height, im.rgba).ok_or_else(|| err("the image's pixels don't match its size"))?; + let stored = super::load::as_png(pixels, None, None)?; + let image = ImageObject { + key: stored.key.clone(), + width: stored.width, + height: stored.height, + xf: im.transform, + link: None, + placement: Default::default(), + pixels: None, + }; + doc.images.insert(stored.key, stored.blob); + let mut n = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(image))); + n.name = im.name; + Ok(n) +} + +/// Gives `doc` the artboards `boards` an importer returned, in order, in place of its one. +fn set_artboards(doc: &mut Document, boards: Vec) { + let Some(template) = doc.artboards.first().cloned() else { return }; + doc.artboards = + boards.into_iter().zip(1u32..).map(|(b, id)| vectorcraft_doc::Artboard { id, name: b.name, rect: b.rect, ..template.clone() }).collect(); +} + /// The artboard of art with bounds `r`: `r` within ±[`MAX_COORD`], at least 1 pt wide and high /// about its center (the artboard of a single line or point). A side that would pass the edge /// moves inward, so art at the edge keeps an artboard the document's edits accept. diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 2b3613984a..4f11935db0 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -74,6 +74,9 @@ pub struct RasterImage { /// a DCS file's (nonzero, [`crate::cmd::place::dcs`]), or a PSD or PSB file's (even-odd, /// [`psdread::clipping_path`]). pub clip: Option<(vectorcraft_geom::PathData, vectorcraft_geom::FillRule)>, + /// What the image leaves out of its file, for Open, Place and the Links commands to warn of: a + /// `.pcraft` document read as its reduced preview ([`super::pcraftread`]). + pub note: Option, } pub(super) fn err(e: impl std::fmt::Display) -> EngineError { @@ -92,6 +95,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if vectorcraft_affinity::is_affinity(bytes) { return format("affinity"); } + if super::pcraftread::is_pcraft(bytes) { + return format("pcraft"); + } if super::cdr::is_cdr(bytes) { // A template keeps its meaning from the extension. return by_name.filter(|f| f.id == "cdt").or_else(|| format("cdr")); @@ -262,16 +268,32 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) if !every_page(opened.page_count(), opts) || !opts.layers || !opts.editing_data { return None; } - let private = opened.illustrator_data()?; - Some(editing_copy_alone(&private, opts)) + // A placeholder page's fonts aren't the art's. + Some(editing_copy_alone(&decoded_copy(opened)?, opts, Default::default())) } -/// [`from_editing_data_alone`] of `private`, the editor's copy already read. -fn editing_copy_alone(private: &[u8], opts: &LoadOptions) -> Result<(Document, Vec)> { - vectorcraft_eps::ai_alone_with(private, opts.legacy_names) +/// [`from_editing_data_alone`] of `decoded`, the editor's copy already read and decoded, or why it +/// can't be decoded, with `widths`, the widths the file's PDF part gives the characters of its +/// fonts, which tell installed copies of a font apart ([`vectorcraft_eps::AiLayers::with_page_widths`]). +fn editing_copy_alone( + decoded: &std::result::Result, String>, + opts: &LoadOptions, + widths: vectorcraft_pdf::PageWidths, +) -> Result<(Document, Vec)> { + decoded + .as_ref() + .map_err(Clone::clone) + .and_then(|data| vectorcraft_eps::ai_alone_decoded(data, opts.legacy_names, widths)) .map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})"))) } +/// The editor's own copy of its art that `opened` carries, read from its streams one after the +/// other and decoded as it is read ([`vectorcraft_eps::decode_ai_private`]): the decoded data or why +/// it can't be decoded, `None` as for [`vectorcraft_pdf::Opened::illustrator_data`]. +fn decoded_copy(opened: &vectorcraft_pdf::Opened) -> Option, String>> { + opened.read_illustrator_data(|private| vectorcraft_eps::decode_ai_private(private)) +} + /// Does a file opened with `opts` read the editor's own copy of its art: no pages picked, and /// layers and the editing data on? fn reads_editing_copy(opts: &LoadOptions) -> bool { @@ -286,10 +308,10 @@ fn reads_layers_alone(opts: &LoadOptions) -> bool { reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines } -/// The editor's own copy of its art that `opened` carries (as [`vectorcraft_pdf::illustrator_data`] -/// reads it), when `opts` read it ([`reads_editing_copy`]). -fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option> { - reads_editing_copy(opts).then(|| opened.illustrator_data()).flatten() +/// The editor's own copy of its art that `opened` carries, decoded ([`decoded_copy`]), when `opts` +/// read it ([`reads_editing_copy`]). +fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option, String>> { + reads_editing_copy(opts).then(|| decoded_copy(opened)).flatten() } /// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's @@ -301,8 +323,12 @@ fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: EngineError) -> Result< if opts.pages.is_some() || !opts.layers || !opts.editing_data { return Err(e); } - let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part(bytes, opts.password.as_deref()) - .and_then(|private| private.map(|p| vectorcraft_eps::ai_alone_on_page(&p.data, p.trim, p.user_unit, opts.legacy_names)).transpose()); + let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part_with(bytes, opts.password.as_deref(), |private| { + vectorcraft_eps::decode_ai_private(private) + }) + .and_then(|private| { + private.map(|p| p.data.and_then(|data| vectorcraft_eps::ai_alone_on_page_decoded(&data, p.trim, p.user_unit, opts.legacy_names))).transpose() + }); match read { Ok(Some((doc, warnings))) => { let notes = @@ -453,6 +479,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result Err(e) => Err(err(e)), }; let mut read = restore_or_import(editing, || { + // The widths the PDF part gives the characters of its fonts, which tell installed + // copies of a font apart: read once, when the editing copy is. + let page_widths = std::cell::OnceCell::new(); + let widths = || page_widths.get_or_init(|| opened.as_ref().map(vectorcraft_pdf::Opened::page_widths).unwrap_or_default()).clone(); // Type all from the text document and nothing that needs the PDF part: the layers // alone, the PDF part not imported. Else what was read of the layers is kept for // reading them with the PDF part. @@ -460,7 +490,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?))) { let pages = o.trim_pages(); - match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names) { + match vectorcraft_eps::ai_layers_alone_decoded(private, &pages.sizes, pages.user_unit, opts.legacy_names, widths()) { Ok((mut doc, warnings)) => { doc.setup.bleed = pages.bleed; editing_data = true; @@ -482,9 +512,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // decoded draws nothing either): its notes are at most the page's own. let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w)); let copy_alone = || match &private { - Some(private) => Some(editing_copy_alone(private, opts)), + Some(private) => Some(editing_copy_alone(private, opts, widths())), None if layers.is_some() => { - opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts)) + opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts, widths())) } None => None, }; @@ -496,7 +526,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result let (doc, warnings, read) = match alone { Some((doc, warnings)) => (doc, warnings, true), None => { - let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode)); + let layers = layers.or_else(|| private.map(|p| vectorcraft_eps::AiLayers::decoded(p).with_page_widths(widths()))); through_editing_data(layers, opts, r.document, r.warnings, r.user_unit) } }; @@ -524,9 +554,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // A restored document opens on the artboard that the editing copy beside it names as // active, as a file read from that copy does (the restored document never holds one). if read.2 - && let Some(private) = opened.as_ref().ok().and_then(|o| o.illustrator_data()) + && let Some(Ok(data)) = opened.as_ref().ok().and_then(decoded_copy) { - read.0.opened_artboard = vectorcraft_eps::ai_opened_artboard(&private, &read.0); + read.0.opened_artboard = vectorcraft_eps::ai_opened_artboard_decoded(&data, &read.0); } read } @@ -566,6 +596,14 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result Ok(None) => (raster_doc(&title, bytes)?, vec![], false), Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false), }, + // A `.pcraft` document opens as its full-size image, its layers combined, or its preview + // with a note that says so. + "pcraft" => { + let mut img = raster_image(bytes)?; + img.blob = crate::cmd::links::readable_and_kept(img.blob, true, false)?; + let note = img.note.take(); + (image_doc(&title, img)?, note.into_iter().collect(), false) + } _ if format.raster => (raster_doc(&title, bytes)?, vec![], false), _ => return Err(err(format!("{} files can't be opened yet", format.label))), }; @@ -627,6 +665,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result doc.title = title; } warnings.extend(doc.images.values().filter_map(|b| size_note(&b.bytes))); + // Generated art that can't be drawn again keeps its art; opening runs no plug-in. + warnings.extend(crate::cmd::plugin_generated::open_notes(&doc)); Ok(Loaded { doc, format, warnings, restored, converted, preview_only, editing_data, native_pdf_compatible }) } @@ -1136,8 +1176,11 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; /// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported /// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes -/// it) is read with that path. +/// it) is read with that path. A `.pcraft` document is read by [`super::pcraftread::image`]. pub fn raster_image(bytes: &[u8]) -> Result { + if super::pcraftread::is_pcraft(bytes) { + return super::pcraftread::image(bytes); + } let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); @@ -1321,7 +1364,7 @@ fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: } let blob = ImageBlob::new(mime, bytes); let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd)); - Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip }) + Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip, note: None }) } /// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from @@ -1404,7 +1447,12 @@ pub(crate) fn preview_with_clip(mut blob: ImageBlob) -> ImageBlob { /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { - let RasterImage { key, blob, width, height, ppi, clip } = raster_image(bytes)?; + image_doc(name, raster_image(bytes)?) +} + +/// [`raster_doc`] of an image already read. +fn image_doc(name: &str, img: RasterImage) -> Result { + let RasterImage { key, blob, width, height, ppi, clip, note: _ } = img; let (sx, sy) = crate::cmd::place::pt_per_px(ppi); let mut d = Document::new(width as f64 * sx, height as f64 * sy); let layer = d.layers[0].id; diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index a4e0e4d24c..41649366f1 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -318,12 +318,7 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result Result>> { - let Some(r) = doc.artboards.first().map(|a| a.rect).or_else(|| vectorcraft_render::encode::art_bounds(doc)) else { return Ok(None) }; - let scale = f64::from(PREVIEW_MAX) / r.width().max(r.height()); - if vectorcraft_render::raster_size(r, scale).is_err() { - return Ok(None); - } - vectorcraft_render::Renderer::new().render_region(doc, r, scale, false).to_png().map(Some).map_err(EngineError::Other) + vectorcraft_render::encode::first_artboard_png(doc, PREVIEW_MAX).map_err(EngineError::Other) } /// `p` with `compress` from the Use Compression preference when it doesn't say (saves only; diff --git a/crates/engine/src/cmd/fileio/pcraftread.rs b/crates/engine/src/cmd/fileio/pcraftread.rs new file mode 100644 index 0000000000..40116bfa0a --- /dev/null +++ b/crates/engine/src/cmd/fileio/pcraftread.rs @@ -0,0 +1,378 @@ +//! `.pcraft` documents (a layered raster document in a ZIP bundle) for File › Open and File › +//! Place, read with craft-doc and stored as PNG. The image is, in this order: +//! +//! 1. the bundle's full-size composite, when its manifest names one; +//! 2. the canvas combined from its layers, when the document is RGB at 8 or 16 bits and every +//! visible layer is a raster layer that blends Normal ([`combine`]); +//! 3. otherwise its composite preview, with a note that names the preview's size, the canvas's +//! and why the layers were not combined, unless the preview is the canvas's size. +//! +//! A full-size composite or preview that the manifest names but the bundle does not hold, or that +//! does not decode, is an error, as is a full-size composite of another size than the canvas. The +//! image is sized by the document's resolution, so a preview places at the canvas's size (at +//! 1 ppi when that would take less). + +use std::fmt; + +use craft_doc::{Limits, RenditionKind, Samples}; +use serde::Deserialize; +use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor}; + +use super::super::Result; +use super::load::{MAX_RASTER_ALLOC, RasterImage, as_png, err, raster_image}; + +/// Whether `bytes` are a `.pcraft` bundle: a ZIP archive holding the manifest craft-doc reads. +pub(crate) fn is_pcraft(bytes: &[u8]) -> bool { + craft_doc::sniff(bytes).is_some_and(|kind| kind.extension() == "pcraft") +} + +/// The image of `.pcraft` bundle `bytes` (see the module documentation), with +/// [`RasterImage::note`] saying so when only a preview smaller than the canvas was read. +pub(super) fn image(bytes: &[u8]) -> Result { + let limits = limits(); + let canvas: Canvas = craft_doc::pcraft_document(bytes, &limits).map_err(err)?; + let (w, h) = (canvas.size.width, canvas.size.height); + if w == 0 || h == 0 { + return Err(err(format!("the .pcraft document's canvas of {w} × {h} pixels is empty"))); + } + let composite = craft_doc::rendition(bytes, RenditionKind::Composite, &limits).map_err(err)?; + if let Some(full) = composite.as_ref().filter(|c| c.is_full_composite) { + let img = stored_png(&full.bytes, canvas.ppi(), "full-size image")?; + if (img.width, img.height) != (w, h) { + return Err(err(format!("the .pcraft document's full-size image is {} × {} pixels, not {w} × {h} as its canvas", img.width, img.height))); + } + return Ok(img); + } + let reason = match combine(bytes, &canvas, &limits)? { + Ok(img) => return Ok(img), + Err(reason) => reason, + }; + let Some(preview) = composite else { + return Err(err(format!("the .pcraft document has no full-size image or preview, and its layers can't be combined: {reason}"))); + }; + let (pw, ph) = vectorcraft_doc::header_size(&preview.bytes).ok_or_else(|| err("the .pcraft document's preview isn't a PNG image"))?; + // The preview covers the canvas: its resolution is the document's (72 ppi without a usable + // one) scaled by its size, and at least 1 ppi, the least a stored image's resolution reads as. + let (x, y) = canvas.ppi().unwrap_or((72.0, 72.0)); + let ppi = ((x * f64::from(pw) / f64::from(w)).max(1.0), (y * f64::from(ph) / f64::from(h)).max(1.0)); + let mut img = stored_png(&preview.bytes, Some(ppi), "preview")?; + let reduced = (img.width, img.height) != (w, h); + let (pw, ph) = (img.width, img.height); + img.note = reduced.then(|| format!("only the {pw} × {ph} preview of this {w} × {h} pixel .pcraft document was read: {reason}")); + Ok(img) +} + +/// The limits of one read: the decoded allowance for an entry, and twice that for everything one +/// call reads and decodes. +fn limits() -> Limits { + let mut limits = Limits::default(); + limits.max_entry = MAX_RASTER_ALLOC; + limits.max_total = MAX_RASTER_ALLOC.saturating_mul(2); + limits +} + +/// PNG `png` from the bundle (its `what`) as a stored image whose PNG records resolution `ppi`. The +/// image's resolution is the one read back from the PNG, as the Links commands read it later. +fn stored_png(png: &[u8], ppi: Option<(f64, f64)>, what: &str) -> Result { + if craft_image_codecs::detect(png) != Some(craft_image_codecs::Format::Png) { + return Err(err(format!("the .pcraft document's {what} isn't a PNG image"))); + } + match ppi { + Some(r) => raster_image(&super::ppi::with_png_resolution(png, r)), + None => raster_image(png), + } +} + +/// The document members that size the image and decide whether its layers can be combined. +#[derive(Deserialize)] +struct Canvas { + size: Size, + resolution_dpi: f32, + mode: String, + depth: String, + #[serde(default)] + icc_profile: Option, +} + +#[derive(Deserialize)] +struct Size { + width: u32, + height: u32, +} + +impl Canvas { + /// The document's resolution, when it is a usable one. + fn ppi(&self) -> Option<(f64, f64)> { + let dpi = f64::from(self.resolution_dpi); + (dpi.is_finite() && (1.0..=100_000.0).contains(&dpi)).then_some((dpi, dpi)) + } +} + +/// The document's layers, bottom first. +#[derive(Deserialize)] +struct Layers { + layers: Vec, +} + +/// The members of a layer that change how it draws. Members that don't (its name, locks, label, +/// id, links, XMP and the blocks kept for PSD files) are skipped; any other member is kept in +/// `unknown`, so a layer with a setting this reader doesn't know is not combined. +#[derive(Default)] +struct Layer { + visible: bool, + blend: String, + opacity: f32, + fill_opacity: f32, + clipped: bool, + mask: Option, + vector_mask: Option, + effects: Option, + kind: String, + frame: bool, + advanced_blending: bool, + unknown: Option, +} + +#[derive(Deserialize)] +struct Mask { + enabled: bool, + density: f32, + feather: f32, +} + +#[derive(Deserialize)] +struct Toggle { + #[serde(default = "yes")] + enabled: bool, +} + +fn yes() -> bool { + true +} + +#[derive(Deserialize)] +struct Effects { + #[serde(default)] + enabled: bool, + #[serde(default)] + items: Vec, +} + +/// A layer's `content`: its kind. A group's children are skipped: a visible group is not combined. +#[derive(Deserialize)] +struct Content { + kind: String, +} + +impl<'de> Deserialize<'de> for Layer { + fn deserialize>(d: D) -> std::result::Result { + struct LayerVisitor; + impl<'de> Visitor<'de> for LayerVisitor { + type Value = Layer; + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a layer object") + } + + fn visit_map>(self, mut map: A) -> std::result::Result { + let mut l = Layer { fill_opacity: 1.0, ..Layer::default() }; + let (mut visible, mut blend, mut opacity, mut kind) = (None, None, None, None); + while let Some(key) = map.next_key::()? { + match key.as_str() { + "visible" => visible = Some(map.next_value()?), + "blend" => blend = Some(map.next_value()?), + "opacity" => opacity = Some(map.next_value()?), + "fill_opacity" => l.fill_opacity = map.next_value()?, + "clipped" => l.clipped = map.next_value()?, + "mask" => l.mask = map.next_value()?, + "vector_mask" => l.vector_mask = map.next_value()?, + "effects" => l.effects = map.next_value()?, + "content" => kind = Some(map.next_value::()?.kind), + "frame" => l.frame = map.next_value::>()?.is_some(), + "excluded_channels" => l.advanced_blending |= map.next_value::()? != 0, + "blend_if" | "advanced" => l.advanced_blending |= map.next_value::>()?.is_some(), + "id" | "name" | "locks" | "label" | "psd_blocks" | "psd_id" | "fill_cache" | "link_group" | "video" | "xmp" => { + map.next_value::()?; + } + _ => { + map.next_value::()?; + l.unknown.get_or_insert(key); + } + } + } + l.visible = visible.ok_or_else(|| serde::de::Error::missing_field("visible"))?; + l.blend = blend.ok_or_else(|| serde::de::Error::missing_field("blend"))?; + l.opacity = opacity.ok_or_else(|| serde::de::Error::missing_field("opacity"))?; + l.kind = kind.ok_or_else(|| serde::de::Error::missing_field("content"))?; + Ok(l) + } + } + d.deserialize_map(LayerVisitor) + } +} + +/// Why visible layer `l` can't be combined by [`combine`], or `None` when it can. +fn unsupported(l: &Layer) -> Option { + let unit = |v: f32| v.is_finite() && (0.0..=1.0).contains(&v); + if let Some(key) = &l.unknown { + return Some(format!("a visible layer has a setting this version doesn't read (`{key}`)")); + } + if l.kind != "raster" { + let kind = match l.kind.as_str() { + "group" => "a visible layer group", + "text" => "a visible type layer", + "shape" => "a visible shape layer", + "smart" => "a visible smart object", + "adjustment" => "a visible adjustment layer", + "fill" => "a visible fill layer", + _ => "a visible layer of a kind this version doesn't read", + }; + return Some(format!("the document has {kind}")); + } + let reason = if l.blend != "Normal" { + "a visible layer blends in a mode other than Normal" + } else if !unit(l.opacity) || !unit(l.fill_opacity) { + "a visible layer's opacity is out of range" + } else if l.clipped { + "a visible layer is clipped to the layer below it" + } else if l.effects.as_ref().is_some_and(|e| e.enabled && !e.items.is_empty()) { + "a visible layer has layer effects" + } else if l.vector_mask.as_ref().is_some_and(|v| v.enabled) { + "a visible layer has a vector mask" + } else if l.mask.as_ref().is_some_and(|m| m.enabled && (m.feather != 0.0 || !unit(m.density))) { + "a visible layer has a feathered layer mask" + } else if l.advanced_blending { + "a visible layer uses advanced blending options" + } else if l.frame { + "a visible layer has a frame" + } else { + return None; + }; + Some(reason.into()) +} + +/// The canvas of `.pcraft` bundle `bytes` combined from its layers, or why it can't be: the +/// document must be RGB at 8 or 16 bits, the canvas's pixels as 32-bit floating-point RGBA within +/// [`MAX_RASTER_ALLOC`], and each visible layer a raster layer that blends Normal at an opacity and +/// fill opacity between 0 and 1, with no clipping, layer effects, vector mask, frame or advanced +/// blending options, and a layer mask that is off or not feathered. Hidden layers are not read. +/// Each layer is laid over the layers below it as the straight-alpha Normal blend lays a source +/// over a backdrop, its alpha scaled by its opacity, its fill opacity and its layer mask (the mask +/// value scaled toward opaque by the mask's density). An RGB ICC profile the document names is +/// kept in the PNG; another profile is a reason not to combine. A visible layer without saved +/// pixels, or with samples other than 8 or 16 bits, is a reason too. +fn combine(bytes: &[u8], canvas: &Canvas, limits: &Limits) -> Result> { + let no = |reason: &str| Ok(Err(reason.to_string())); + if canvas.mode != "Rgb" { + return Ok(Err(format!("the document's color mode is {}, not RGB", canvas.mode))); + } + let deep = match canvas.depth.as_str() { + "U8" => false, + "U16" => true, + _ => return no("the document stores 32-bit samples"), + }; + let (w, h) = (canvas.size.width, canvas.size.height); + let pixels = u64::from(w) * u64::from(h); + if pixels.saturating_mul(16) > MAX_RASTER_ALLOC { + return no("the canvas is too large to combine its layers"); + } + let Layers { layers } = craft_doc::pcraft_document(bytes, limits).map_err(err)?; + let visible: Vec = layers.iter().enumerate().filter(|(_, l)| l.visible).map(|(i, _)| i).collect(); + if let Some(reason) = visible.iter().find_map(|&i| unsupported(&layers[i])) { + return Ok(Err(reason)); + } + let icc = match canvas.icc_profile { + Some(_) => craft_doc::pcraft_icc_profile(bytes, limits).map_err(err)?, + None => None, + }; + if icc.as_deref().is_some_and(|icc| vectorcraft_doc::cmyk::icc_color_space(icc) != Some(*b"RGB ")) { + return no("the document's color profile isn't an RGB profile"); + } + let n = usize::try_from(pixels).map_err(err)?; + let mut out = vec![[0.0f32; 4]; n]; + for i in visible { + let l = &layers[i]; + let Some(px) = craft_doc::pcraft_layer_rgba(bytes, &[i], limits).map_err(err)? else { + return no("a visible layer has no saved pixels"); + }; + if (px.width, px.height) != (w, h) || px.rgba.len() != n * 4 { + return Err(err("a layer of the .pcraft document doesn't cover its canvas")); + } + let Some(rgba) = Levels::of(&px.rgba) else { return no("a visible layer stores 32-bit samples") }; + let mask = match px.mask.as_ref().filter(|m| m.enabled) { + Some(m) => match Levels::of(&m.alpha).filter(|_| m.alpha.len() == n) { + Some(levels) => Some((levels, m.density)), + None => return no("a visible layer's mask stores 32-bit samples"), + }, + None => None, + }; + let opacity = l.opacity * l.fill_opacity; + for (p, b) in out.iter_mut().enumerate() { + let coverage = mask.as_ref().map_or(1.0, |(m, density)| 1.0 - density * (1.0 - m.at(p))); + let s = [rgba.at(p * 4), rgba.at(p * 4 + 1), rgba.at(p * 4 + 2), rgba.at(p * 4 + 3)]; + *b = over(*b, s, opacity * coverage); + } + } + let img: image::DynamicImage = if deep { + let samples = out.iter().flat_map(|p| level16(*p)).collect(); + image::ImageBuffer::from_raw(w, h, samples) + .map(image::DynamicImage::ImageRgba16) + .ok_or_else(|| err("the combined layers don't fit the canvas"))? + } else { + let samples = out.iter().flat_map(|p| level8(*p)).collect(); + image::ImageBuffer::from_raw(w, h, samples) + .map(image::DynamicImage::ImageRgba8) + .ok_or_else(|| err("the combined layers don't fit the canvas"))? + }; + drop(out); + as_png(img, icc, canvas.ppi()).map(Ok) +} + +/// 8- or 16-bit samples read as levels from 0 to 1. +enum Levels<'a> { + U8(&'a [u8]), + U16(&'a [u16]), +} + +impl<'a> Levels<'a> { + fn of(s: &'a Samples) -> Option { + match s { + Samples::U8(v) => Some(Levels::U8(v)), + Samples::U16(v) => Some(Levels::U16(v)), + _ => None, + } + } + + fn at(&self, i: usize) -> f32 { + match self { + Levels::U8(v) => v.get(i).map_or(0.0, |&v| f32::from(v) / 255.0), + Levels::U16(v) => v.get(i).map_or(0.0, |&v| f32::from(v) / 65535.0), + } + } +} + +/// Straight-alpha source `s` laid over backdrop `b` with the Normal blend, the source's alpha +/// scaled by `k`. +fn over(b: [f32; 4], s: [f32; 4], k: f32) -> [f32; 4] { + let sa = s[3] * k; + if sa <= 0.0 { + return b; + } + let kb = b[3] * (1.0 - sa); + let a = sa + kb; + if a <= 0.0 { + return [0.0; 4]; + } + let mix = |c: usize| (kb * b[c] + sa * s[c]) / a; + [mix(0), mix(1), mix(2), a] +} + +fn level8(p: [f32; 4]) -> [u8; 4] { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if p[3] <= 0.0 { [0; 4] } else { [q(p[0]), q(p[1]), q(p[2]), q(p[3])] } +} + +fn level16(p: [f32; 4]) -> [u16; 4] { + let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16; + if p[3] <= 0.0 { [0; 4] } else { [q(p[0]), q(p[1]), q(p[2]), q(p[3])] } +} diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 3754752939..6e63170f88 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -82,6 +82,60 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() { assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]); } +/// The sample `.ai` with its private data `private` cut into streams of `size` bytes, each +/// deflated on its own, and `content` more in its page's content stream dictionary. +fn deflated_streams(private: &[u8], size: usize, content: &str) -> Vec { + let parts: Vec> = private + .chunks(size) + .map(|part| { + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); + e.write_all(part).unwrap(); + e.finish().unwrap() + }) + .collect(); + let parts: Vec<&[u8]> = parts.iter().map(Vec::as_slice).collect(); + ai::ai_with_parts(&parts, ai::page_pdf(), content, "/Filter /FlateDecode ") +} + +/// A `.ai` whose private data streams are cut inside the compression's marker and inside the +/// compressed data opens with its layers. +#[test] +fn ai_private_data_cut_anywhere_opens_with_its_layers() { + let private = compressed(&ai::sample_data()); + for size in [7, 1000] { + let mut s = Session::new(); + let r = open(&mut s, "art.ai", &deflated_streams(&private, size, ""), json!({})).unwrap(); + assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("weren't read")), "{r}"); + check_sample(&s); + } +} + +/// A `.ai` whose private data streams hold more than 256 MiB, once their own compression is undone, +/// opens with its layers when the editing data they hold is within the limit on it, also when its +/// PDF part can't be read (#4366): the streams are read one after the other as the data is +/// decoded, without a limit of their own. +#[cfg(target_pointer_width = "64")] +#[test] +fn ai_private_data_past_256_mib_opens_with_its_layers() { + let data = ai::sample_data(); + let at = data.windows(13).position(|w| w == b"%%PageTrailer").unwrap(); + // A comment line the reader skips, so the data stays valid while it grows past 256 MiB. + let mut program = Vec::with_capacity(data.len() + (257 << 20)); + program.extend_from_slice(&data[..at]); + program.push(b'%'); + program.resize(at + (257 << 20), b'x'); + program.push(b'\n'); + program.extend_from_slice(&data[at..]); + for content in ["", REFUSED_CONTENT] { + let file = deflated_streams(&program, 64 << 20, content); + assert!(file.len() < 4 << 20, "the filler deflates"); + let mut s = Session::new(); + let r = open(&mut s, "art.ai", &file, json!({})).unwrap(); + assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("weren't read")), "{content}: {r}"); + check_sample(&s); + } +} + /// Opening a `.ai` or a PDF whose PDF part reads, or a `.ai` saved without PDF compatibility, /// reads and checks the file once, on any thread, for the document it may carry, its pages, its /// editing data and its File Info, with pages picked or not. @@ -2180,3 +2234,110 @@ fn an_illustrator_ai_file_opens_with_its_layers_closed() { assert_eq!(r["restored"], json!(true), "{r}"); assert_eq!(open_rows(&s).1, ["Art", "Hidden"]); } + +/// A `.ai` whose layer `Art` holds one line of type, `Hamburg`, that its text document sets in the +/// font of PostScript name `name` (a font record without a version), and whose PDF part sets it in +/// a subset of that font that gives each character the width `width` gives it, in thousandths of an +/// em. With `square`, the layer and the page have a gray square too. The editing copy's artboard is +/// 200 × 100 pt, and the page `page_width` × 100. +fn type_in_copy_ai(name: &str, square: bool, page_width: f64, width: impl Fn(char) -> f64) -> Vec { + let story = "Hamburg"; + let n = story.chars().count() + 1; + let document = format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 ({name}) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\ + /1 << /1 [ << /0 << /0 ({story}\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \ + /6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /0 0 /1 10.0 >> >> >> /1 {n} >> ] >> >> \ + /1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8105.5 8176.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \ + << /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 {n} >> >> ] >> ] >> ] >> ] >> ] >> ] >> >> ] /2 << /1 12.0 >> >>\n" + ); + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n"; + let (art, drawn) = + if square { (format!("0.5 g\n{}f\n{text}", ai::rect(120.0, 20.0, 160.0, 60.0)), "0.5 g 120 20 40 40 re f ") } else { (text.to_string(), "") }; + let body = format!( + "%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", + ai::layer("Art", &art), + lines.join("\n") + ); + let data = ai::editing_data(200.0, 100.0, &body); + let widths: Vec = (32u8..=126).map(char::from).map(|c| if story.contains(c) { width(c).to_string() } else { "0".into() }).collect(); + let page = PdfPage { + resources: format!( + "/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>", + widths.join(" ") + ), + entries: format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(1)), + // A page that is only type, with its art box, isn't a placeholder. + art: Some([0.0, 0.0, page_width, 100.0]), + ..PdfPage::new(page_width, 100.0, &format!("{drawn}BT /F1 10 Tf 14 65 Td ({story}) Tj ET")) + }; + pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len())], None) +} + +/// Type from the text document of a `.ai` whose font record keeps no version, where two installed +/// copies of the font share its PostScript name, family and style and differ in their widths, is +/// set in the copy that sets its characters at the widths the file's PDF part gives them: whether +/// its layers open alone, with the PDF part imported, or from the editing copy alone because the PDF +/// part is only type (read after the layers alone, on a page of another size, were not used). +#[test] +fn type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in() { + let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewtest Ink", "PagewtestInk-Regular")); + let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }; + // (a square beside the type, the page's width, the options, whether the PDF part is imported) + let cases = [ + (true, 200.0, &LoadOptions::default(), false), + (true, 200.0, &trim, true), + (false, 200.0, &LoadOptions::default(), false), + (false, 200.0, &trim, true), + (false, 260.0, &LoadOptions::default(), true), + ]; + for (square, page_width, opts, imported) in cases { + let file = type_in_copy_ai("PagewtestInk-Regular", square, page_width, &width); + let before = vectorcraft_pdf::imports_of(&file); + let loaded = load_with("copies.ai", &file, opts).unwrap(); + let case = format!("square {square}, page {page_width}, {:?}: {:?}", opts.crop, loaded.warnings); + assert!(loaded.editing_data, "{case}"); + assert_eq!(vectorcraft_pdf::imports_of(&file) > before, imported, "{case}"); + let art = loaded.doc.layers[0].children().unwrap(); + assert_eq!(art.len(), 1 + usize::from(square), "{case}"); + let Some(NodeKind::Text(t)) = art.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(_))) else { panic!("type: {case}") }; + assert_eq!(t.plain_text(), "Hamburg"); + assert_eq!(db.style_face(&t.runs[0].style).unwrap().version, "1.1", "{case}"); + } +} + +/// Installs two copies of family `family` and PostScript name `name`: Inter as version 1.0, loaded +/// first, and Source Sans 3 as 1.1, whose advances (thousandths of an em) the returned function gives. +fn install_width_copies(family: &str, name: &str) -> impl Fn(char) -> f64 + use<> { + let db = vectorcraft_text::FontDb::global(); + for (inter, version) in [(true, "1.0"), (false, "1.1")] { + let font = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", version, name)).unwrap(); + assert_eq!(db.add_font(font), 1); + } + let newer = db.postscript_faces(name).into_iter().find(|f| f.version == "1.1").unwrap(); + move |c: char| newer.advance(newer.glyph_for(c)) * 1000.0 / newer.units_per_em() +} + +/// Type the PDF part's widths set in the second copy of its font is saved as `.ai` with that +/// copy's version in its font record, so it opens in the same copy again, from the editing copy +/// alone as from the whole file. +#[test] +fn type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save() { + let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewrt Ink", "PagewrtInk-Regular")); + let mut s = Session::new(); + let r = open(&mut s, "copies.ai", &type_in_copy_ai("PagewrtInk-Regular", true, 200.0, &width), json!({})).unwrap(); + let saved = s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let versions = |doc: &vectorcraft_doc::Document| -> Vec { + let art = doc.layers[0].children().unwrap(); + art.iter() + .filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(db.style_face(&t.runs[0].style).unwrap().version.clone()) } else { None }) + .collect() + }; + assert_eq!(versions(&s.doc().unwrap().doc), ["1.1"], "{r}"); + let loaded = load_with("saved.ai", &bytes, &LoadOptions { native: false, ..Default::default() }).unwrap(); + assert!(loaded.editing_data, "{:?}", loaded.warnings); + assert_eq!(versions(&loaded.doc), ["1.1"], "{:?}", loaded.warnings); + let private = vectorcraft_pdf::illustrator_data(&bytes, None).unwrap(); + assert_eq!(versions(&vectorcraft_eps::ai_alone(&private).unwrap().0), ["1.1"]); +} diff --git a/crates/engine/src/cmd/fileio/tests_pcraftread.rs b/crates/engine/src/cmd/fileio/tests_pcraftread.rs new file mode 100644 index 0000000000..444ba06606 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_pcraftread.rs @@ -0,0 +1,326 @@ +//! Reading `.pcraft` documents built here from scratch (a hand-written manifest, PNG previews +//! encoded here and layers whose surfaces are one default pixel, in a stored ZIP archive): the +//! full-size composite is the image when the bundle has one; otherwise visible Normal raster layers +//! are combined at the canvas's size; otherwise the preview is read, with a note when it is smaller +//! than the canvas. Damaged and unreadable bundles are refused with a message. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use super::*; + +/// A surface of one `pixel` (hex of its bytes) everywhere, in `sample` (U8 or U16). +fn surface(sample: &str, mode: &str, alpha: bool, pixel: &str) -> String { + format!(r#"{{"format":{{"mode":"{mode}","sample":"{sample}","alpha":{alpha}}},"default":"{pixel}","tiles":[]}}"#) +} + +/// An 8-bit RGBA surface of one pixel everywhere. +fn rgba8(p: [u8; 4]) -> String { + surface("U8", "Rgb", true, &p.iter().map(|b| format!("{b:02x}")).collect::()) +} + +/// Effects that are on, with none in the list. +const NO_EFFECTS: &str = r#"{"enabled":true,"items":[],"psd_raw":null}"#; + +/// A layer: `visible`, `blend`, `opacity`, `content`, its `mask` and `effects` (JSON), and `extra` +/// members (each `,"key":value`). +fn layer_with(visible: bool, blend: &str, opacity: f32, content: &str, mask: &str, effects: &str, extra: &str) -> String { + format!( + r#"{{"id":1,"name":"L","visible":{visible},"locks":{{}},"blend":"{blend}","opacity":{opacity},"fill_opacity":1.0,"clipped":false, + "mask":{mask},"effects":{effects},"label":"None","content":{content},"psd_blocks":[],"psd_id":null,"fill_cache":null{extra}}}"# + ) +} + +/// [`layer_with`] without a mask or effects. +fn layer(visible: bool, blend: &str, opacity: f32, content: &str, extra: &str) -> String { + layer_with(visible, blend, opacity, content, "null", NO_EFFECTS, extra) +} + +fn raster(surface: &str) -> String { + format!(r#"{{"kind":"raster","surface":{surface}}}"#) +} + +/// A visible Normal raster layer of `pixel` at `opacity`. +fn plain(pixel: [u8; 4], opacity: f32) -> String { + layer(true, "Normal", opacity, &raster(&rgba8(pixel)), "") +} + +/// A `w` × `h` PNG of `pixel`. +fn png(w: u32, h: u32, pixel: [u8; 4]) -> Vec { + let mut out = vec![]; + image::RgbaImage::from_pixel(w, h, image::Rgba(pixel)).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// What a test bundle holds besides its layers. +struct Bundle<'a> { + size: (u32, u32), + dpi: f32, + depth: &'a str, + version: u32, + layers: Vec, + /// The full-size composite's entry, when the manifest names it (`None` bytes: not in the archive). + full: Option>>, + /// The preview's entry, likewise. + preview: Option>>, +} + +impl Bundle<'_> { + fn new(layers: Vec) -> Self { + Bundle { size: (300, 200), dpi: 150.0, depth: "U8", version: 1, layers, full: None, preview: Some(Some(png(30, 20, [9, 9, 9, 255]))) } + } + + fn bytes(&self) -> Vec { + let (w, h) = self.size; + let named = |m: &Option>>, path: &str| if m.is_some() { format!(r#""{path}""#) } else { "null".into() }; + let mut manifest = format!( + r#"{{"format_version":{},"generator":"test 0.1.0", + "document":{{"id":1,"name":"Untitled","size":{{"width":{w},"height":{h}}},"resolution_dpi":{},"mode":"Rgb","depth":"{}", + "icc_profile":null,"layers":[{}],"channels":[],"guides":{{}},"selection":null,"metadata":{{}},"global_light":{{}}}}, + "thumbnail":null,"composite":{}"#, + self.version, + self.dpi, + self.depth, + self.layers.join(","), + named(&self.preview, "composite/preview.png"), + ); + if self.full.is_some() { + manifest.push_str(r#","full_composite":"composite/full.png""#); + } + manifest.push('}'); + let mut files: Vec<(&str, Vec)> = vec![("manifest.json", manifest.into_bytes())]; + if let Some(Some(b)) = &self.preview { + files.push(("composite/preview.png", b.clone())); + } + if let Some(Some(b)) = &self.full { + files.push(("composite/full.png", b.clone())); + } + super::zip::store(&files).unwrap() + } +} + +/// Place `file` (named `art.pcraft`) in a new document: the reply and the placed image's (natural +/// width in points, its stored pixels). +fn place(file: &[u8]) -> (Value, f64, image::DynamicImage) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + let r = s.execute("file.place", &json!({"name": "art.pcraft", "dataBase64": vectorcraft_format::base64_encode(file)})).unwrap(); + let doc = &s.doc().unwrap().doc; + let node = doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + let NodeKind::Image(im) = &node.kind else { panic!("an image, got {:?}", node.kind) }; + let width = node.geometric_bounds().map(|b| b.width()).unwrap(); + let pixels = image::load_from_memory(&doc.images[&im.key].bytes).unwrap(); + (r, width, pixels) +} + +fn warnings(r: &Value) -> Vec { + r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect() +} + +fn place_error(file: &[u8]) -> String { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + s.execute("file.place", &json!({"name": "art.pcraft", "dataBase64": vectorcraft_format::base64_encode(file)})).unwrap_err().to_string() +} + +#[test] +fn the_full_size_composite_is_placed_rather_than_the_layers_or_the_preview() { + // The red layer could be combined, and the preview the manifest names is not in the archive. + let mut b = Bundle::new(vec![plain([255, 0, 0, 255], 1.0)]); + b.full = Some(Some(png(300, 200, [0, 200, 0, 255]))); + b.preview = Some(None); + let file = b.bytes(); + assert!(super::pcraftread::is_pcraft(&file)); + assert_eq!(detect("art.zip", &file).map(|f| f.id), Some("pcraft"), "by its content"); + let (r, width, pixels) = place(&file); + assert_eq!(r["format"], "pcraft"); + assert!(warnings(&r).is_empty(), "{r}"); + assert_eq!((pixels.width(), pixels.height()), (300, 200)); + assert_eq!(pixels.to_rgba8().get_pixel(5, 5).0, [0, 200, 0, 255]); + // Sized by the document's resolution: 300 px at 150 ppi are 144 pt (the PNG keeps the + // resolution in whole pixels per meter). + assert!((width - 144.0).abs() < 0.5, "{width}"); +} + +#[test] +fn visible_normal_raster_layers_are_combined_at_the_canvas_size() { + let file = Bundle::new(vec![ + plain([255, 0, 0, 255], 1.0), + // Half its alpha and half its opacity: a quarter over the red. + plain([0, 0, 255, 128], 0.5), + // Hidden layers draw nothing, whatever they are. + layer(false, "Normal", 1.0, &raster(&rgba8([0, 255, 0, 255])), ""), + layer(false, "Screen", 1.0, r#"{"kind":"text","text":"A","cache":null}"#, r#","advanced":{"knockout":"deep"}"#), + ]) + .bytes(); + let (r, width, pixels) = place(&file); + assert!(warnings(&r).is_empty(), "{r}"); + assert_eq!((pixels.width(), pixels.height()), (300, 200), "the canvas's size, not the 30 × 20 preview's"); + let [red, green, blue, alpha] = pixels.to_rgba8().get_pixel(150, 100).0; + assert!(red > blue && blue > 0 && green == 0 && alpha == 255, "{:?}", [red, green, blue, alpha]); + assert!((width - 144.0).abs() < 0.5, "{width}"); + + // A 16-bit document's layers combine into 16-bit samples. + let mut b = Bundle::new(vec![layer(true, "Normal", 1.0, &raster(&surface("U16", "Rgb", true, "ffff000000000080")), "")]); + b.depth = "U16"; + let (_, _, pixels) = place(&b.bytes()); + assert!(matches!(pixels, image::DynamicImage::ImageRgba16(_)), "{:?}", pixels.color()); +} + +#[test] +fn a_layer_mask_hides_by_its_density_unless_it_is_off() { + // A mask that hides everything, at half density. + let mask = |enabled: bool, feather: f32| { + format!(r#"{{"surface":{},"enabled":{enabled},"linked":true,"density":0.5,"feather":{feather}}}"#, surface("U8", "Grayscale", false, "00")) + }; + let blue_at = |mask: &str| { + let top = layer_with(true, "Normal", 1.0, &raster(&rgba8([0, 0, 255, 255])), mask, NO_EFFECTS, ""); + let (r, _, pixels) = place(&Bundle::new(vec![plain([255, 0, 0, 255], 1.0), top]).bytes()); + (warnings(&r), pixels.to_rgba8().get_pixel(0, 0).0) + }; + let (w, [red, _, blue, _]) = blue_at(&mask(true, 0.0)); + assert!(w.is_empty() && red > 100 && blue > 100, "half hidden: {red} {blue}"); + let (w, [red, _, blue, _]) = blue_at(&mask(false, 0.0)); + assert!(w.is_empty() && red == 0 && blue == 255, "a mask that is off hides nothing: {red} {blue}"); + let (w, [red, ..]) = blue_at(&mask(true, 4.0)); + assert!(w.iter().any(|w| w.contains("feathered layer mask")) && red == 9, "a feathered mask leaves the preview: {w:?}"); +} + +#[test] +fn layers_that_cant_be_combined_leave_the_preview_with_a_note() { + let file = Bundle::new(vec![plain([255, 0, 0, 255], 1.0), layer(true, "Multiply", 1.0, &raster(&rgba8([0, 0, 255, 255])), "")]).bytes(); + let (r, width, pixels) = place(&file); + assert_eq!((pixels.width(), pixels.height()), (30, 20)); + let w = warnings(&r); + assert!(w.len() == 1 && w[0].contains("30 × 20 preview") && w[0].contains("300 × 200") && w[0].contains("Normal"), "{w:?}"); + // The preview covers the canvas, at the same size as the full image. + assert!((width - 144.0).abs() < 0.5, "{width}"); + + // Each other setting that changes how a layer draws leaves the preview too. + let pixels = raster(&rgba8([0; 4])); + let shadow = r#"{"enabled":true,"items":[{"DropShadow":{}}],"psd_raw":null}"#; + for (content, effects, extra, said) in [ + (pixels.as_str(), shadow, "", "layer effects"), + (&pixels, NO_EFFECTS, r#","blend_if":{"ranges":[1]}"#, "advanced blending"), + (&pixels, NO_EFFECTS, r#","excluded_channels":2"#, "advanced blending"), + (&pixels, NO_EFFECTS, r#","vector_mask":{"enabled":true,"path":{}}"#, "vector mask"), + (&pixels, NO_EFFECTS, r#","frame":{"path":{}}"#, "frame"), + (&pixels, NO_EFFECTS, r#","a_new_setting":true"#, "a_new_setting"), + (r#"{"kind":"group","children":[],"expanded":true}"#, NO_EFFECTS, "", "layer group"), + (r#"{"kind":"text","text":"A","cache":null}"#, NO_EFFECTS, "", "type layer"), + ] { + let l = layer_with(true, "Normal", 1.0, content, "null", effects, extra); + let (r, _, pixels) = place(&Bundle::new(vec![l]).bytes()); + let w = warnings(&r); + assert!(pixels.width() == 30 && w.len() == 1 && w[0].contains(said), "{said}: {w:?}"); + } + + // A preview of the canvas's own size is not reduced, so nothing is said. + let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]); + b.size = (30, 20); + let (r, _, pixels) = place(&b.bytes()); + assert!(warnings(&r).is_empty() && pixels.width() == 30, "{r}"); +} + +/// A linked preview keeps its size when it is read again: the resolution it was placed at is the +/// one its stored PNG gives back, at least 1 ppi when the canvas is far larger than the preview. +#[test] +fn a_linked_preview_keeps_its_size_when_it_is_updated() { + let dir = vectorcraft_testkit::TempDir::new("pcraft-preview-size"); + for (size, dpi) in [((300, 200), 150.0), ((300, 200), 72.0), ((3000, 2000), 10.0)] { + let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]); + (b.size, b.dpi) = (size, dpi); + let path = dir.join("art.pcraft"); + std::fs::write(&path, b.bytes()).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let width = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().width(); + let placed = width(&s); + for preserve in ["transforms", "bounds"] { + s.execute("links.relink", &json!({"ids": [id.0], "path": path.to_string_lossy(), "preserve": preserve})).unwrap(); + s.execute("links.update", &json!({"ids": [id.0]})).unwrap(); + assert!((width(&s) - placed).abs() < 1e-6, "{size:?} at {dpi} ppi, {preserve}: {} then {placed}", width(&s)); + } + // The 30 px preview places at the canvas's width, or at 1 ppi when that would take less. + let ppi = (f64::from(dpi) * 30.0 / f64::from(size.0)).max(1.0); + assert!((placed - 30.0 * 72.0 / ppi).abs() < 0.5, "{size:?} at {dpi} ppi: {placed}"); + } +} + +#[test] +fn damaged_or_unreadable_bundles_are_refused() { + let multiply = || vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]; + // The full-size composite the manifest names is missing, or not the canvas's size: never the preview. + let mut b = Bundle::new(multiply()); + b.full = Some(None); + assert!(place_error(&b.bytes()).contains("composite/full.png")); + b.full = Some(Some(png(30, 20, [0; 4]))); + assert!(place_error(&b.bytes()).contains("not 300 × 200")); + b.full = Some(Some(b"not a png".to_vec())); + assert!(place_error(&b.bytes()).contains("isn't a PNG")); + // No preview and layers that can't be combined. + let mut b = Bundle::new(multiply()); + b.preview = None; + assert!(place_error(&b.bytes()).contains("no full-size image or preview")); + // A newer format version. + let mut b = Bundle::new(multiply()); + b.version = 99; + assert!(place_error(&b.bytes()).contains("newer")); +} + +#[test] +fn pcraft_files_open_and_place_linked_and_updates_read_them_again() { + let b64 = vectorcraft_format::base64_encode; + let red = Bundle::new(vec![plain([255, 0, 0, 255], 1.0)]).bytes(); + let blue = Bundle::new(vec![plain([0, 0, 255, 255], 1.0)]).bytes(); + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"name": "art.pcraft", "dataBase64": b64(&red)})).unwrap(); + assert_eq!((&r["format"], &r["warnings"]), (&json!("pcraft"), &json!([])), "{r}"); + let multiply = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]).bytes(); + let r = s.execute("document.open", &json!({"name": "art.pcraft", "dataBase64": b64(&multiply)})).unwrap(); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("preview")), "Open says so too: {r}"); + + let dir = vectorcraft_testkit::TempDir::new("pcraft-link"); + let path = dir.join("art.pcraft"); + std::fs::write(&path, &red).unwrap(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap(); + let id = r["ids"][0].as_u64().unwrap(); + let shown = |s: &Session| { + let doc = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &doc.node(NodeId(id)).unwrap().kind else { panic!("an image") }; + assert!(im.link.is_some(), "linked"); + image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgba8().get_pixel(0, 0).0 + }; + assert_eq!(shown(&s), [255, 0, 0, 255]); + std::fs::write(&path, &blue).unwrap(); + s.execute("links.update", &json!({"ids": [id]})).unwrap(); + assert_eq!(shown(&s), [0, 0, 255, 255], "the update reads the file again"); + // A file that now has only its preview to show says so. + std::fs::write(&path, &multiply).unwrap(); + let r = s.execute("links.update", &json!({"ids": [id]})).unwrap(); + let w = warnings(&r); + assert!(w.len() == 1 && w[0].starts_with("art.pcraft: only the 30 × 20 preview"), "{r}"); + // A preview whose header reads but whose pixels don't is not taken: the link counts as missing. + let mut damaged = png(30, 20, [9, 9, 9, 255]); + let n = damaged.len(); + damaged[40..n - 12].fill(0xff); + let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]); + b.preview = Some(Some(damaged)); + let damaged = b.bytes(); + let e = s.execute("document.open", &json!({"name": "art.pcraft", "dataBase64": b64(&damaged)})).unwrap_err(); + assert!(e.to_string().contains("pixels can't be read"), "{e}"); + std::fs::write(&path, damaged).unwrap(); + let r = s.execute("links.update", &json!({"ids": [id]})).unwrap(); + assert_eq!(r["missing"], json!([id]), "{r}"); + let r = s.execute("links.replaceEmbedded", &json!({"ids": [id], "dataBase64": b64(&multiply)})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("preview")), "{r}"); + + // The dialogs list it; the desktop packaging doesn't associate it; nothing writes it. + assert!(OPEN_EXTS.contains(&"pcraft") && PLACE_EXTS.contains(&"pcraft") && UNASSOCIATED_EXTS.contains(&"pcraft")); + let r = s.execute("document.formats", &json!({})).unwrap(); + let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pcraft").unwrap().clone(); + assert_eq!((f["read"].as_bool(), f["write"].as_bool()), (Some(true), Some(false))); +} diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 37f4b132b5..1d6bd59fd1 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -602,6 +602,53 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() { assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again"); } +/// Place with Replace of an image changed by Perspective Distort or Free Distort by a clipped PSD +/// file with many more pixels keeps its corners when the image is tiny: the new image's transform +/// is the old one scaled down to the new pixel size, which is invertible however small it is. +#[test] +fn replacing_a_tiny_distorted_image_by_a_large_clipped_psd_keeps_its_corners() { + let dir = vectorcraft_testkit::TempDir::new("psd-replace-tiny-distorted"); + let plane = vec![255u8; 2000 * 2000]; + let zero = vec![0u8; 2000 * 2000]; + let big = psd(1, 3, (2000, 2000), 8, 3, &[], &triangle_resources(), &[], &raw(&[&plane, &zero, &zero])); + let cut = write_file(&dir, "big.psd", &big); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let png = crate::tests_links::png(4, 4, [0, 0, 255]); + let r = s + .execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": [100, 100, 0.001, 0.001]})) + .unwrap(); + let old = NodeId(r["ids"][0].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [old.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[100, 100], [100.001, 100.0001], [100.0009, 100.001], [99.9998, 100.0008]]})).unwrap(); + assert!(s.doc().unwrap().doc.node(old).unwrap().is_distorted_image(), "the old image is distorted"); + let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "replace": true})).unwrap(); + let image = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone(); + assert!(image.is_distorted_image()); + assert_eq!(image.image_corners().unwrap(), corners); +} + +/// Place with Replace of a clipped PSD file's image changed by Perspective Distort or Free Distort +/// by a DCS file keeps the image's corners: the DCS file's image fills them. +#[test] +fn replacing_a_distorted_clipped_psd_by_a_dcs_file_keeps_its_corners() { + let dir = vectorcraft_testkit::TempDir::new("psd-replace-distorted-dcs"); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let dcs = write_file(&dir, "pic.eps", &crate::tests::dcs::two_plates()); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap(); + let r = s.execute("file.place", &json!({"path": dcs, "replace": true})).unwrap(); + let new = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone(); + assert!(new.is_distorted_image(), "the DCS file's image takes the corners"); + assert_eq!(new.image_corners().unwrap(), corners); +} + /// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective /// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners, /// a clip group of the old file's clipping path loses it when the new file names none, and a later diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index cc210ffa2a..ded0f137b3 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -456,6 +456,30 @@ fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() { } } +/// A file placed with Replace over an image changed by Perspective Distort or Free Distort takes +/// its corners, and its slices cover what the corners put their part of the pixels on. +#[test] +fn slices_placed_over_a_distorted_image_follow_its_corners() { + let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 10, 10])], &[])); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let png = crate::tests_links::png(4, 4, [0, 0, 255]); + s.execute("file.place", &json!({"name": "a.png", "dataBase64": b64(&png), "at": [100, 100]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[100, 100], [160, 104], [150, 140], [96, 136]]})).unwrap(); + let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "replace": true})).unwrap(); + assert_eq!(r["slices"].as_array().map(Vec::len), Some(1), "{r}"); + let d = &s.doc().unwrap().doc; + let image = d.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + assert!(image.is_distorted_image()); + let vectorcraft_doc::NodeKind::Image(im) = &image.kind else { panic!("an image") }; + // The top left quarter of the 20 × 20 px canvas. + let (w, h) = (f64::from(im.width) / 2.0, f64::from(im.height) / 2.0); + let want = image.image_map().unwrap().map_rect_bbox(Rect::new(0.0, 0.0, w, h)).unwrap(); + let got = slices(&s)[0].0; + let near = |a: f64, b: f64| (a - b).abs() < 1e-6; + assert!(near(got.x0, want.x0) && near(got.y0, want.y0) && near(got.x1, want.x1) && near(got.y1, want.y1), "{got:?} vs {want:?}"); +} + #[test] fn linked_files_are_placed_without_their_slices() { let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id())); diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index c79f795b50..3ea811392d 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -576,23 +576,36 @@ struct ObjectOpacity { knockout_shape: bool, } +/// The series `id` belongs to when it is a graph series group or a path directly in one, as [`series_members`] finds +/// it. Looked up through its parents, with no pass over the document. +fn series_group_or_mark(doc: &Document, id: NodeId) -> Option { + let node = doc.node(id)?; + let chain = doc.ancestry(id)?; + let parent = doc.node(*chain.iter().rev().nth(1)?)?; + let in_graph = |group: &Node, graph: &Node| { + let index = group.extras().series_index.and_then(|i| usize::try_from(i).ok())?; + graph.extras().graph.as_deref().filter(|spec| index < series_count(spec)).map(|_| SeriesRef { graph: graph.id, group: group.id, index }) + }; + if let Some(r) = in_graph(node, parent) { + return Some(r); + } + // Only the paths the graph draws again, not the copy of a graph design. + if !matches!(node.kind, NodeKind::Path { .. }) { + return None; + } + in_graph(parent, doc.node(*chain.iter().rev().nth(2)?)?) +} + /// The graph, series, whether it is the series group itself (`true`) or a path directly in it, and the object -/// transparency of each of `edited` that is one of those, in order. +/// transparency of each of `edited` that is one of those, in order. Each object is looked up through its parents +/// ([`series_group_or_mark`]), so an edit of a few objects does not read the rest of the document. fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, bool, ObjectOpacity)> { - if edited.is_empty() { - return Vec::new(); - } - let members = series_members(doc); - if members.is_empty() { - return Vec::new(); - } edited .iter() .filter_map(|id| { - let r = members.get(id)?; + let r = series_group_or_mark(doc, *id)?; let group = r.group == *id; - // Only the series group and the paths the graph draws again, not the copy of a graph design. - let node = doc.node(*id).filter(|n| group || (doc.parent_of(*id) == Some(r.group) && matches!(n.kind, NodeKind::Path { .. })))?; + let node = doc.node(*id)?; let mut look = ObjectOpacity { opacity: (node.opacity < 1.0).then_some(node.opacity), blend: (node.blend != BlendMode::Normal).then_some(node.blend), @@ -675,6 +688,25 @@ fn graph_labels(doc: &Document) -> HashMap { out } +/// The graph and kind of generated label `id`, as [`graph_labels`] finds it. Only the graphs among its parent and +/// grandparent are read, with no pass over the document; `own` keeps each graph's labels read so far. +fn graph_label_of(doc: &Document, id: NodeId, own: &mut HashMap>) -> Option<(NodeId, Role)> { + if !doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) { + return None; + } + let chain = doc.ancestry(id)?; + // The nearer graph first: [`graph_labels`] visits it later, so its entry is the one kept. + for graph in chain.iter().rev().skip(1).take(2) { + let Some(n) = doc.node(*graph) else { continue }; + let Some(spec) = n.extras().graph.as_deref() else { continue }; + let labels = own.entry(*graph).or_insert_with(|| own_labels(n, spec).into_iter().collect()); + if let Some(role) = labels.get(&id) { + return Some((*graph, *role)); + } + } + None +} + /// The generated labels of graph `n` (with spec `g`) and what each shows, as [`graph_labels`] finds them. fn own_labels(n: &Node, g: &GraphSpec) -> Vec<(NodeId, Role)> { let mut out = vec![]; @@ -1725,9 +1757,9 @@ fn label_rows_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role, Option)> = vec![]; - for (&(g, role), n) in ids.iter().rev().filter_map(|id| Some((labels.get(id)?, doc.node(*id)?))) { + for ((g, role), n) in ids.iter().rev().filter_map(|id| Some((graph_label_of(doc, *id, &mut own)?, doc.node(*id)?))) { if !picked.iter().any(|(pg, pr, _)| *pg == g && *pr == role) { picked.push((g, role, label_rows(n))); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 5c7c75c610..78febf0f18 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Layer Options…", ["Window", "Layers"], None, - "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step", + "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given", has_doc, set_props ), @@ -400,6 +400,18 @@ fn apply_options(n: &mut Node, p: &Value, xml_id: bool) { } } +/// Whether Layer Options `p` ([`apply_options`]) would change row `n`: its name, eye, lock or +/// layer options. +fn changes_options(n: &Node, p: &Value, xml_id: bool) -> bool { + let mut after = n.clone(); + apply_options(&mut after, p, xml_id); + let options = |n: &Node| match &n.kind { + NodeKind::Layer { color, template, printable, preview, dim_images, .. } => Some((*color, *template, *printable, *preview, *dim_images)), + _ => None, + }; + after.name != n.name || after.visible != n.visible || after.locked != n.locked || options(&after) != options(n) +} + /// Bad values in Layer Options params, as an error for `cmd`. /// `xml_id`: Preferences › Units › Identify Objects By › XML ID — a non-empty `name` must be a /// valid XML id. @@ -706,6 +718,17 @@ fn set_props(s: &mut Session, p: &Value) -> Result { let name = if xml_id { vectorcraft_doc::xml_id::to_object_name(v) } else { v.to_string() }; super::buildcmds::check_part_name(&s.doc()?.doc, &ids, &name)?; } + // When every row already has every option given, the document and its undo history stay as + // they are. + let d = &s.doc()?.doc; + if ids.iter().all(|id| d.node(*id).is_some_and(|n| !changes_options(n, p, xml_id))) { + // Hidden or locked rows' art can't stay selected. + let flag = |k: &str| p.get(k).and_then(Value::as_bool); + if flag("visible") == Some(false) || flag("locked") == Some(true) || flag("template") == Some(true) { + s.select(|d, sel| sel.deselect_uneditable(d))?; + } + return ok(); + } s.edit("Layer Options", |d, sel| { for id in &ids { apply_options(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, p, xml_id); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 5a77b6d780..65f268f2b0 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Update Links", [], None, - "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. An image changed by Perspective Distort or Free Distort keeps its corners, with the file's pixels between them, and its Placement Options do not apply; the clipping path its file names is drawn through the corners, and a clip group of the old file's clipping path gets the new one, or becomes a plain group when the file names none. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", + "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. An image changed by Perspective Distort or Free Distort keeps its corners, with the file's pixels between them, and its Placement Options do not apply; the clipping path its file names is drawn through the corners, and a clip group of the old file's clipping path gets the new one, or becomes a plain group when the file names none. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns; a .pcraft file read only as its reduced preview, after the file's name]}", has_doc, update ), @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Replace Image", [], None, - "{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}", + "{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids], warnings?: [a .pcraft document read only as its reduced preview]}", has_doc, replace_embedded ), @@ -636,11 +636,12 @@ pub(crate) fn store_image(d: &mut Document, key: &str, full: ImageBlob, linked: d.images.insert(key.to_string(), blob); } -/// Whether `bytes` are a PNG, JPEG, GIF or WebP file: the formats [`fileio::raster_image`] keeps -/// as they are after reading only their header. +/// Whether `bytes` are a PNG, JPEG, GIF or WebP file, the formats [`fileio::raster_image`] keeps +/// as they are after reading only their header, or a `.pcraft` document, whose full-size composite +/// or preview it keeps the same way. pub(crate) fn kept_unread(bytes: &[u8]) -> bool { use craft_image_codecs::Format as F; - matches!(craft_image_codecs::detect(bytes), Some(F::Png | F::Jpeg | F::Gif | F::WebP)) + matches!(craft_image_codecs::detect(bytes), Some(F::Png | F::Jpeg | F::Gif | F::WebP)) || fileio::is_pcraft(bytes) } /// `blob`, an image [`fileio::raster_image`] read from a file, ready to keep. When `unread` (the @@ -1275,8 +1276,13 @@ fn replace_embedded(s: &mut Session, p: &Value) -> Result { let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?; let mut img = fileio::raster_image(&bytes)?; img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?; + let note = img.note.clone(); s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?; - Ok(json!({ "replaced": ids_json(&ids) })) + let mut out = json!({ "replaced": ids_json(&ids) }); + if let Some(note) = note { + out["warnings"] = json!([note]); + } + Ok(out) } /// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels @@ -1308,7 +1314,7 @@ fn refill_distorted( /// `path` with its anchors and handles mapped through `map` as a distort maps a path's points /// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front /// of it, and one past it to the far side. `None` when a point maps to no finite page point. -fn warped(path: &PathData, map: &Homography) -> Option { +pub(super) fn warped(path: &PathData, map: &Homography) -> Option { let [[a, b, c], [d, e, f], [g, h, i]] = map.0; let apply = |p: vectorcraft_geom::Point| { let w = g * p.x + h * p.y + i; @@ -2089,7 +2095,8 @@ fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) - } } let updated: Vec = reads.iter().flat_map(|(g, _)| ids_json(&g.ids)).collect(); - let warnings = spot_swatch_notes(&st.doc, reads.iter().map(|(_, read)| read)); + let mut warnings = spot_swatch_notes(&st.doc, reads.iter().map(|(_, read)| read)); + warnings.extend(file_notes(reads.iter().map(|(_, read)| read))); if !reads.is_empty() { s.edit("Update Links", |d, _| { editing_brush_art(d, |d| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g)))) @@ -2102,6 +2109,22 @@ fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) - Ok(out) } +/// The notes of the images in `reads` that leave part of their file out ([`RasterImage::note`], a +/// `.pcraft` document read as its reduced preview), each after its file's name, once per file. +fn file_notes<'a>(reads: impl Iterator) -> Vec { + let mut out: Vec = vec![]; + for read in reads { + let Read::Image((link, img)) = read else { continue }; + let Some(note) = &img.note else { continue }; + let name = Path::new(&link.path).file_name().map_or_else(|| link.path.clone(), |n| n.to_string_lossy().into_owned()); + let note = format!("{name}: {note}"); + if !out.contains(¬e) { + out.push(note); + } + } + out +} + /// The warnings for the spot plates of the DCS files in `reads` whose ink a swatch of `d` already /// names in another color, or as a process color ([`super::place::dcs::swatch_notes`]), or that an /// earlier file of `reads` adds as a spot swatch in another color, each once. @@ -2354,6 +2377,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { let unpreserved = preserve.and_then(|_| unpreserved_note(&doc, &reads)); drop(doc); let mut warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read)); + warnings.extend(file_notes(reads.iter().map(|(_, read)| read))); warnings.extend(unpreserved); if !reads.is_empty() { s.edit("Relink", |d, _| editing_brush_art(d, |d| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None))))?; diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 379130629c..8385350b2e 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -9,7 +9,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::marks::{MarkStyle, TrimMarks}; use vectorcraft_doc::{Appearance, ImageObject, LiveShape, Node, NodeId, NodeKind, RasterColorModel, RasterEffectsSettings, Scaling}; -use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, Vec2}; +use vectorcraft_geom::{Affine, Anchor, Homography, PathData, Point, Rect, Vec2}; use vectorcraft_render::AntiAlias; use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; @@ -133,7 +133,7 @@ pub fn specs() -> Vec { "Create Object Mosaic…", ["Object"], None, - "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it, both growing or shrinking in proportion to keep the sizes within 0.1..1000000), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles colored by the selected image's average tile colors → {id, tiles, columns, rows}", + "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it, both growing or shrinking in proportion to keep the sizes within 0.1..1000000), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles colored by the selected image's average tile colors; on an image changed by Perspective Distort or Free Distort each tile is its cell placed between the image's corners, a four-sided shape, and spacing is measured at the mean length of the image's sides → {id, tiles, columns, rows}", has_image, object_mosaic ), @@ -981,6 +981,9 @@ struct MosaicPlan { cols: u32, rows: u32, xf: Affine, + /// For a distorted image, the map from its pixels to the page that places the tiles instead of + /// `xf`. + warp: Option, tile: (f64, f64), gap: (f64, f64), gray: bool, @@ -1001,9 +1004,6 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result { .ok_or_else(|| bad(C, "select an image"))?; let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) }; - if node.is_distorted_image() { - return Err(super::xform::distorted_image_error(C, id)); - } if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) { return Err(bad(C, "the image has no embedded pixels")); } @@ -1062,11 +1062,21 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result { }; let resize = Affine::translate(b.origin().to_vec2()) * Affine::scale_non_uniform(nw / bw, nh / bh) * Affine::translate(-b.origin().to_vec2()); let xf = resize * im.xf; - // Points per image pixel along each of the image's axes (the image may be turned). - let ppx = (xf * Point::new(1.0, 0.0) - xf * Point::ZERO).hypot().max(1e-9); - let ppy = (xf * Point::new(0.0, 1.0) - xf * Point::ZERO).hypot().max(1e-9); - let (sx, sy) = (f64_or(p, "spacingX", 0.0).max(0.0), f64_or(p, "spacingY", 0.0).max(0.0)); let (iw, ih) = (im.width as f64, im.height as f64); + // A distorted image's tiles are its cells mapped between its corners, resized the same way. + let warp = node.image_map().filter(|_| node.is_distorted_image()).map(|h| Homography::from_affine(resize).then_after(&h)); + // Points per image pixel along each of the image's axes (the image may be turned). A distorted + // image's sides change length along the way: each axis takes the mean of its two sides. + let (ppx, ppy) = match &warp { + Some(h) => { + let corner = |x: f64, y: f64| h.apply(Point::new(x, y)).ok_or_else(|| super::xform::distorted_image_error(C, id)); + let [a, b, c, d] = [corner(0.0, 0.0)?, corner(iw, 0.0)?, corner(iw, ih)?, corner(0.0, ih)?]; + ((a.distance(b) + d.distance(c)) / (2.0 * iw.max(1.0)), (a.distance(d) + b.distance(c)) / (2.0 * ih.max(1.0))) + } + None => ((xf * Point::new(1.0, 0.0) - xf * Point::ZERO).hypot(), (xf * Point::new(0.0, 1.0) - xf * Point::ZERO).hypot()), + }; + let (ppx, ppy) = (ppx.max(1e-9), ppy.max(1e-9)); + let (sx, sy) = (f64_or(p, "spacingX", 0.0).max(0.0), f64_or(p, "spacingY", 0.0).max(0.0)); // Use Ratio: square tiles as drawn, spacing taken off, from the count on the kept side, // measured along the image's axes. match use_ratio { @@ -1078,7 +1088,7 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result { // Spacing is in points; convert to image pixels along each axis. let gap = ((sx / ppx).min(tw * 0.9), (sy / ppy).min(th * 0.9)); let delete = switch_or(p, "deleteRaster", false, C)?; - Ok(MosaicPlan { id, im: im.as_ref().clone(), cols, rows, xf, tile: (tw, th), gap, gray, delete }) + Ok(MosaicPlan { id, im: im.as_ref().clone(), cols, rows, xf, warp, tile: (tw, th), gap, gray, delete }) } /// The tile counts (columns, rows) `object.createObjectMosaic` would use with `p`, Use Ratio @@ -1089,10 +1099,26 @@ pub fn mosaic_counts(s: &Session, p: &Value) -> Result<(u32, u32)> { fn object_mosaic(s: &mut Session, p: &Value) -> Result { const C: &str = "object.createObjectMosaic"; - let MosaicPlan { id, im, cols, rows, xf, tile: (tw, th), gap: (gx, gy), gray, delete } = mosaic_plan(s, p)?; + let MosaicPlan { id, im, cols, rows, xf, warp, tile: (tw, th), gap: (gx, gy), gray, delete } = mosaic_plan(s, p)?; let blob = s.doc()?.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image has no embedded pixels"))?; let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?; let colors = vectorcraft_trace::mosaic(&raster, cols, rows); + // Each tile's corners on the page, its cell less the spacing, through `warp` or `xf`. + let mut quads = Vec::with_capacity(colors.len()); + for r in 0..rows { + for c in 0..cols { + let x0 = c as f64 * tw + gx / 2.0; + let y0 = r as f64 * th + gy / 2.0; + let cell = [Point::new(x0, y0), Point::new(x0 + tw - gx, y0), Point::new(x0 + tw - gx, y0 + th - gy), Point::new(x0, y0 + th - gy)]; + let mut quad = cell.map(|q| xf * q); + if let Some(h) = &warp { + for (to, q) in quad.iter_mut().zip(cell) { + *to = h.apply(q).ok_or_else(|| super::xform::distorted_image_error(C, id))?; + } + } + quads.push(quad); + } + } let (gid, n) = s.edit("Create Object Mosaic", |d, sel| { let mut tiles = vec![]; for r in 0..rows { @@ -1101,10 +1127,7 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result { if ca == 0 { continue; } - let x0 = c as f64 * tw + gx / 2.0; - let y0 = r as f64 * th + gy / 2.0; - let quad = [Point::new(x0, y0), Point::new(x0 + tw - gx, y0), Point::new(x0 + tw - gx, y0 + th - gy), Point::new(x0, y0 + th - gy)] - .map(|q| xf * q); + let quad = quads[(r * cols + c) as usize]; let color = if gray { let l = (0.299 * cr as f32 + 0.587 * cg as f32 + 0.114 * cb as f32) / 255.0; Color::rgb(l, l, l) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 47190a2cdf..de893c79da 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 8d2a344ffe..81909da76f 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -443,10 +443,18 @@ fn changed_aligned(before: &[Arc], after: &[Arc], out: &mut Vec, angle: Option) -> Option Option { + let ratio = |was: f64, now: f64| if was == now { 1.0 } else { now / was }; + let xf = match (old, new) { + (LiveShape::Rectangle { w, h, xf, .. }, LiveShape::Rectangle { w: w2, h: h2, xf: xf2, .. }) + | (LiveShape::Ellipse { w, h, xf, .. }, LiveShape::Ellipse { w: w2, h: h2, xf: xf2, .. }) => { + if xf == xf2 && w == w2 && h == h2 { + return None; + } + *xf2 * Affine::scale_non_uniform(ratio(*w, *w2), ratio(*h, *h2)) * xf.inverse() + } + (LiveShape::Polygon { radius, xf, .. }, LiveShape::Polygon { radius: r2, xf: xf2, .. }) => { + if xf == xf2 && radius == r2 { + return None; + } + *xf2 * Affine::scale(ratio(*radius, *r2)) * xf.inverse() + } + (LiveShape::Line { a, b }, LiveShape::Line { a: a2, b: b2 }) => { + let (d, d2) = (*b - *a, *b2 - *a2); + let len2 = d.hypot2(); + if (a == a2 && b == b2) || len2 <= 0.0 { + return None; + } + // `d2` divided by `d` as complex numbers: the turn and even scale between them. + let (c, s) = ((d2.x * d.x + d2.y * d.y) / len2, (d2.y * d.x - d2.x * d.y) / len2); + let turn = Affine::new([c, s, -s, c, 0.0, 0.0]); + Affine::translate(*a2 - turn * *a) * turn + } + _ => return None, + }; + xf.as_coeffs().iter().all(|c| c.is_finite()).then_some(xf) +} + pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { - check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii"], "object.setLiveShape")?; + check_switches( + p, + &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii", "strokes", "patterns"], + "object.setLiveShape", + )?; check_numbers(p, &["radius", "sides"], "object.setLiveShape")?; // `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them. let items = match p.get("items").filter(|v| !v.is_null()) { @@ -317,50 +361,87 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return ok(); } + // The live shapes that the polygon, rectangle, ellipse and line values change: each as it is and + // as it becomes. + let mut reshaped = std::collections::BTreeMap::new(); + for id in &ids { + let Some(NodeKind::Path { live: Some(old), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue }; + let mut new = (**old).clone(); + let mut edited = false; + if let l @ LiveShape::Polygon { .. } = &mut new + && (sides.is_some() || polygon_angle.is_some() || polygon_radius.is_some() || side.is_some() || equal) + { + if let Some(n) = sides { + l.set_sides(n); + } + if equal { + l.make_sides_equal(); + } + if let Some(a) = polygon_angle { + l.set_polygon_angle(a); + } + // A side length sets the radius that gives it (with the new side count). + if let Some(r) = side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius) { + l.set_polygon_radius(r); + } + edited = true; + } + if let Some(a) = rectangle_angle + && let l @ LiveShape::Rectangle { .. } = &mut new + { + l.set_shape_angle(a); + edited = true; + } + if let l @ LiveShape::Ellipse { .. } = &mut new + && (pie_start.is_some() || pie_end.is_some() || invert || ellipse_angle.is_some()) + { + if let Some(a) = ellipse_angle { + l.set_shape_angle(a); + } + if let LiveShape::Ellipse { pie, .. } = l { + *pie = pie_of(*pie); + } + edited = true; + } + if let Some(line) = lines.get(id) { + new = line.clone(); + edited = true; + } + if edited { + reshaped.insert(*id, ((**old).clone(), new)); + } + } + // A shape that moves, turns or scales takes the rest of the object along as a transform does: + // Scale Strokes & Effects and Transform Patterns come from `strokes` and `patterns` or the + // preferences, and are noted in the journal so a replay does the same. Corner radii in the rest + // of the object keep their size, as the shape's own do; Scale Corners does not apply. + let carried: Vec = reshaped.iter().filter(|(_, (old, new))| carry(old, new).is_some()).map(|(id, _)| *id).collect(); + let scales = reshaped.values().any(|(old, new)| carry(old, new).is_some_and(|xf| Scaling::factor(xf).is_some())); + let base = if scales { + let sc = scaling_options(s, p); + s.note_journal("strokes", serde_json::json!(sc.strokes)); + sc + } else { + Scaling::default() + }; + let sc = Scaling { patterns: !carried.is_empty() && transform_patterns(s, p, &carried)?, keep_corners: true, ..base }; s.edit("Live Shape", |d, sel| { + // Each object once, however often `ids` or `items` names it. + for (id, (old, new)) in &reshaped { + let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?; + if let Some(xf) = carry(old, new) { + // The bounding box keeps its angle: a shape angle is the shape's own. + let bbox_angle = n.bbox_angle; + n.transform(xf, sc); + n.bbox_angle = bbox_angle; + } + if let NodeKind::Path { path, live, .. } = &mut n.kind { + *live = Some(Box::new(new.clone())); + *path = new.to_path(); + } + } for id in &ids { let Some(NodeKind::Path { path, live, .. }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; - if let Some(l @ LiveShape::Polygon { .. }) = live.as_deref_mut() - && (sides.is_some() || polygon_angle.is_some() || polygon_radius.is_some() || side.is_some() || equal) - { - if let Some(n) = sides { - l.set_sides(n); - } - if equal { - l.make_sides_equal(); - } - if let Some(a) = polygon_angle { - l.set_polygon_angle(a); - } - // A side length sets the radius that gives it (with the new side count). - if let Some(r) = side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius) { - l.set_polygon_radius(r); - } - *path = l.to_path(); - } - if let Some(a) = rectangle_angle - && let Some(l @ LiveShape::Rectangle { .. }) = live.as_deref_mut() - { - l.set_shape_angle(a); - *path = l.to_path(); - } - if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut() - && (pie_start.is_some() || pie_end.is_some() || invert || ellipse_angle.is_some()) - { - if let Some(a) = ellipse_angle { - l.set_shape_angle(a); - } - if let LiveShape::Ellipse { pie, .. } = l { - *pie = pie_of(*pie); - } - *path = l.to_path(); - } - if let Some(new) = lines.get(id) - && let Some(l) = live.as_deref_mut() - { - *l = new.clone(); - *path = l.to_path(); - } if let Some(on) = relative_radii && let Some(l) = live.as_deref_mut() { @@ -385,8 +466,10 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { }; recut(path, live, partial, &picked, radius, kind); } + // The snap to the pixel grid moves the patterns of a carried shape when the carry did. for id in &ids { - super::pixelgrid::resnap(d, *id); + let snap = Scaling { patterns: sc.patterns && carried.contains(id), ..Scaling::default() }; + super::pixelgrid::resnap_with(d, *id, snap); } // A shape named in `ids` and not selected is not checked after the edit: one that a turn or // a new radius would take past the coordinate limit is an error here, and nothing changes. diff --git a/crates/engine/src/cmd/object/spans.rs b/crates/engine/src/cmd/object/spans.rs index 57fe9aeb2c..88e9629a82 100644 --- a/crates/engine/src/cmd/object/spans.rs +++ b/crates/engine/src/cmd/object/spans.rs @@ -1,5 +1,5 @@ use super::shape::scale_across; -use super::{Affine, Document, Node, NodeId, NodeKind, OrientedBox, Point, Rect}; +use super::{Affine, Appearance, Document, Node, NodeId, NodeKind, OrientedBox, Point, Rect}; /// One axis of an object that [`set_bounds`] sizes, square to its frame: the geometric box runs /// from `lo` to `hi`, and the visual box reaches past each end (before, after) by a margin that @@ -47,27 +47,47 @@ impl Spans { (true, true) => n.visual_bounds_with(s), (false, _) => n.bounds_in(s, to_local, visual), }; + // The box the strokes of the plain groups around `n` paint along it, square to `frame` + // (`Node::painted_by_container`). + let painted = |n: &Node, groups: &[&Appearance], s: &vectorcraft_doc::SymbolBoxes| { + if groups.is_empty() { + return None; + } + let placed; + let n = if frame.angle == 0.0 { + n + } else { + let mut m = n.clone(); + m.transform(to_local, false); + placed = m; + &placed + }; + groups.iter().fold(None, |acc, a| vectorcraft_geom::union_opt(acc, n.painted_by_container(a, Some(s)))) + }; let roots: Vec<&Node> = ids.iter().filter_map(|id| d.node(*id)).collect(); let mut parts = vec![]; - if !roots.iter().all(|n| open(n, 0.0, d, &symbols, to_local, &mut parts)) { - parts = roots.iter().map(|n| Part::Object(n, 0.0)).collect(); + if !roots.iter().all(|n| open(n, &[], d, &symbols, to_local, &mut parts)) { + parts = roots.iter().map(|n| Part::Object(n, vec![])).collect(); } let mut out = Self { x: vec![], y: vec![], strokes }; for part in parts { let (g, v, vs) = match part { - Part::Object(n, grow) => { + Part::Object(n, groups) => { let Some(g) = measure(n, &symbols, false) else { continue }; - let v = measure(n, &symbols, true).unwrap_or(g).inflate(grow, grow); - let vs = if strokes { measure(n, &without, true).unwrap_or(g).inflate(grow, grow) } else { g }; + let v = vectorcraft_geom::union_opt(measure(n, &symbols, true), painted(n, &groups, &symbols)).unwrap_or(g); + let vs = + if strokes { vectorcraft_geom::union_opt(measure(n, &without, true), painted(n, &groups, &without)).unwrap_or(g) } else { g }; (g, v, vs) } // Measured as the instance's own box measures its art (`Node::visual_bounds_with`): - // the strokes at their own weight, and the instances in it by their art boxes. + // the strokes at their own weight, those of the plain groups around it in the art + // included, and the instances in it by their art boxes. Part::Art(n, xf, grow, kept) => { let mut placed = n.clone(); placed.transform(xf, false); let Some(g) = placed.geometric_bounds_with(&art) else { continue }; - let v = placed.visual_bounds_with(&art).map_or(g, |v| v.union(g)).inflate(kept + grow, kept + grow); + let v = placed.visual_bounds_with(&art).map_or(g, |v| v.union(g)); + let v = kept.iter().fold(v, |v, a| placed.painted_by_container(a, Some(&art)).map_or(v, |p| v.union(p))).inflate(grow, grow); let vs = if strokes { g.inflate(grow, grow) } else { g }; (g, v, vs) } @@ -155,29 +175,40 @@ const MAX_SPANS: usize = 4096; /// What [`Spans::measure`] measures as one span. enum Part<'a> { - /// An object of the selection, or a member of a plain group in it, and the outset of the - /// strokes of the plain groups around it, which scale with its own. - Object(&'a Node, f64), + /// An object of the selection, or a member of a plain group in it, and the appearances of the + /// plain groups around it, whose strokes paint along it and scale with its own. + Object(&'a Node, Vec<&'a Appearance>), /// An object in the art of a symbol instance and the transform that places it square to the - /// frame. The outset of the strokes of the instance and of the plain groups around the instance - /// scales with the strokes; the outset of the strokes of the plain groups around the object in - /// the art stays, as the strokes in the art do. - Art(&'a Node, Affine, f64, f64), + /// frame. The outset of the strokes of the instance scales with the strokes; the strokes of the + /// plain groups around the object in the art, given by their appearances, paint along it and + /// stay, as the strokes in the art do. The strokes of the plain groups around the instance paint + /// nothing round it. + Art(&'a Node, Affine, f64, Vec<&'a Appearance>), } -/// Adds the parts that [`Spans::measure`] measures `n` by to `parts`, `grow` being the outset of -/// the strokes of the plain groups around it ([`Part::Object`]). A plain group ([`opens`]) adds the -/// parts of each member. A symbol instance without effects or an opacity mask of its own adds the -/// objects of its art, with plain groups there opened too ([`Part::Art`]), when its symbol's art +/// Adds the parts that [`Spans::measure`] measures `n` by to `parts`, `groups` being the +/// appearances of the plain groups around it ([`Part::Object`]); hidden members and guides stop +/// those groups' strokes. A plain group ([`opens`]) adds the parts of each member. A symbol +/// instance without effects or an opacity mask of its own adds the objects of its art, with plain +/// groups there opened too ([`Part::Art`]), when its symbol's art /// measures it, it is not in perspective, and its transform keeps the art square to the frame (a /// turned or slanted instance is measured by the box around its turned art box). Anything else is /// one part. Returns false when the parts pass [`MAX_SPANS`]. -fn open<'a>(n: &'a Node, grow: f64, d: &'a Document, symbols: &vectorcraft_doc::SymbolBoxes, to_local: Affine, parts: &mut Vec>) -> bool { +fn open<'a>( + n: &'a Node, + groups: &[&'a Appearance], + d: &'a Document, + symbols: &vectorcraft_doc::SymbolBoxes, + to_local: Affine, + parts: &mut Vec>, +) -> bool { + let groups = if n.visible && !n.is_guide() { groups } else { &[] }; if opens(n) { match &n.kind { NodeKind::Group { children, .. } => { - let grow = grow + n.appearance.outset(); - return children.iter().all(|c| open(c, grow, d, symbols, to_local, parts)); + let mut groups = groups.to_vec(); + groups.push(&n.appearance); + return children.iter().all(|c| open(c, &groups, d, symbols, to_local, parts)); } NodeKind::SymbolInstance { symbol, xf } => { let xf = to_local * *xf; @@ -186,38 +217,41 @@ fn open<'a>(n: &'a Node, grow: f64, d: &'a Document, symbols: &vectorcraft_doc:: && symbols.art_bounds(symbol).is_some() && let Some(art) = d.symbols.iter().find(|s| s.name == *symbol) { - return open_art(&art.art, xf, grow + n.appearance.outset(), 0.0, parts); + return open_art(&art.art, xf, n.appearance.outset(), &[], parts); } } _ => {} } } - parts.push(Part::Object(n, grow)); + parts.push(Part::Object(n, groups.to_vec())); parts.len() <= MAX_SPANS } /// [`open`] for `n` in symbol art that `xf` places square to the frame: a plain group adds the parts -/// of each member, and anything else, a symbol instance included, is one part. `kept` is the outset -/// of the strokes of the plain groups around `n` in the art, and `grow` that of the instance and the -/// plain groups around it. -fn open_art<'a>(n: &'a Node, xf: Affine, grow: f64, kept: f64, parts: &mut Vec>) -> bool { +/// of each member, and anything else, a symbol instance included, is one part. `kept` holds the +/// appearances of the plain groups around `n` in the art, stopped at hidden members and guides, +/// and `grow` is the outset of the strokes of the instance. +fn open_art<'a>(n: &'a Node, xf: Affine, grow: f64, kept: &[&'a Appearance], parts: &mut Vec>) -> bool { + let kept = if n.visible && !n.is_guide() { kept } else { &[] }; if let NodeKind::Group { children, .. } = &n.kind && opens(n) { - let kept = kept + n.appearance.outset(); - return children.iter().all(|c| open_art(c, xf, grow, kept, parts)); + let mut kept = kept.to_vec(); + kept.push(&n.appearance); + return children.iter().all(|c| open_art(c, xf, grow, &kept, parts)); } - parts.push(Part::Art(n, xf, grow, kept)); + parts.push(Part::Art(n, xf, grow, kept.to_vec())); parts.len() <= MAX_SPANS } -/// Whether [`open`] opens `n`: a group without a clip, a Shaper construction, effects or an opacity -/// mask of its own, or a symbol instance without effects or an opacity mask of its own. +/// Whether [`open`] opens `n`: a group that is not a compound shape and has no clip, Shaper +/// construction, effects or opacity mask of its own, or a symbol instance without effects or an +/// opacity mask of its own. fn opens(n: &Node) -> bool { let visible = |effects: &[vectorcraft_doc::Effect]| effects.iter().any(|e| e.visible); let effects = visible(&n.appearance.effects) || n.appearance.items.iter().any(|i| visible(i.effects())); let kind = match n.kind { - NodeKind::Group { clip, .. } => !clip && n.extras().shaper.is_none(), + NodeKind::Group { clip, .. } => !clip && !n.is_compound_shape() && n.extras().shaper.is_none(), NodeKind::SymbolInstance { .. } => true, _ => false, }; diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 527957f234..1a15e44aa3 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -63,15 +63,15 @@ pub(super) fn scaling_options(s: &Session, p: &Value) -> Scaling { } /// Transform Patterns: do the pattern fills and strokes of `ids` transform with them (`patterns` -/// param, else General › Transform Pattern Tiles)? Noted in the journal when they use a pattern, -/// so a replay moves their tiles alike whatever the preference is then. +/// param, else General › Transform Pattern Tiles)? Noted in the journal when they or the art of +/// their linked opacity masks use a pattern, so a replay moves their tiles alike whatever the preference is then. pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result { let on = bool_or(p, "patterns", s.prefs.transform_pattern_tiles); let d = &s.doc()?.doc; let mut uses = false; let paths = d.index_paths(ids.iter().copied()); for n in ids.iter().filter_map(|id| paths.get(id)).filter_map(|p| d.node_at(p)) { - n.walk(&mut |c| uses |= vectorcraft_doc::pattern::uses_pattern(c, None)); + uses |= uses_pattern_with_masks(n); } if uses { s.note_journal("patterns", json!(on)); @@ -79,6 +79,17 @@ pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) -> Ok(on) } +/// Whether `n`, a descendant or the art of a linked opacity mask among them (and theirs) has a +/// pattern fill or stroke: what Transform Patterns moves when `n` is transformed. +fn uses_pattern_with_masks(n: &vectorcraft_doc::Node) -> bool { + let mut uses = false; + n.walk(&mut |c| { + uses |= vectorcraft_doc::pattern::uses_pattern(c, None) + || c.extras().mask.as_deref().is_some_and(|m| m.linked && uses_pattern_with_masks(&m.art)); + }); + uses +} + /// Transform Objects (`objects` param, on unless it is false): off, a transform leaves the art /// where it is and, with Transform Patterns, moves only its pattern tiles. pub(crate) fn transforms_objects(p: &Value) -> bool { diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 7756cada1d..88ee200c2c 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed), or with an opacity alone how many took the opacity}", has_doc, |s, p| set_paint(s, p, true) ), @@ -394,6 +394,76 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&' } } +#[cfg(test)] +thread_local! { + /// Tests: how many fills [`SelectionPaints`] read or took out on this thread. + pub(crate) static PAINTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many stroke weights [`SelectionPaints`] read or took out on this thread. + pub(crate) static WEIGHTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The objects that reading objects `ids` meets, one item each ([`SelectionPaints::reads_no_more_than`]): +/// each id, and the contents of a group, a layer, a Live Paint group or a container inside a group, +/// as [`painted`] expands them. An id with no object and a ruler guide count once each. A type +/// object counts once for each of its runs, since the stroke weights are read run by run. +struct Reads<'a> { + doc: &'a Document, + ids: std::slice::Iter<'a, NodeId>, + /// The contents not counted yet of the objects met, innermost last. + left: Vec>>, + /// The runs not counted yet of the type object met last. + runs: usize, +} + +impl<'a> Reads<'a> { + fn new(doc: &'a Document, ids: &'a [NodeId]) -> Self { + Self { doc, ids: ids.iter(), left: vec![], runs: 0 } + } +} + +impl Iterator for Reads<'_> { + type Item = (); + + fn next(&mut self) -> Option<()> { + if self.runs > 0 { + self.runs -= 1; + return Some(()); + } + loop { + let (n, top) = match self.left.last_mut() { + Some(contents) => match contents.next() { + Some(c) => (&**c, false), + None => { + self.left.pop(); + continue; + } + }, + None => match self.doc.node(*self.ids.next()?) { + Some(n) => (n, true), + None => return Some(()), + }, + }; + // A ruler guide has no paints, but reading meets it, so it counts once. + if n.is_ruler_guide() { + return Some(()); + } + // A Live Paint group is a group too, so it expands without looking for its parts. + let expand = match n.kind { + NodeKind::Group { .. } | NodeKind::Layer { .. } => true, + NodeKind::Compound { .. } => false, + _ => !top && n.is_container(), + }; + if let Some(contents) = n.children().filter(|_| expand) { + self.left.push(contents.iter()); + } + if let NodeKind::Text(t) = &n.kind { + self.runs = t.runs.len().saturating_sub(1); + } + return Some(()); + } + } +} + /// What the proxies read from selected objects: the first fill, stroke and stroke weight met, and /// whether another one differs ([`DocState::proxy_mixed`] without an active Appearance item or /// picked mesh points, and [`super::stroke::StrokeMixed::weight`]), and whether an object lies in a @@ -489,6 +559,23 @@ impl SelectionPaints { self.may_hold_mesh > 0 } + /// Does reading objects `ids` of `doc` meet no more objects than reading objects `others`? + /// Each id counts once, and a group, a layer, a Live Paint group or a container inside a group + /// also counts its contents, as [`painted`] expands them. The two counts go up one object at a + /// time in turn and stop when either side runs out, so the check meets at most twice as many + /// objects as the smaller side holds. + pub(crate) fn reads_no_more_than(doc: &Document, ids: &[NodeId], others: &[NodeId]) -> bool { + let (mut these, mut those) = (Reads::new(doc, ids), Reads::new(doc, others)); + loop { + if these.next().is_none() { + return true; + } + if those.next().is_none() { + return false; + } + } + } + /// Read objects `ids` of `doc` too: ids that are not read yet, each named once. pub(crate) fn add(&mut self, doc: &Document, ids: &[NodeId]) { self.each(doc, ids, true); @@ -517,6 +604,8 @@ impl SelectionPaints { painted(n, true, false, &mut fills); painted(n, true, true, &mut strokes); } + #[cfg(test)] + PAINTS_READ.with(|c| c.set(c.get() + fills.len())); for n in fills { meet(&mut self.fill, proxy_paint(n, false, None)); } @@ -541,6 +630,8 @@ impl SelectionPaints { NodeKind::Text(t) => t.runs.iter().map(|r| r.style.stroke_layer().width).collect(), _ => n.appearance.stroke().map(|s| s.width).into_iter().collect(), }; + #[cfg(test)] + WEIGHTS_READ.with(|c| c.set(c.get() + widths.len())); for w in widths { if add { self.weight.add(w, |a, b| a == b); @@ -834,6 +925,11 @@ fn opacity_param(p: &Value, cmd: &str) -> Result> { } } +/// Whether `p` gives `key` a value other than null. +fn names(p: &Value, key: &str) -> bool { + p.get(key).is_some_and(|v| !v.is_null()) +} + /// The error for an `opacity` that would go to type characters, which have no opacity of their own. fn characters_have_no_opacity(cmd: &str) -> EngineError { bad(cmd, "type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke") @@ -863,13 +959,22 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; let for_tool = tool_color_params(s, p, cmd, !fill)?; let p = for_tool.as_ref().unwrap_or(p); + // A bad `target` or `aligned` is refused for every kind of target: selected characters take + // the paint before `item_target` reads either. + super::appearance::aligned(p, cmd)?; + super::appearance::targets_contents(p)?; let focus = switch_or(p, "focus", true, cmd)?; // An opacity alone places no gradient, so `span` may only be "object" with it. let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?; // Characters selected with the Type tool take the paint, not the whole type object (#1063). A // null `ids` or `id` names no object, as `given_nodes` reads it. - if ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) - && p.get("item").is_none() + let on_characters = !names(p, "ids") && !names(p, "id") && p.get("item").is_none(); + // An opacity for the characters is refused before their typing session ends, so the session + // and its undo step stay as they are. + if on_characters && opacity.is_some() && super::textedit::selected_range(s).is_some_and(|(_, a, b)| a != b) { + return Err(characters_have_no_opacity(cmd)); + } + if on_characters && let Some((id, a, b)) = super::textedit::editing_range(s)? && a != b { @@ -1378,7 +1483,7 @@ impl DocState { /// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands /// then change that object. A bad `target` or `aligned` is refused as it is for any other selection. fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result)>> { - if p.get("ids").is_some() || p.get("id").is_some() || p.get("item").is_some() { + if names(p, "ids") || names(p, "id") || p.get("item").is_some() { return Ok(None); } let part = super::brushsym::selected_part(s)?; @@ -1895,6 +2000,8 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( Some(ids) => ids, None => super::edit::selected_roots(s)?, }; + // Read before the default is recolored, so that a bad `target` or `aligned` is refused with nothing selected too. + let item = item_target(s, p, cmd)?; if ids.is_empty() { let def = if stroke { &mut s.paint.stroke } else { &mut s.paint.fill }; let changed = super::colorcmds::map_paint(def, f); @@ -1902,7 +2009,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( s.remember_paint(&shown); return Ok(json!({ "changed": changed as usize })); } - let item = item_target(s, p, cmd)?.of_kind(s, !stroke); + let item = item.of_kind(s, !stroke); // Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has // no row for) is still an error. let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?; diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 525cef316a..bd6609e2f8 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Move Anchors", [], None, - "{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected", + "{dx, dy (a move by 0 changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected", has_selection, move_anchors ), @@ -54,6 +54,15 @@ pub fn specs() -> Vec { has_doc, set_handle ), + cmd!( + "path.moveHandles", + "Move Direction Handles", + [], + None, + "{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; a move by 0, 0 changes only the anchors it makes corners, so a live shape with no such anchor stays live and one with such an anchor becomes a plain path, and with none it changes nothing and records no undo step; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused", + has_doc, + move_handles + ), cmd!( "path.moveAnchor", "Move Anchor Point", @@ -262,6 +271,10 @@ fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result { check_switches(p, &["patterns", "interpolate"], C)?; // An object selected in a symbol instance's art stays where the symbol puts it. super::edit::refuse_symbol_part(s)?; + // A move by 0 changes nothing, and the document and its undo history stay as they are. + if d == Vec2::ZERO { + return ok(); + } let st = s.doc()?; let mut sel = st.selection.clone(); let (held, bends) = if bend { held_segments(&st.doc, &mut sel, d) } else { (false, vec![]) }; @@ -584,6 +597,83 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { ok() } +/// `path.moveHandles`: the listed direction handles move by `(dx, dy)` together, as one undo step. +/// Each anchor with one listed handle places it as `path.setHandle` does; an anchor with both +/// listed moves both and becomes a corner. A move by nothing, with no anchor to make a corner, +/// records no undo step. +fn move_handles(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.moveHandles"; + let list = match p.get("handles") { + None | Some(Value::Null) => return Err(bad(C, "missing handles")), + Some(v) => v.as_array().ok_or_else(|| bad(C, "`handles` must be an array"))?, + }; + if list.is_empty() { + return Err(bad(C, "`handles` is empty")); + } + let d = Vec2::new(f64_req(p, "dx", C)?, f64_req(p, "dy", C)?); + if !(d.x.abs() < 1e9 && d.y.abs() < 1e9) { + return Err(bad(C, "dx and dy must be finite")); + } + let independent = switch_or(p, "independent", false, C)?; + if s.script_running() { + return Err(EngineError::Busy); + } + // Each anchor with the sides of it listed: (incoming, outgoing). + let mut anchors: BTreeMap<(NodeId, usize, usize), (bool, bool)> = BTreeMap::new(); + let doc = &s.doc()?.doc; + for (i, h) in list.iter().enumerate() { + if !h.is_object() { + return Err(bad(C, format!("handles[{i}] must be an object"))); + } + let id = object_param(h, "id", C)?.ok_or_else(|| bad(C, format!("handles[{i}]: missing id")))?; + let si = usize_opt(h, "subpath", C)?.unwrap_or(0); + let ai = index_opt(h, "anchor", C)?.ok_or_else(|| bad(C, format!("handles[{i}]: missing anchor")))?; + let out = match str_param(h, "which") { + Some("out") => true, + Some("in") => false, + _ => return Err(bad(C, format!("handles[{i}]: `which` must be \"in\" or \"out\""))), + }; + let n = doc.node(id).ok_or(EngineError::NoNode(id))?; + let NodeKind::Path { path, .. } = &n.kind else { return Err(bad(C, format!("handles[{i}]: object {id} is not a path"))) }; + if path.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)).is_none() { + return Err(bad(C, format!("handles[{i}]: object {id} has no anchor {ai} in subpath {si}"))); + } + let e = anchors.entry((id, si, ai)).or_default(); + if out { e.1 = true } else { e.0 = true } + } + // A move by nothing changes only the kind of anchors that become corners: those with both + // handles listed, or every listed one with `independent`. + // The other anchors are left out, so a live shape that only they lie on is not expanded. + if d == Vec2::ZERO { + anchors.retain(|&(id, si, ai), &mut (inn, out)| { + (independent || (inn && out)) + && doc + .node(id) + .and_then(|n| n.path_data()) + .and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) + .is_some_and(|a| a.kind != AnchorKind::Corner) + }); + if anchors.is_empty() { + return ok(); + } + } + s.edit("Reshape", |doc, _| { + for (&(id, si, ai), &(inn, out)) in &anchors { + let a = path_mut(doc, id)?.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + if inn && out { + a.kind = AnchorKind::Corner; + a.h_in += d; + a.h_out += d; + } else { + let h = if out { a.h_out } else { a.h_in }; + a.set_handle(out, h + d, independent); + } + } + Ok(()) + })?; + ok() +} + /// `path.setHandle` with `link` (the Anchor Point tool's Alt-drag on a handle): the handle goes to /// (x, y) and the anchor becomes smooth, its other handle turned in line at its own length. A /// retracted other handle is pulled out to the moved handle's length when a segment leaves the @@ -1504,6 +1594,91 @@ fn join_pair(d: &mut Document, (a, sa): (NodeId, usize), (b, sb): (NodeId, usize Ok(compound_or_self(d, a)) } +/// An end of an open subpath of an editable path (not a guide) at `at`: the path, the subpath and +/// whether the end is the subpath's first anchor. In isolation mode (`scope`), only a path inside +/// the isolated node counts. Among several, one in or inside the selection `selected` comes first, +/// then the last in paint order. +pub(super) fn open_end_at(d: &Document, scope: Option, selected: &[NodeId], at: Point) -> Option<(NodeId, usize, bool)> { + let editable = d.editable(); + let mut found: Option<((NodeId, usize, bool), bool)> = None; + d.walk(|n| { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { return }; + if !editable(n.id) { + return; + } + let chain = d.ancestry(n.id).unwrap_or_default(); + if scope.is_some_and(|s| !chain.contains(&s)) { + return; + } + let chosen = chain.iter().any(|id| selected.contains(id)); + for (si, sp) in path.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed) { + let Some((first, last)) = end_points(sp) else { continue }; + let end = if last.distance(at) < 1e-6 { + false + } else if first.distance(at) < 1e-6 { + true + } else { + continue; + }; + if found.is_none_or(|(_, was)| chosen || !was) { + found = Some(((n.id, si, end), chosen)); + } + } + }); + found.map(|(end, _)| end) +} + +/// `sp`, an open subpath whose end (its first anchor when `at_first`) lies on an end of `arc` +/// (its first anchor when `arc_at_start`), with `arc` added there: one subpath running the way +/// `sp` runs. The anchor where they meet is `sp`'s, with its handle on the arc's side taken from +/// the arc. +fn splice(sp: &SubPath, at_first: bool, arc: &SubPath, arc_at_start: bool) -> SubPath { + let mut arc = arc.clone(); + if arc_at_start == at_first { + arc.reverse(); + } + let mut out = sp.clone(); + if at_first { + let meet = arc.anchors.pop(); + if let (Some(meet), Some(first)) = (meet, out.anchors.first_mut()) { + first.h_in = meet.h_in; + } + arc.anchors.extend(out.anchors); + out.anchors = arc.anchors; + } else { + if !arc.anchors.is_empty() { + let meet = arc.anchors.remove(0); + if let Some(last) = out.anchors.last_mut() { + last.h_out = meet.h_out; + } + } + out.anchors.extend(arc.anchors); + } + out +} + +/// The arc `arc` joined to the open path ends `start` (at its first anchor) and `end` (at its +/// last), as [`open_end_at`] gives them, at least one of them. The arc joins the path at `start` +/// first, keeping that path's direction and look, and then, when `end` is an end of another open +/// subpath, that subpath joins it as Join joins two paths; when `end` is the other end of the same +/// subpath, the subpath closes. Returns what to select: the joined path, or its compound path. +pub(super) fn join_arc(d: &mut Document, arc: &SubPath, start: Option<(NodeId, usize, bool)>, end: Option<(NodeId, usize, bool)>) -> Result { + let err = || EngineError::Other("join needs open paths".into()); + let ((id, si, at_first), arc_at_start, rest) = match (start, end) { + (Some(s), e) => (s, true, e), + (None, Some(e)) => (e, false, None), + (None, None) => return Err(err()), + }; + let path = path_mut(d, id)?; + let sp = path.subpaths.get_mut(si).filter(|sp| !sp.closed && !sp.anchors.is_empty()).ok_or_else(err)?; + *sp = splice(sp, at_first, arc, arc_at_start); + match rest { + // The arc's far end is the first anchor of the joined subpath when it was added before it. + Some((other, osi, other_first)) => join_pair(d, (id, si), (other, osi), (at_first, !other_first), None), + None => Ok(compound_or_self(d, id)), + } +} + pub(super) type AnchorTargets = Vec<(NodeId, Vec<(usize, usize)>)>; pub(super) fn anchor_targets(s: &Session) -> Result { diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index d1c86a4f62..58612c744c 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -57,7 +57,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes}; -use vectorcraft_geom::{Affine, Point, Rect, shapes}; +use vectorcraft_geom::{Affine, Homography, Point, Rect, shapes}; use vectorcraft_pdf::CropTo; use super::fileio::{self, Format, RasterImage}; @@ -88,7 +88,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its objects, guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -329,7 +329,7 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o let (sx, sy) = pt_per_px(img.ppi); let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy); let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes)); - let mut warnings: Vec = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect(); + let mut warnings: Vec = unread.into_iter().chain(img.note.clone()).chain(fileio::size_note(&img.blob.bytes)).collect(); *slices_out = psd_slices(slices_from, natural, &mut warnings); let clip = img.clip.clone().map(|(path, _)| path); return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None }); @@ -655,7 +655,7 @@ fn at_param(p: &Value) -> Result> { /// The transform that puts new art with the natural box `natural` where `old` is: an image's scale /// and rotation relative to its 100% size (its resolution's) and its centre are kept (with -/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by +/// `image_xf`), also for an image alone in a clip group when the new art is a raster or DCS image, clipped by /// its file's clipping path or not (`new_image`); other objects keep their centre. fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine { let image = replace_measured(d, old, new_image); @@ -663,7 +663,7 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes))); let full = Affine::scale_non_uniform(sx, sy); let centre = full * Point::new(im.width as f64 / 2.0, im.height as f64 / 2.0); - if im.xf.determinant().abs() > 1e-12 { + if Homography::affine_is_invertible(im.xf) { return im.xf * full.inverse() * Affine::translate(centre - natural.center()); } } @@ -672,8 +672,8 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image } /// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as -/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an -/// image (`new_image`), except a DCS file's plates; else `old` itself. +/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is a +/// raster or DCS image (`new_image`), except a DCS file's plates; else `old` itself. fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node { match &old.kind { NodeKind::Group { children, clip: true } if new_image => match &children[..] { @@ -687,6 +687,60 @@ fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Nod } } +/// What Replace does when the image it measures, `old`, is distorted and the art placed is a +/// raster image or a DCS file's image (`art`): the transform that puts the new pixels on `old`'s +/// transform scaled to their size, as Update Links scales it, the corners the new image takes, and +/// the map from the art's natural box to the page through those corners, which a PSD file's slices +/// follow. `None` for other art, for an image with no pixels, and for corners the new pixels can't +/// fill ([`Node::set_image_corners`]). +fn distorted_replace(old: &Node, art: &Art) -> Option<(Affine, [Point; 4], Homography)> { + let NodeKind::Image(im) = &old.kind else { return None }; + let q = old.image_quad()?; + let (pixels, width, height) = match art { + Art::Image(img, _) => { + let (sx, sy) = pt_per_px(img.ppi); + (Affine::scale_non_uniform(sx, sy), img.width, img.height) + } + Art::Dcs(a) => (a.xf, a.img.width, a.img.height), + _ => return None, + }; + if width == 0 || height == 0 || !Homography::affine_is_invertible(pixels) { + return None; + } + let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(width), f64::from(im.height) / f64::from(height)); + let new = ImageObject { key: String::new(), width, height, xf, link: None, placement: Default::default(), pixels: None }; + let mut probe = Node::new(old.id, NodeKind::Image(Box::new(new))); + probe.set_image_corners(q).ok()?; + let page = probe.image_map()?.checked_then_after(&Homography::from_affine(pixels.inverse()))?; + Some((xf * pixels.inverse(), q, page)) +} + +/// Placed raster `node` (an image, or an image in a clip group of its file's clipping path, as +/// [`build`] makes them) with the image's corners at `q`: the pixels fill them, and the clipping +/// path is drawn through them as the pixels are. `None` when the corners can't hold the image. +fn with_corners(mut node: Node, q: [Point; 4]) -> Option { + match &mut node.kind { + NodeKind::Image(_) => node.set_image_corners(q).ok()?, + NodeKind::Group { children, clip: true } => { + let [path, image] = &mut children[..] else { return None }; + let image = Arc::make_mut(image); + let NodeKind::Image(im) = &image.kind else { return None }; + if !Homography::affine_is_invertible(im.xf) { + return None; + } + // The clipping path in the image's pixels, which its transform placed on the page. + let to_pixels = im.xf.inverse(); + image.set_image_corners(q).ok()?; + let map = image.image_map()?; + let NodeKind::Path { path: p, .. } = &mut Arc::make_mut(path).kind else { return None }; + p.transform(to_pixels); + *p = super::links::warped(p, &map)?; + } + _ => return None, + } + Some(node) +} + /// `rect` fitted with `natural`'s aspect, centred. fn fit(natural: Rect, r: Rect) -> Affine { let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b); @@ -846,19 +900,24 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { loaded.natural = Rect::from_origin_size(Point::ORIGIN, size); } let natural = loaded.natural; - // Replace keeps the transform of the image it measures (`replace_measured`), which a - // distortion's corners do not follow. Type, and any other object it measures, is placed by the - // bounds of what it replaces, so a distorted image there is not refused. + // Replace keeps the transform of the image it measures (`replace_measured`). When that image + // is distorted, a raster placed in its place takes its corners ([`distorted_replace`]); other + // art is refused. Type, and any other object it measures, is placed by the bounds of what it + // replaces, so a distorted image there is not refused. + let mut distorted = None; + let new_image = matches!(loaded.art, Art::Image(..) | Art::Dcs(..)); if let Some(o) = old_node && !is_text { - let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..))); + let image = replace_measured(&st.doc, o, new_image); if image.is_distorted_image() { - return Err(super::xform::distorted_image_error(PLACE, image.id)); + let fit = distorted_replace(image, &loaded.art).ok_or_else(|| super::xform::distorted_image_error(PLACE, image.id))?; + distorted = Some((image.id, fit)); } } let m = match (old_node, rect) { - (Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))), + (Some(_), _) if let Some((_, (m, ..))) = distorted => m, + (Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, new_image), (None, Some(r)) => fit(natural, r), // Its artboard's bottom-left corner on the target's. (None, None) if let (Some(src), Some(to)) = (loaded.board, target) => Affine::translate((to.x0 - src.x0, to.y1 - src.y1)), @@ -867,6 +926,38 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { Affine::translate(c - natural.center()) } }; + let mut retained = natural; + match &loaded.art { + Art::Vector { src, nodes, .. } => { + let symbols = src.symbol_boxes(); + for node in nodes { + node.walk(&mut |node| { + if let Some(bounds) = node.geometric_bounds_with(&symbols) { + retained = retained.union(bounds); + } + }); + } + } + Art::Image(image, _) => { + let (sx, sy) = pt_per_px(image.ppi); + retained = retained.union(Rect::new(0.0, 0.0, f64::from(image.width) * sx, f64::from(image.height) * sy)); + } + Art::Dcs(art) => { + let pixels = Rect::new(0.0, 0.0, f64::from(art.img.width), f64::from(art.img.height)); + retained = retained.union(art.xf.transform_rect_bbox(pixels)); + if let Some(clip) = &art.clip { + clip.walk(&mut |node| { + if let Some(bounds) = node.geometric_bounds() { + retained = retained.union(bounds); + } + }); + } + } + Art::Text(_) | Art::Document(..) => {} + } + if !crate::sanity::rect_in_range(m.transform_rect_bbox(retained)) { + return Err(bad(PLACE, "placed art lies outside the canvas")); + } let parent = st.insertion_parent(); let below = st.current_layer().or_else(|| parent.and_then(|p| st.doc.layer_of(p))); let link = loaded.link.take().filter(|_| bool_or(p, "link", true)); @@ -876,13 +967,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { if let Art::Dcs(a) = &loaded.art { warnings.extend(dcs::swatch_notes(&st.doc, &a.spots)); } - // A PSD file's slices move and scale with its art; one that would leave the canvas is left out. + // A PSD file's slices move and scale with its art, through a distorted image's corners when + // it takes them; one that would leave the canvas is left out. let read_count = read_slices.len(); let slices: Slices = read_slices .into_iter() .filter_map(|(r, o)| { - let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c); - let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c)); + let placed = match distorted { + Some((_, (_, _, page))) => page.map_rect_bbox(r)?, + None => { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c); + corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c)) + } + }; super::slices::slice_rect_ok(placed).then_some((placed, o)) }) .collect(); @@ -892,7 +989,10 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")), } let (id, size, slice_ids) = s.edit("Place", |d, sel| { - let node = transformed(build(d, loaded, link), m); + let mut node = transformed(build(d, loaded, link), m); + if let Some((old_image, (_, q, _))) = distorted { + node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?; + } let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default(); let (into, index) = match old { Some(old) => { diff --git a/crates/engine/src/cmd/place/dcs.rs b/crates/engine/src/cmd/place/dcs.rs index efa02e06a8..0c44e2f946 100644 --- a/crates/engine/src/cmd/place/dcs.rs +++ b/crates/engine/src/cmd/place/dcs.rs @@ -105,7 +105,7 @@ pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result { let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref()) .ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?; let clip = clip.map(|path| (path, vectorcraft_geom::FillRule::NonZero)); - let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip }; + let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip, note: None }; let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect(); Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings }) } diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 1c67f8b656..e890c2b65f 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -111,7 +111,7 @@ pub fn describe(p: &Plugin) -> Value { v["place"] = json!(true); } } - Kind::Filter => {} + Kind::Filter | Kind::Generator => {} } if m.budget == Budget::Heavy { v["budget"] = json!("heavy"); @@ -119,6 +119,9 @@ pub fn describe(p: &Plugin) -> Value { if !m.inputs.is_empty() { v["inputs"] = json!(m.inputs); } + if !m.output_kinds.is_empty() { + v["outputKinds"] = json!(m.output_kinds); + } if !m.writes.is_empty() { v["writes"] = json!(m.writes); } @@ -156,6 +159,9 @@ pub fn describe(p: &Plugin) -> Value { } entry["menu"] = menu; } + if !c.context.is_empty() { + entry["menu"]["context"] = json!(c.context); + } entry }) .collect(); @@ -274,6 +280,9 @@ impl FilterRun { format!("`{}` is an importer: open a file with document.open {{\"importer\": \"{}\"}}", m.id, export::format_id(&m.id)), )); } + Kind::Generator => { + return Err(bad(C, format!("`{}` is a generator: draw its art with plugin.generate {{\"id\": \"{}\"}}", m.id, m.id))); + } } Self::prepare_with(s, plugin, None, C, p) } @@ -2402,7 +2411,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), outputKinds?: [\"type\"|\"image\"|\"layer\"|\"artboard\"] (what an importer at API level 4 returns besides paths, see docs/plugins.md), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 4), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 3d49db0f2a..612cf436b7 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -154,6 +154,7 @@ pub(super) const ALLOWED: &[&str] = &[ "color.convert", "color.gamutCheck", "color.harmony", + "color.parse", "color.plates", "color.used", "dataset.capture", @@ -473,6 +474,7 @@ pub(super) const ALLOWED: &[&str] = &[ "path.mirrorCut", "path.moveAnchor", "path.moveAnchors", + "path.moveHandles", "path.quickPen", "path.quickPenLength", "path.rectCut", @@ -545,6 +547,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.object.strayPoints", "select.object.textObjects", "select.recall", + "select.remove", "select.reselect", "select.same.appearance", "select.same.appearanceAttribute", @@ -679,6 +682,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.thread.info", "text.thread.releaseSelection", "text.thread.remove", + "text.thread.setNeighbor", "text.touchType", "threeD.addGraphic", "threeD.mapArt", diff --git a/crates/engine/src/cmd/plugin_generated.rs b/crates/engine/src/cmd/plugin_generated.rs new file mode 100644 index 0000000000..83ef85decc --- /dev/null +++ b/crates/engine/src/cmd/plugin_generated.rs @@ -0,0 +1,275 @@ +//! Generated art objects: art a generator plug-in draws from its parameters alone +//! ([`vectorcraft_plugins::generate`]), kept in a group with the parameters it was drawn with +//! ([`vectorcraft_doc::generated`]). +//! +//! `plugin.generate` runs a generator and adds its art as a new generated art object, one undo +//! step. `plugin.editGenerated` runs the object's generator again with changed parameters and +//! replaces the art, one undo step (none when nothing changes), placed as the object has been +//! moved, scaled, rotated, reflected or sheared since it was drawn. Object › Expand makes it an +//! ordinary group of its art. `plugin.generatedInfo` describes one. +//! +//! The plug-in runs only when one of these commands asks it to, with its own permissions and budget: +//! opening, placing, pasting, drawing and exporting a document never run it. A generated art object +//! whose plug-in isn't installed, whose saved fields are damaged, or whose art doesn't match the hash +//! its file gave keeps its art as it is, and opening the file says so ([`open_notes`]). + +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::generated::{GeneratedArt, MAX_ART_BYTES, State, art_bytes}; +use vectorcraft_doc::{Document, Node, NodeId}; +use vectorcraft_plugins::objects::{self, OutObject}; +use vectorcraft_plugins::permissions::{self, display_text}; +use vectorcraft_plugins::{Plugin, generate, registry}; + +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, str_param}; + +const GENERATE: &str = "plugin.generate"; +const EDIT: &str = "plugin.editGenerated"; +const INFO: &str = "plugin.generatedInfo"; + +/// The undo step of `plugin.editGenerated`. +pub const EDIT_LABEL: &str = "Edit Generated Art"; + +/// What a plug-in error looks like to the user. A run the caller cancelled changed nothing. +fn err(e: vectorcraft_plugins::Error) -> EngineError { + match e { + vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled, + e => EngineError::Other(e.to_string()), + } +} + +/// The error of a plug-in's bad parameters for command `c`, others as [`err`] gives them. +fn params_err(c: &str) -> impl Fn(vectorcraft_plugins::Error) -> EngineError + '_ { + move |e| match e { + vectorcraft_plugins::Error::Params(why) => bad(c, why), + e => err(e), + } +} + +/// The limits a generator runs under: its own, with the Plug-in Instruction Budget in force. +fn limits(s: &Session, plugin: &Plugin) -> vectorcraft_plugins::Limits { + match s.prefs.plugin_instruction_budget { + crate::PluginBudget::Normal => plugin.limits().clone(), + crate::PluginBudget::Large => plugin.large_limits(), + } +} + +/// The plug-in of generated art `g` as a message shows it: its name (its id when it has none) and +/// its id, each as a prompt shows a manifest string. +fn shown(g: &GeneratedArt) -> (String, String) { + let id = display_text(&g.plugin, permissions::MAX_SHOWN_FIELD); + let name = if g.name.trim().is_empty() { id.clone() } else { display_text(g.name.trim(), permissions::MAX_SHOWN_NAME) }; + (name, id) +} + +/// Generated art whose plug-in, by its saved id, isn't installed. +fn not_installed(g: &GeneratedArt) -> String { + let (name, id) = shown(g); + format!("“{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is") +} + +/// Generated art whose saved fields can't be read. +const DAMAGED: &str = "a generated art object's plug-in id or parameters are damaged, so its art can't be drawn again: the art stays as it is"; + +/// Generated art that doesn't match the hash its file gave. +fn changed(g: &GeneratedArt) -> String { + let (name, id) = shown(g); + format!("the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is") +} + +/// What opening `doc` says about its generated art objects, each note once: those whose plug-in +/// isn't installed or is installed as a plug-in of another kind, those whose saved fields are +/// damaged, and those whose art doesn't match its file's hash. Opening runs no plug-in. +pub fn open_notes(doc: &Document) -> Vec { + let mut notes: Vec = vec![]; + let mut visit = |n: &Node| { + let Some(g) = n.extras().generated.as_deref() else { return }; + let note = match g.state { + State::Damaged => DAMAGED.to_string(), + state => match generate::named(&g.plugin) { + Err(vectorcraft_plugins::Error::NotFound(_)) => not_installed(g), + Err(e) => e.to_string(), + Ok(_) if state == State::Changed => changed(g), + Ok(_) => return, + }, + }; + if !notes.contains(¬e) { + notes.push(note); + } + }; + for layer in &doc.layers { + vectorcraft_doc::swatches::walk_with_masks(layer, &mut visit); + } + for symbol in &doc.symbols { + vectorcraft_doc::swatches::walk_with_masks(&symbol.art, &mut visit); + } + for pattern in &doc.patterns { + for art in &pattern.art { + vectorcraft_doc::swatches::walk_with_masks(art, &mut visit); + } + } + for design in &doc.graph_designs { + vectorcraft_doc::swatches::walk_with_masks(&design.art, &mut visit); + } + notes +} + +/// Draws the art `out` in generated art object `gid`, in place of the art it holds, placed as +/// `settings` says its art has been transformed ([`GeneratedArt::place`]). The objects go through a +/// filter's checks; art past [`MAX_ART_BYTES`] is refused. +fn draw(d: &mut Document, gid: NodeId, out: Vec, settings: &GeneratedArt) -> Result<()> { + if let Some(ch) = d.node_mut(gid).and_then(Node::children_mut) { + ch.clear(); + } + let admit = |fx: &[vectorcraft_doc::Effect], n: &Node| super::plugin::admit_effects_for(GENERATE, fx, n); + let ids = objects::apply_output(d, &[], out, Some(gid), &admit).map_err(err)?; + let g = d.node_mut(gid).ok_or(EngineError::NoNode(gid))?; + if let Some(ch) = g.children_mut() { + for c in ch.iter_mut() { + settings.place(Arc::make_mut(c), vectorcraft_render::effects::scale_effect); + } + } + if art_bytes(g.children().map_or(&[][..], Vec::as_slice)) > MAX_ART_BYTES { + return Err(err(vectorcraft_plugins::Error::Output(format!( + "the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps" + )))); + } + if !super::super::sanity::objects_in_range(d, &ids) { + return Err(EngineError::Other("result would exceed the canvas (coordinates out of range)".into())); + } + Ok(()) +} + +/// `plugin.generate {id, params?}`: runs generator `id` with its parameters (checked first: missing +/// ones take their defaults) and adds its art as a new generated art object in the current layer, +/// selected, as one undo step named after the plug-in → `{id, plugin}`. +fn generate_art(s: &mut Session, p: &Value) -> Result { + let id = str_param(p, "id").ok_or_else(|| bad(GENERATE, "missing `id` (see plugin.list)"))?; + let plugin = generate::named(id).map_err(params_err(GENERATE))?; + let given = p.get("params").cloned().unwrap_or(Value::Null); + let params = generate::resolve(&plugin, &given).map_err(params_err(GENERATE))?; + let parent = s.doc()?.target_parent()?; + let out = generate::run(&plugin, ¶ms, &limits(s, &plugin)).map_err(err)?; + let m = plugin.manifest(); + let label = m.name.trim_end_matches('…').to_string(); + let gid = s.edit(&label, |d, sel| { + let gid = d.alloc_id(); + let mut g = Node::group(gid, vec![]); + g.name = Some(m.name.trim_end_matches('…').to_string()); + let settings = GeneratedArt::new(&m.id, &m.name, params); + g.extras_mut().generated = Some(Box::new(settings.clone())); + d.insert(parent, usize::MAX, g)?; + draw(d, gid, out, &settings)?; + sel.set([gid]); + Ok(gid) + })?; + Ok(json!({"id": gid.0, "plugin": m.id})) +} + +/// The generated art object `p` names (`id`), else the one selected → its id and settings. A +/// locked or hidden one, and a selection that holds none or more than one, are errors. +fn target(s: &Session, c: &str, p: &Value) -> Result<(NodeId, GeneratedArt)> { + let st = s.doc()?; + let one = |id: NodeId| st.doc.node(id).and_then(|n| n.extras().generated.as_deref().cloned()).map(|g| (id, g)); + let found = match super::given_objects(s, p, c)? { + Some(ids) if ids.len() == 1 => one(ids[0]), + Some(_) => None, + None => match st.selection.objects.as_slice() { + [id] => one(*id), + _ => None, + }, + }; + let select = || bad(c, "select one generated art object"); + let (id, g) = found.ok_or_else(select)?; + if !st.doc.is_editable(id) { + return Err(select()); + } + Ok((id, g)) +} + +/// The installed generator of generated art `g`, which must be able to draw it again. +fn generator_of(c: &str, g: &GeneratedArt) -> Result> { + if g.state == State::Damaged { + return Err(bad(c, DAMAGED)); + } + match registry::get(&g.plugin) { + None => Err(bad(c, not_installed(g))), + Some(_) => generate::named(&g.plugin).map_err(params_err(c)), + } +} + +/// `plugin.editGenerated {id?, params}`: runs the generator of generated art object `id` (else the +/// selected one) again with its saved parameters changed by `params` (checked against the plug-in's +/// manifest; saved ones it no longer declares are left out) and replaces its art, placed as the +/// object has been transformed since it was drawn, as one undo step. Parameters that change nothing +/// run nothing and make no undo step → `{id, plugin, changed}`. +fn edit_generated(s: &mut Session, p: &Value) -> Result { + let (id, g) = target(s, EDIT, p)?; + let plugin = generator_of(EDIT, &g)?; + let m = plugin.manifest(); + let given = match p.get("params") { + None | Some(Value::Null) => Value::Object(Map::new()), + Some(v @ Value::Object(_)) => v.clone(), + Some(_) => return Err(bad(EDIT, "`params` must be an object")), + }; + let params = generate::resolve_over(&plugin, &g.params, &given).map_err(params_err(EDIT))?; + if params == g.params { + return Ok(json!({"id": id.0, "plugin": g.plugin, "changed": false})); + } + let out = generate::run(&plugin, ¶ms, &limits(s, &plugin)).map_err(err)?; + let settings = GeneratedArt { params, state: State::Intact, name: m.name.chars().take(vectorcraft_doc::generated::MAX_NAME).collect(), ..g }; + s.edit(EDIT_LABEL, |d, _| { + draw(d, id, out, &settings)?; + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + n.extras_mut().generated = Some(Box::new(settings)); + Ok(()) + })?; + Ok(json!({"id": id.0, "plugin": m.id, "changed": true})) +} + +/// `plugin.generatedInfo {id?}`: generated art object `id` (else the selected one) → `{id, plugin, +/// name, params, state, installed}`. +fn info(s: &mut Session, p: &Value) -> Result { + let (id, g) = target(s, INFO, p)?; + let state = match g.state { + State::Intact => "intact", + State::Damaged => "damaged", + State::Changed => "changed", + }; + let installed = g.state != State::Damaged && generate::named(&g.plugin).is_ok(); + Ok(json!({"id": id.0, "plugin": g.plugin, "name": g.name, "params": g.params, "state": state, "installed": installed})) +} + +/// This module's commands: `plugin.generate`, `plugin.editGenerated` and `plugin.generatedInfo`. +pub fn specs() -> Vec { + vec![ + cmd!( + "plugin.generate", + "Generate Art", + [], + None, + "{id: a generator plug-in (plugin.list kind \"generator\"), params?: {…} (its parameters; missing ones take their defaults, see plugin.info; a bad one is an error)} run the generator and add its art to the current layer as a new generated art object (a group that keeps the plug-in's id and name and the parameters, at most 64 KiB of JSON), selected, as one undo step named after the plug-in; its objects go through a filter's checks and the art may take at most 16 MiB of JSON. Edit it with plugin.editGenerated; Object › Expand makes it an ordinary group → {id, plugin}", + has_doc, + generate_art + ), + cmd!( + "plugin.editGenerated", + "Edit Generated Art", + [], + None, + "{id?: a generated art object (default: the one selected), params: {…} (the parameters to change; the others keep their saved values)} run the object's generator again and replace its art, placed as the object has been moved, scaled, rotated, reflected or sheared since it was drawn, as one undo step; parameters that change nothing run nothing and make no undo step. An object whose plug-in isn't installed, or whose saved plug-in id, parameters, transforms or scales are damaged, is an error, and its art stays as it is (Object › Expand keeps it as ordinary art) → {id, plugin, changed}", + has_doc, + edit_generated + ), + cmd!( + query "plugin.generatedInfo", + "Generated Art Info", + [], + None, + "{id?: a generated art object (default: the one selected)} → {id, plugin (its generator's id), name (the generator's name when it drew the art), params, state: \"intact\" | \"damaged\" (its saved plug-in id, parameters, transforms or scales can't be read: it can't be drawn again) | \"changed\" (its art doesn't match the hash its file gave), installed (its generator is installed)}", + has_doc, + info + ), + ] +} diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b3bd2f1298..194df59e51 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -195,6 +195,7 @@ fn prepare(s: &Session, p: &Value) -> Result { if s.script_frames && !answers.is_empty() { return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog")); } + let actions = script::actions::parse(p.get("actions")).map_err(param)?; let fuel = max_fuel(p)?; let installed = switch_or(p, "installed", false, "script.run")?; let mut checked_real = None; @@ -241,6 +242,7 @@ fn prepare(s: &Session, p: &Value) -> Result { fuel, locale, answers, + actions, }) } @@ -442,6 +444,7 @@ impl Session { fuel, locale, answers: vec![], + actions: vec![], }; let runs = self.script_runs; self.script_start(request).map_err(|e| { diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index b7a6043a98..eb504b6074 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -77,6 +77,15 @@ pub fn specs() -> Vec { has_doc, toggle ), + cmd!( + "select.remove", + "Remove from Selection", + [], + None, + "{id} or {ids: [id…]}: each one leaves the selection; one inside a selected group or compound path (Direct Selection's Shift-click on it) leaves it too, and the rest of that group stays selected: the outermost selected object around it gives way to the objects inside it on the way down, leaving out hidden and locked objects; an id that is neither selected nor inside a selected object is left alone; all ids must be non-negative integers naming existing objects → {count, ids} (resulting selection)", + has_doc, + remove + ), cmd!( "select.key", "Cancel Key Object", @@ -556,6 +565,25 @@ fn toggle(s: &mut Session, p: &Value) -> Result { selection_result(s) } +fn remove(s: &mut Session, p: &Value) -> Result { + const C: &str = "select.remove"; + let ids = if p.get("ids").is_some() { + checked_ids_param(s, p, "ids", C)? + } else { + let value = p.get("id").ok_or_else(|| bad(C, "missing id or ids"))?; + vec![checked_id(s, value, C)?] + }; + s.select(|d, sel| { + for id in ids { + sel.expand_to(d, id); + if sel.contains(id) { + sel.remove(id); + } + } + })?; + selection_result(s) +} + fn selection_result(s: &Session) -> Result { let selection = &s.doc()?.selection; Ok(json!({ "count": selection.len(), "ids": selection.objects })) @@ -930,7 +958,15 @@ fn anchors(s: &mut Session, p: &Value) -> Result { } // A path selected as a whole has every anchor selected: toggle and add start from them all, // but only when no partial anchor selection is active and only on a single isolated object. - let whole = sel.contains(id) && sel.partial(id).is_none() && sel.anchors.is_empty() && sel.objects.len() <= 1; + // A toggle on a path inside a selected group selects the path itself in the group's place, + // beside the group's other objects, and starts from all its anchors. A toggle on a group + // member that is itself selected whole (as an earlier toggle in the group leaves the other + // members) starts from all its anchors whatever else is selected. + let toggle = mode == "toggle"; + let inside = toggle && sel.expand_to(d, id); + let own = sel.contains(id) && sel.partial(id).is_none(); + let in_group = || d.ancestry(id).is_some_and(|c| c.len() >= 2 && d.node(c[c.len() - 2]).is_some_and(|n| !n.is_layer())); + let whole = inside || (own && ((sel.anchors.is_empty() && sel.objects.len() <= 1) || (toggle && in_group()))); sel.add(id); // A segment pick's endpoints aren't selected anchors: start from none of them. if sel.segments.remove(&id).is_some() { diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index bf2ffad073..e1d64b2112 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index b632dbd3ba..47eccccba9 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -148,8 +148,11 @@ macro_rules! style_cmds { }; } +/// The largest document `charStyle.load`, `paraStyle.load` and `textStyle.loadAll` read, in bytes. +pub const MAX_LOAD_BYTES: usize = 64 << 20; + /// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`. -const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; +const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats; at most 64 MB) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; pub fn specs() -> Vec { let mut v = style_cmds!( @@ -163,7 +166,7 @@ pub fn specs() -> Vec { "charStyle.edit", "Edit Character Style", &[], - "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings", + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; [Normal Character Style] takes only `to` equal to `name`; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings", |s, p| edit_style(s, p, Kind::Char), true, )); @@ -178,7 +181,7 @@ pub fn specs() -> Vec { "paraStyle.edit", "Edit Paragraph Style", &[], - "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position", + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; [Normal Paragraph Style] takes only `to` equal to `name`; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position", |s, p| edit_style(s, p, Kind::Para), true, )); @@ -1018,8 +1021,9 @@ fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result { let d = &s.doc()?.doc; let old = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?; 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"))); + // The Normal style takes new attributes but keeps its name. + if name == kind.normal() && to != name { + return Err(bad(&c, format!("`{name}` can't be renamed"))); } if to.is_empty() { return Err(bad(&c, "give the style a name")); @@ -1031,9 +1035,13 @@ fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result { return ok(); } s.edit(if kind == Kind::Char { "Character Style Options" } else { "Paragraph Style Options" }, |d, _| { - if let Some(def) = kind.defs_mut(d).iter_mut().find(|def| def.name == name) { - def.name = to.clone(); - def.attrs = attrs.clone(); + // A Normal style that was never redefined has no definition yet. + match kind.defs_mut(d).iter_mut().find(|def| def.name == name) { + Some(def) => { + def.name = to.clone(); + def.attrs = attrs.clone(); + } + None => kind.defs_mut(d).push(TextStyleDef { name: to.clone(), attrs: attrs.clone() }), } update_users(d, kind, &name, &old, &attrs)?; if to != name { @@ -1217,12 +1225,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result { _ => "textStyle.loadAll".to_string(), }; let path = str_param(p, "path"); - let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { - (Some(path), ..) => super::fileio::read_file(path)?, - (None, Some(text), _) => text.as_bytes().to_vec(), - (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?, + let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20)); + let bytes: std::borrow::Cow<[u8]> = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { + (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?.into(), + (None, Some(text), _) => text.as_bytes().into(), + (None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()), + (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?.into(), _ => return Err(bad(c, "give `path`, `data` or `dataBase64`")), }; + if bytes.len() > MAX_LOAD_BYTES { + return Err(too_large()); + } let file = str_param(p, "name").or(path).unwrap_or("Styles"); let src = super::fileio::load(file, &bytes).map_err(|e| bad(c, e.to_string()))?; if src.preview_only { diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 49e50ca14c..fffd80f2c5 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -37,6 +37,48 @@ fn character_style_attributes_refuse_a_glyph_choice() { assert!(err.to_string().contains("glyphAlternate"), "{err}"); } +/// `charStyle.edit` and `paraStyle.edit` give a Normal style that was never redefined its first definition, in one +/// undo step: the type set in it takes the new attributes and keeps its overrides. The Normal style keeps its name, +/// and an edit that changes nothing records no undo step. +#[test] +fn style_options_edit_defines_a_normal_style_in_one_undo_step() { + let (mut s, id) = session_with_text("One\nTwo"); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 7, "size": 30.0})).unwrap(); + s.execute("text.setFormat", &json!({"id": id, "start": 4, "end": 4, "leftIndent": 20.0})).unwrap(); + for (command, normal, attrs) in [ + ("charStyle.edit", NORMAL_CHAR, json!({"size": 18.0, "tracking": 40.0})), + ("paraStyle.edit", NORMAL_PARA, json!({"left_indent": 12.0, "space_before": 6.0})), + ] { + assert!(Kind::Char.defs(&s.doc().unwrap().doc).iter().chain(Kind::Para.defs(&s.doc().unwrap().doc)).all(|d| d.name != normal)); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute(command, &json!({"name": normal, "to": normal, "attrs": attrs})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{command}: one undo step"); + let d = &s.doc().unwrap().doc; + let defs = if command == "charStyle.edit" { &d.char_styles } else { &d.para_styles }; + assert_eq!(defs.iter().find(|def| def.name == normal).map(|def| json!(def.attrs)), Some(attrs.clone()), "{command}: the definition"); + let changed = s.doc().unwrap().doc.clone(); + s.execute(command, &json!({"name": normal, "to": normal, "attrs": attrs})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{command}: the same attributes record nothing"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before, "{command}: undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, changed, "{command}: redo"); + } + let r = runs(&s, id); + assert_eq!( + r.iter().map(|r| (r.style.style_name.as_deref(), r.style.size, r.style.tracking)).collect::>(), + [(None, 18.0, 40.0), (None, 30.0, 40.0)], + "the type in Normal takes the new size and tracking and keeps its own size" + ); + let p = paras(&s, id); + assert_eq!( + p.iter().map(|p| (p.style_name.as_deref(), p.left_indent, p.space_before)).collect::>(), + [(None, 12.0, 6.0), (None, 20.0, 6.0)], + "the paragraphs in Normal take the new indent and space and keep their own indent" + ); +} + fn session_with_text(text: &str) -> (Session, u64) { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); @@ -557,7 +599,7 @@ fn character_style_options_edit_validates_names_and_allows_case_changes() { s.execute("charStyle.new", &json!({"name":"Body","attrs":{"size":24.0}})).unwrap(); s.execute("charStyle.new", &json!({"name":"Other","attrs":{}})).unwrap(); for (name, to, message) in - [(super::NORMAL_CHAR, "New", "can't be edited this way"), ("Body", " ", "give the style a name"), ("Body", "Other", "already exists")] + [(super::NORMAL_CHAR, "New", "can't be renamed"), ("Body", " ", "give the style a name"), ("Body", "Other", "already exists")] { let error = s.execute("charStyle.edit", &json!({"name":name,"to":to,"attrs":{}})).unwrap_err().to_string(); assert!(error.contains(message), "{error}"); @@ -854,6 +896,27 @@ fn load_all_styles_loads_both_kinds_in_one_step() { assert_eq!(s.doc().unwrap().doc, before); } +/// A file or `dataBase64` larger than 64 MB loads nothing and is not read past the limit. +#[test] +fn loading_refuses_a_file_larger_than_64_mb() { + let (mut s, _) = session_with_text("Title"); + let dir = std::env::temp_dir().join(format!("vc-load-styles-big-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Big.vectorcraft"); + std::fs::File::create(&path).unwrap().set_len(MAX_LOAD_BYTES as u64 + 1).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let r = s.execute("charStyle.load", &json!({"path": path.to_string_lossy()})); + std::fs::remove_dir_all(&dir).ok(); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8); + let r = s.execute("paraStyle.load", &json!({"dataBase64": b64})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + let text = " ".repeat(MAX_LOAD_BYTES + 1); + let r = s.execute("textStyle.loadAll", &json!({"data": text})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + assert_eq!(s.doc().unwrap().doc, before); +} + /// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or /// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped. #[test] @@ -1672,13 +1735,13 @@ fn paragraph_style_options_edit_applies_to_users_and_is_one_saved_undo_step() { assert_eq!(s.doc().unwrap().doc, before); s.execute("edit.redo", &json!({})).unwrap(); assert_eq!(s.doc().unwrap().doc, changed); - // The Normal style, an empty or a taken name and an unknown style are errors. + // Renaming the Normal style, an empty or a taken name and an unknown style are errors. s.execute("paraStyle.new", &json!({"name": "Other"})).unwrap(); for (params, why) in [ (json!({"name": "Text", "to": " ", "attrs": {}}), "give the style a name"), (json!({"name": "Text", "to": "Other", "attrs": {}}), "already exists"), (json!({"name": "Missing", "to": "Missing", "attrs": {}}), "no style `Missing`"), - (json!({"name": NORMAL_PARA, "to": NORMAL_PARA, "attrs": {}}), "can't be edited"), + (json!({"name": NORMAL_PARA, "to": "Basic", "attrs": {}}), "can't be renamed"), ] { let error = s.execute("paraStyle.edit", ¶ms).unwrap_err().to_string(); assert!(error.contains(why), "{params}: {error}"); diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index f4f807cb15..1a79fbfbc9 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -59,6 +59,15 @@ pub fn specs() -> Vec { has_doc, break_thread ), + cmd!( + "text.thread.setNeighbor", + "Thread Text", + [], + None, + "{id, side: \"next\"|\"previous\", neighbor: id|null} link area type or type on a path `id` to the frame that follows it (`next`) or comes before it (`previous`) in its story, or with null break that one link, as a script's `nextFrame` and `previousFrame` assignments do. Linking joins two stories: `id` must be the last frame of its story for `next` (the first for `previous`) and `neighbor` the first (the last) of another one, and the second story's text flows on after the first's. Breaking a link makes each side of it a story of its own: no text moves across the break, and the frames after it flow their own text again from their first frame, which now starts a paragraph. An error, with nothing changed, for point type or other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a frame of either story that is hidden or locked; a link that is already there, or a break where there is no link, changes nothing and records no undo step; the selection is kept → {changed: bool, threads: [[id…]] (the stories of the frames involved, after the change, a one-frame story as [id])}", + has_doc, + set_neighbor + ), cmd!(query "text.thread.info", "Threads", [], None, "{} → [[id…]] every thread in order", has_doc, |s, _| { Ok(json!(s.doc()?.doc.text_threads.iter().map(|t| t.iter().map(|i| i.0).collect::>()).collect::>())) }), @@ -986,5 +995,111 @@ fn break_thread(s: &mut Session, p: &Value) -> Result { ok() } +/// The frames of the story `id` is a frame of, in thread order: its thread's area type and type on +/// a path, each once, or `id` alone when it is in no thread. +fn chain_of(d: &Document, id: NodeId) -> Vec { + let mut frames = story_of(d, id); + let mut seen = Ids::default(); + frames.retain(|f| seen.insert(*f)); + if frames.len() < 2 { vec![id] } else { frames } +} + +fn chain_ids(chains: &[&[NodeId]]) -> Value { + json!(chains.iter().filter(|c| !c.is_empty()).map(|c| c.iter().map(|i| i.0).collect::>()).collect::>()) +} + +/// `text.thread.setNeighbor`: link a frame to the frame after or before it, or break that link. +fn set_neighbor(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.thread.setNeighbor"; + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?; + let next = match p.get("side").and_then(Value::as_str) { + Some("next") => true, + Some("previous") => false, + _ => return Err(bad(C, "`side` must be \"next\" or \"previous\"")), + }; + let neighbor = match p.get("neighbor") { + None => return Err(bad(C, "missing `neighbor` (an id, or null to break the link)")), + Some(Value::Null) => None, + Some(v) => Some(checked_id(s, v, C)?), + }; + let d = &s.doc()?.doc; + if text_of(d, id).is_none() { + return Err(bad(C, "`id` must be area type or type on a path")); + } + let locked = |frames: &[NodeId]| { + let editable = d.editable(); + frames.iter().any(|f| !editable(*f)) + }; + let chain = chain_of(d, id); + let Some(n) = neighbor else { + // Break the link on that side: the frames before it and the frames after it. + let i = chain.iter().position(|f| *f == id).unwrap_or(0); + let at = if next { i + 1 } else { i }; + if at == 0 || at >= chain.len() { + return Ok(json!({"changed": false, "threads": chain_ids(&[&chain])})); + } + if locked(&chain) { + return Err(bad(C, "a frame of the story is hidden or locked")); + } + let (head, tail) = (chain[..at].to_vec(), chain[at..].to_vec()); + let cut: Ids = chain.iter().copied().collect(); + s.edit("Break Thread", |d, _| { + d.text_threads.retain(|t| !t.iter().any(|f| cut.contains(f))); + for part in [&head, &tail] { + if part.len() >= 2 { + d.text_threads.push(part.clone()); + } + } + // The first frame after the break starts its story, which flows again on this edit so + // that its numbered paragraphs count from 1. + if let Some(f) = tail.first() { + touch(d, *f); + } + if let Some(NodeKind::Text(t)) = tail.first().and_then(|f| d.node_mut(*f)).map(|n| &mut n.kind) + && t.first_para_continues + { + t.first_para_continues = false; + refresh_bounds(t); + } + Ok(()) + })?; + return Ok(json!({"changed": true, "threads": chain_ids(&[&head, &tail])})); + }; + if n == id { + return Err(bad(C, "a frame cannot be linked to itself")); + } + if text_of(d, n).is_none() { + return Err(bad(C, "`neighbor` must be area type or type on a path")); + } + // `first` is to flow into `second`. + let (first, second) = if next { (id, n) } else { (n, id) }; + let (a, b) = if next { (chain, chain_of(d, n)) } else { (chain_of(d, n), chain) }; + if a.contains(&second) { + if a.windows(2).any(|w| w == [first, second]) { + return Ok(json!({"changed": false, "threads": chain_ids(&[&a])})); + } + return Err(bad(C, "the two frames are already in one story: the link would make a loop or reorder it")); + } + if a.last() != Some(&first) { + return Err(bad(C, format!("frame {} already has a next frame: break that link first", first.0))); + } + if b.first() != Some(&second) { + return Err(bad(C, format!("frame {} already has a previous frame: break that link first", second.0))); + } + if locked(&a) || locked(&b) { + return Err(bad(C, "a frame of either story is hidden or locked")); + } + let joined: Vec = a.iter().chain(&b).copied().collect(); + let affected: Ids = joined.iter().copied().collect(); + s.edit("Thread Text", |d, _| { + d.text_threads.retain(|t| !t.iter().any(|f| affected.contains(f))); + d.text_threads.push(joined.clone()); + // Force a re-flow of the joined story on this edit. + touch(d, first); + Ok(()) + })?; + Ok(json!({"changed": true, "threads": chain_ids(&[&joined])})) +} + #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index f12df3f229..7b71a20a3a 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -4,8 +4,9 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling}; -use vectorcraft_geom::{Affine, Point, Rect, Vec2}; +use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling, SymbolBoxes}; +use vectorcraft_geom::{Affine, Homography, Point, Rect, Vec2}; +use vectorcraft_tools::distort::project_node; use super::edit::{outermost, selected_roots}; use super::{ @@ -21,7 +22,7 @@ pub fn specs() -> Vec { "Free Distort", [], None, - "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step", + "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); the corners of a type object's or symbol instance's box go exactly where the warp takes them too, and it stays type or an instance, drawn through the warp after any projection it had (the same errors, naming the object); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step", has_doc, distort ), @@ -105,6 +106,21 @@ impl Projective { Point::new((a * u + b * v + c) / w, (d * u + e * v + f) / w) } + /// Whether the warp is a perspective map rather than an affine one. + fn is_projective(&self) -> bool { + let [.., g, h] = self.m; + g != 0.0 || h != 0.0 + } + + /// The warp as one page-to-page map, which [`Self::apply`] matches in front of the horizon. + fn homography(&self) -> Homography { + let [a, b, c, d, e, f, g, h] = self.m; + let scale = |len: f64| if len.abs() > 1e-12 { 1.0 / len } else { 0.0 }; + let (sx, sy) = (scale(self.src.width()), scale(self.src.height())); + let to_unit = Affine::new([sx, 0.0, 0.0, sy, -self.src.x0 * sx, -self.src.y0 * sy]) * self.pre; + Homography([[a, b, c], [d, e, f], [g, h, 1.0]]).then_after(&Homography::from_affine(to_unit)) + } + /// Affine approximation at a point (for objects that can't be warped: text, images, symbols). fn affine_near(&self, p: Point) -> Affine { let eps = 1.0; @@ -127,6 +143,8 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option { n.pin_gradients(); // The children before these are left out of a group's or compound path's bounds. let skip = n.children().map_or(0, Vec::len) - n.editing_children().len(); + // Type and symbol instances drawn through the warp keep their gradients in their own art. + let mut projected = false; let before = match &mut n.kind { NodeKind::Path { path, live, .. } => { let b = path.bounds(); @@ -156,6 +174,15 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option { } b } + // Type and symbol instances keep their art and are drawn through the warp, after the + // projection they had ([`project_node`]), so the corners of their box follow it exactly; + // [`distort`] has checked that the projection stays finite and their corners in front of + // the horizon. + NodeKind::Text(_) | NodeKind::SymbolInstance { .. } if pr.is_projective() => { + let b = n.geometric_bounds(); + projected = project_node(n, &pr.homography()); + b + } _ => { // No editable points: the affine approximation (which maps the gradients too). let b = n.geometric_bounds(); @@ -171,7 +198,9 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option { if let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) { warp_node(Arc::make_mut(&mut m.art), pr); } - n.appearance.warp_gradients(&|p| pr.affine_near(p)); + if !projected { + n.appearance.warp_gradients(&|p| pr.affine_near(p)); + } before } @@ -199,17 +228,19 @@ fn warp_children(children: &mut [Arc], pr: &Projective, counts: impl Fn(us }) } -/// The first image in `n` (its children and the art of linked opacity masks, as [`warp_node`] -/// reaches them) whose corners `pr` would fold, collapse or carry past the warp's horizon, with -/// why. -fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeId, Unwarpable)> { +/// The first image, type object or symbol instance in `n` (its children and the art of linked +/// opacity masks, as [`warp_node`] reaches them) whose corners `pr` would fold, collapse or carry +/// past the warp's horizon, or type being edited flat, with why. `symbols` measures the boxes of +/// symbol instances. +fn unwarpable(n: &Node, pr: &Projective, symbols: &SymbolBoxes) -> Option<(vectorcraft_doc::NodeId, Cornered, Unwarpable)> { if let (Some(q), NodeKind::Image(im)) = (n.image_corners(), &n.kind) { if !q.iter().all(|p| pr.in_front(*p)) { - return Some((n.id, Unwarpable::Horizon)); + return Some((n.id, Cornered::Image, Unwarpable::Horizon)); } if let Err(e) = vectorcraft_doc::image_quad::check_for(im, &q.map(|p| pr.apply(p))) { return Some(( n.id, + Cornered::Image, match e { vectorcraft_doc::image_quad::QuadError::NotFinite | vectorcraft_doc::image_quad::QuadError::NotConvex => Unwarpable::NotConvex, vectorcraft_doc::image_quad::QuadError::TooNarrow => Unwarpable::TooNarrow, @@ -217,24 +248,79 @@ fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeI )); } } - warped_parts(n).into_iter().find_map(|c| unwarpable_image(c, pr)) + // Type and symbol instances are drawn through the warp ([`warp_node`]): their box's corners + // must stay in front of its horizon, and the projection they end with must be one that draws. + if let Some(kind) = Cornered::of(n).filter(|k| *k != Cornered::Image && pr.is_projective()) { + if kind == Cornered::Type && n.extras().perspective.as_deref().is_some_and(|p| p.editing) { + return Some((n.id, kind, Unwarpable::EditingFlat)); + } + if n.drawn_corners(symbols).is_some_and(|q| !q.iter().all(|p| pr.in_front(*p))) { + return Some((n.id, kind, Unwarpable::Horizon)); + } + let had = n.extras().perspective.as_deref().and_then(|p| p.homography()).unwrap_or(Homography::IDENTITY); + let Some(after) = pr.homography().checked_then_after(&had).and_then(|h| Homography::from_array(h.to_array())) else { + return Some((n.id, kind, Unwarpable::TooNarrow)); + }; + // The map it ends with must place its flat corners by the rules it is drawn with. + let flat = match n.extras().perspective.is_some() { + true => { + let mut flat = n.clone(); + flat.extras_mut().perspective = None; + flat.drawn_corners(symbols) + } + false => n.drawn_corners(symbols), + }; + if flat.is_some_and(|q| q.iter().any(|p| after.apply(*p).is_none())) { + return Some((n.id, kind, Unwarpable::Horizon)); + } + } + warped_parts(n).into_iter().find_map(|c| unwarpable(c, pr, symbols)) } -/// The first image in `n` that [`warp_node`] reaches (its children and the art of linked opacity -/// masks). -fn first_image(n: &Node) -> Option { - if matches!(n.kind, NodeKind::Image(_)) { - return Some(n.id); +/// The first image, type object or symbol instance in `n` that [`warp_node`] reaches (its children +/// and the art of linked opacity masks), whose corners follow the warp exactly. +fn first_cornered(n: &Node) -> Option<(vectorcraft_doc::NodeId, Cornered)> { + if let Some(kind) = Cornered::of(n) { + return Some((n.id, kind)); + } + warped_parts(n).into_iter().find_map(first_cornered) +} + +/// The objects whose corners follow a distort exactly. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Cornered { + Image, + Type, + Symbol, +} + +impl Cornered { + fn of(n: &Node) -> Option { + match n.kind { + NodeKind::Image(_) => Some(Self::Image), + NodeKind::Text(_) => Some(Self::Type), + NodeKind::SymbolInstance { .. } => Some(Self::Symbol), + _ => None, + } + } + + /// The object's name in an error. + fn noun(self) -> &'static str { + match self { + Self::Image => "image", + Self::Type => "type object", + Self::Symbol => "symbol instance", + } } - warped_parts(n).into_iter().find_map(first_image) } /// The objects inside `n` that [`warp_node`] warps point by point: the children of layers, groups -/// and compound paths, and the art of a linked opacity mask on those, paths and images. Other -/// objects (blends, envelopes, repeats and the rest) take the warp's affine approximation whole. +/// and compound paths, and the art of a linked opacity mask on those, paths, images, type and +/// symbol instances. Other objects (blends, envelopes, repeats and the rest) take the warp's affine +/// approximation whole. fn warped_parts(n: &Node) -> Vec<&Node> { let inside = matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }); - let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_)); + let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_) | NodeKind::Text(_) | NodeKind::SymbolInstance { .. }); let children = n.children().filter(|_| inside).into_iter().flatten().map(|c| &**c); let mask = n.extras().mask.as_deref().filter(|m| mask_too && m.linked).map(|m| &*m.art); children.chain(mask).collect() @@ -246,9 +332,11 @@ pub(crate) fn distorted_image_error(command: &str, id: vectorcraft_doc::NodeId) bad(command, format!("object {} is an image changed by Perspective Distort or Free Distort, which this command does not work on", id.0)) } -/// Why an image cannot follow the corners of a distort. +/// Why an image, type object or symbol instance cannot follow the corners of a distort. #[derive(Clone, Copy)] enum Unwarpable { + /// Type is being edited flat in Edit Text. + EditingFlat, /// Its corners would fold over, meet or fall on one line. NotConvex, /// A corner would cross the warp's horizon. @@ -257,14 +345,16 @@ enum Unwarpable { TooNarrow, } -/// The error of `object.distort` when image `id` cannot follow its corners. -fn unwarpable_error(id: vectorcraft_doc::NodeId, why: Unwarpable) -> EngineError { +/// The error of `object.distort` when object `id` (`kind`) cannot follow its corners. +fn unwarpable_error(id: vectorcraft_doc::NodeId, kind: Cornered, why: Unwarpable) -> EngineError { const C: &str = "object.distort"; + let noun = kind.noun(); match why { - Unwarpable::NotConvex => bad(C, format!("image {} cannot be distorted this way: its corners would not make a convex shape", id.0)), - Unwarpable::Horizon => bad(C, format!("image {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)), + Unwarpable::EditingFlat => bad(C, format!("{noun} {} cannot be distorted this way: it is being edited flat in Edit Text", id.0)), + Unwarpable::NotConvex => bad(C, format!("{noun} {} cannot be distorted this way: its corners would not make a convex shape", id.0)), + Unwarpable::Horizon => bad(C, format!("{noun} {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)), Unwarpable::TooNarrow => { - bad(C, format!("image {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0)) + bad(C, format!("{noun} {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0)) } } } @@ -311,25 +401,26 @@ fn distort(s: &mut Session, p: &Value) -> Result { return Ok(ids_json); } let pr = Projective::from_box(src, [tl, tr, br, bl]); - // An image's corners follow the handles exactly, so they must stay a convex shape: nothing - // changes when one would not. + // The corners of an image, a type object or a symbol instance follow the handles exactly, so + // they must stay a convex shape: nothing changes when one would not. let doc = &s.doc()?.doc; // Corners that do not make a convex shape give no perspective map (the warp falls back to an - // affine one), so an image cannot follow them. + // affine one), so such an object cannot follow them. if vectorcraft_doc::image_quad::check(&[tl, tr, br, bl]).is_err() - && let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image) + && let Some((id, kind)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_cornered) { - return Err(unwarpable_error(id, Unwarpable::NotConvex)); + return Err(unwarpable_error(id, kind, Unwarpable::NotConvex)); } // Corners so close together that the map falls back to an affine one: the box's corners do - // not reach the handles, so an image cannot follow them either. + // not reach the handles, so such an object cannot follow them either. if !reaches_corners(src, [tl, tr, br, bl]) - && let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image) + && let Some((id, kind)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_cornered) { - return Err(unwarpable_error(id, Unwarpable::TooNarrow)); + return Err(unwarpable_error(id, kind, Unwarpable::TooNarrow)); } - if let Some((id, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable_image(n, &pr)) { - return Err(unwarpable_error(id, why)); + let symbols = doc.symbol_boxes(); + if let Some((id, kind, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable(n, &pr, &symbols)) { + return Err(unwarpable_error(id, kind, why)); } s.edit("Free Distort", |d, _| { for id in &ids { diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index f87cc07654..4f05e615af 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -3,6 +3,44 @@ use super::history::{History, HistoryEntry}; use super::interaction::{Interaction, LastTransform, UndoGroup}; use super::{Arc, Document, NodeId, NodeKind, Selection, Value, cmd, file_access}; +/// A document's window as the desktop app shows it ([`crate::Session::window_views`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WindowView { + /// The document point at the centre of the canvas. + pub center: vectorcraft_geom::Point, + /// The zoom is 1 at the window's displayed 100%. + pub zoom: f64, + /// The camera uses this scale at the window's displayed 100%. + pub zoom_baseline: f64, + /// The view's rotation in degrees, clockwise on screen. + pub rotation: f64, + /// The canvas's width and height in document points at a zoom of 1. + pub size: [f64; 2], + /// View › Screen Mode: 0 Normal, 1 Full Screen Mode with Menu Bar, 2 Full Screen Mode, 3 + /// Presentation Mode (`view.screenMode`). + pub screen_mode: u8, +} + +impl WindowView { + /// The physical camera scale stays within these limits. + pub const ZOOM_RANGE: (f64, f64) = (0.0313, 640.0); + + /// `zoom_range` returns this window's allowed displayed zoom ratios. + pub fn zoom_range(&self) -> (f64, f64) { + let (min, max) = Self::ZOOM_RANGE; + (min / self.zoom_baseline, max / self.zoom_baseline) + } + + /// The part of the document the canvas shows: the box around its four corners, which a + /// rotated view turns. + pub fn visible(&self) -> vectorcraft_geom::Rect { + let (sin, cos) = self.rotation.to_radians().sin_cos(); + let (w, h) = (self.size[0] / self.zoom / 2.0, self.size[1] / self.zoom / 2.0); + let (x, y) = (w * cos.abs() + h * sin.abs(), w * sin.abs() + h * cos.abs()); + vectorcraft_geom::Rect::new(self.center.x - x, self.center.y - y, self.center.x + x, self.center.y + y) + } +} + /// Per-document editing state. #[derive(Clone, Debug)] pub struct DocState { @@ -501,7 +539,9 @@ impl DocState { /// Lock Guides `guides_locked`. `record` is the record of the selection before, in the same /// document: the objects that leave the selection are taken out of its paints and the objects /// that join it are read into them, unless that reads more objects than reading the selection - /// again would, or the paints left can't be told apart without reading them again. + /// again would, counting the contents of groups and containers on both sides + /// ([`cmd::SelectionPaints::reads_no_more_than`]), or the paints left can't be told apart + /// without reading them again. pub(crate) fn record_selection(&mut self, record: Option, guides_locked: bool) { if !objects_only(&self.selection) { self.selection_record = None; @@ -514,7 +554,8 @@ impl DocState { let (kept, removed) = kept_from(&r.objects, objects); let gone = left_out(&removed, objects); let joined = left_out(&objects[kept..], &r.objects); - if gone.len() + joined.len() > objects.len() || !p.remove(&self.doc, &gone) { + let changed = [gone.as_slice(), joined.as_slice()].concat(); + if !cmd::SelectionPaints::reads_no_more_than(&self.doc, &changed, objects) || !p.remove(&self.doc, &gone) { r.paints = None; } else { p.add(&self.doc, &joined); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 288d35ffd4..3f71f45cb3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -378,8 +378,16 @@ pub struct Session { pub(crate) startup_failures: Vec<(String, String)>, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, + /// The styles the steps of a batch a script runs removed or renamed and the documents they + /// reverted ([`script::note_style_lists`]). + pub(crate) script_style_trail: script::StyleTrail, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, + /// The desktop app supplies each window by (document uid, runtime window identity) while a + /// script runs. Scripts read them as `Document.views`, and the app applies their zoom, center, + /// and screen mode. This list is empty without windows (headless). + /// View state: not saved, not undoable, and a run that fails keeps what it changed. + pub window_views: Vec<((u64, u64), WindowView)>, /// Write recovery copies of the unsaved documents before a run, and don't start without them. pub script_copy_first: bool, /// While the active tool's actions run: their commands aren't "a command from outside the @@ -504,7 +512,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS; #[cfg(test)] use command_sets::given_ids; pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit}; -pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection}; +pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection, WindowView}; pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY}; #[cfg(test)] use history::history_budget_for; diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs new file mode 100644 index 0000000000..2abb290cf7 --- /dev/null +++ b/crates/engine/src/script/actions.rs @@ -0,0 +1,354 @@ +//! `app.doScript(action, set, dialogs?)`: plays an action of the Actions panel inside the script's +//! run, as the VBScript reference's `DoScript` method of the Application object describes it +//! (). +//! +//! The actions a run can play come with its request (`script.run`'s `actions`), each with the steps +//! that playback runs: the included steps, those of a recorded `command.batch` one by one. In the app +//! they are the Actions panel's. +//! +//! VectorCraft's own rules, which the reference does not state: +//! - The action and its set are matched by their exact names; a name that matches no action, or +//! more than one, throws before any step runs. +//! - The call returns when every step has run, or when the run is asked to stop. Each step runs as `vc.run` runs a command: it joins +//! the run's transaction and its one undo step for each changed document, it is counted as a host +//! call, it reads and writes files only where the script may, and a step that fails is put back +//! and throws an error that names the step and the action, while the steps before it stay done. +//! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine +//! does not have (a View menu step, or one that plays an action), and a stop throw before any step +//! runs, as does such a command among those an `action.batch` step plays. An action cannot play +//! another action, so it cannot play itself. +//! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it +//! changes nothing. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostError, HostMember}; + +use super::{Host, Link, command, current, refused_to_scripts}; + +/// The most actions a run's request may carry. +pub const MAX_ACTIONS: usize = 4096; +/// The most steps one action may have, after a `command.batch` step gives its own steps. +pub const MAX_ACTION_STEPS: usize = 10_000; +/// The most steps the actions of one request may have in all. +pub const MAX_ALL_STEPS: usize = 100_000; +/// The most bytes of the request's actions, as JSON. +pub const MAX_ACTIONS_BYTES: usize = 16 << 20; +/// The longest name of an action or a set, in bytes. +pub const MAX_NAME_BYTES: usize = 1024; +/// The longest command id of a step, in bytes. +const MAX_ID_BYTES: usize = 256; +/// The command id of a stop, which waits for the person in the Actions panel. +pub const STOP_STEP: &str = "action.stop"; + +/// An action a run can play: its set's name, its name and the steps playback runs. +#[derive(Clone, Debug)] +pub struct Playable { + set: String, + name: String, + steps: Vec, +} + +/// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a +/// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and +/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names. +#[derive(Clone, Debug)] +struct Step { + place: String, + id: String, + params: Value, + bytes: u64, + artboard: Option, +} + +/// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the +/// step's place in the action (1 for the first; default its place in the list), within the limits +/// above. A `command.batch` step gives its own steps, each at the batch's place and its own. +pub fn parse(v: Option<&Value>) -> Result, String> { + let Some(v) = v else { return Ok(Vec::new()) }; + let Value::Array(list) = v else { return Err("`actions` must be a list".into()) }; + if list.len() > MAX_ACTIONS { + return Err(format!("`actions` holds more than {MAX_ACTIONS} actions")); + } + if let Some(place) = super::too_deep(v) { + return Err(format!("`actions{place}` is nested more than 64 levels deep")); + } + if serde_json::to_vec(v).map_or(true, |b| b.len() > MAX_ACTIONS_BYTES) { + return Err("`actions` is larger than 16 MiB".into()); + } + let mut all = 0usize; + let mut out = Vec::with_capacity(list.len()); + for (i, a) in list.iter().enumerate() { + let at = format!("`actions[{i}]`"); + let Value::Object(a) = a else { return Err(format!("{at} must be an object")) }; + only_keys(a, &["set", "name", "steps"], &at)?; + let set = name_of(a, "set", &at)?; + let name = name_of(a, "name", &at)?; + let Some(Value::Array(given)) = a.get("steps") else { return Err(format!("{at}.steps must be a list")) }; + let mut steps = Vec::new(); + for (j, s) in given.iter().enumerate() { + let at = format!("{at}.steps[{j}]"); + let Value::Object(s) = s else { return Err(format!("{at} must be an object")) }; + only_keys(s, &["command", "params", "step"], &at)?; + let place = match s.get("step") { + None => (j + 1).to_string(), + Some(n) => match n.as_u64().filter(|n| (1..=1_000_000).contains(n)) { + Some(n) => n.to_string(), + None => return Err(format!("{at}.step must be a whole number from 1 to 1000000")), + }, + }; + let (id, params) = command_of(s, &at)?; + match params.get("commands") { + Some(Value::Array(inner)) if id == "command.batch" => { + // The batch's `artboard`, for its steps that act on the active artboard, as + // `command.batch` reads it. + let artboard = params.get("artboard").and_then(Value::as_u64); + for (k, c) in inner.iter().enumerate() { + let at = format!("{at}.params.commands[{k}]"); + let Value::Object(c) = c else { return Err(format!("{at} must be an object")) }; + let (id, params) = command_of(c, &at)?; + if id == "command.batch" { + return Err(format!("{at} is a command.batch inside a command.batch")); + } + steps.push(step(format!("{place}.{}", k + 1), id, params, artboard)); + } + } + _ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")), + _ => steps.push(step(place, id, params, None)), + } + if steps.len() > MAX_ACTION_STEPS { + return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps")); + } + } + all += steps.len(); + if all > MAX_ALL_STEPS { + return Err(format!("`actions` has more than {MAX_ALL_STEPS} steps in all")); + } + out.push(Playable { set, name, steps }); + } + Ok(out) +} + +impl Playable { + /// The steps the action runs. + pub fn len(&self) -> usize { + self.steps.len() + } + + /// Whether the action runs no step. + pub fn is_empty(&self) -> bool { + self.steps.is_empty() + } +} + +fn only_keys(o: &Map, keys: &[&str], at: &str) -> Result<(), String> { + match o.keys().find(|k| !keys.contains(&k.as_str())) { + Some(k) => Err(format!("{at} has the unknown key `{}`", shown(k))), + None => Ok(()), + } +} + +fn name_of(o: &Map, key: &str, at: &str) -> Result { + match o.get(key) { + Some(Value::String(s)) if s.len() <= MAX_NAME_BYTES => Ok(s.clone()), + Some(Value::String(_)) => Err(format!("{at}.{key} is longer than {MAX_NAME_BYTES} bytes")), + _ => Err(format!("{at}.{key} must be a string")), + } +} + +/// A step's `command` and `params` (default `{}`). +fn command_of(o: &Map, at: &str) -> Result<(String, Value), String> { + let id = match o.get("command") { + Some(Value::String(id)) if !id.is_empty() && id.len() <= MAX_ID_BYTES => id.clone(), + _ => return Err(format!("{at}.command must be a command id")), + }; + let params = match o.get("params") { + None => json!({}), + Some(p @ Value::Object(_)) => p.clone(), + Some(_) => return Err(format!("{at}.params must be an object")), + }; + Ok((id, params)) +} + +fn step(place: String, id: String, params: Value, artboard: Option) -> Step { + let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64); + Step { place, id, params, bytes, artboard } +} + +/// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters +/// as U+FFFD. +fn shown(text: &str) -> String { + const MAX: usize = 80; + let mut out: String = text.chars().take(MAX).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect(); + if text.chars().nth(MAX).is_some() { + out.push('…'); + } + out +} + +/// The members of `app` this module adds. +pub(super) fn app_members(link: &Link) -> Vec { + let l = link.clone(); + let play = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + do_script(&h, &a) + }); + let info = super::dom::returns("undefined", &[("action", "string"), ("set", "string"), ("dialogs", "boolean")]); + let mut members = vec![("doScript".to_string(), HostMember::Method(play), info)]; + members.extend(["loadAction", "unloadAction"].map(|name| super::dom::later(link, "Application", name))); + members +} + +fn arg(a: &[Data], i: usize) -> &Data { + a.get(i).unwrap_or(&Data::Undefined) +} + +/// `app.doScript(action, set, dialogs?)`, its arguments after `this`. +fn do_script(h: &Host, a: &[Data]) -> std::result::Result { + if a.len() > 4 { + return Err(HostError::Type("doScript takes an action's name, its set's name and dialogs".into())); + } + let (Data::String(action), Data::String(set)) = (arg(a, 1), arg(a, 2)) else { + return Err(HostError::Type("doScript needs the action's name and its set's name, as strings".into())); + }; + if action.is_empty() || set.is_empty() { + return Err(HostError::Error("doScript needs the action's name and its set's name".into())); + } + if action.len() > MAX_NAME_BYTES || set.len() > MAX_NAME_BYTES { + return Err(HostError::Range(format!("an action's or a set's name is at most {MAX_NAME_BYTES} bytes"))); + } + if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) { + return Err(HostError::Type("doScript's dialogs must be true or false".into())); + } + let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect(); + let p = match found.as_slice() { + [p] => *p, + [] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))), + [] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))), + _ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))), + }; + if p.steps.is_empty() { + return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name)))); + } + // Every step is checked before the first runs, so a step that cannot run leaves the documents as + // they were. + for s in &p.steps { + if let Some((place, id)) = refused_step(s) { + let name = shown(&p.name); + return Err(HostError::Error(if id == STOP_STEP { + format!("step {place} of “{name}” is a stop, which a script cannot wait at") + } else { + format!("step {place} of “{name}” runs `{}`, which a script cannot run", shown(&id)) + })); + } + } + for s in &p.steps { + // A run asked to stop runs no further step; the realm ends it at its next instruction and + // puts the documents back. + if h.session.borrow().script_stop.is_set() { + break; + } + h.charge_call(16 + s.id.len() as u64 + s.bytes)?; + // Saved steps run as they run in the Actions panel: keys their commands no longer read are + // passed over. + let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard }; + let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params); + let outer = h.session.borrow_mut().set_replaying(true); + let r = command(h, &s.id, ¶ms); + h.session.borrow_mut().set_replaying(outer); + if let Err(e) = r { + let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id)); + return Err(match e { + HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) => HostError::Error(named(m)), + other => other, + }); + } + } + Ok(Data::Undefined) +} + +/// The place and command of the first command step `s` would run that a script may not run: the +/// step itself, or one of the `commands` an `action.batch` step plays on each file (placed as the +/// batch's place and its own, as in `3.2`). A stop, a command a script may not run and a command the +/// engine does not have are refused. +fn refused_step(s: &Step) -> Option<(String, String)> { + let refused = |id: &str| id == STOP_STEP || refused_to_scripts(id) || crate::find_command(id).is_none(); + if refused(&s.id) { + return Some((s.place.clone(), s.id.clone())); + } + if s.id != "action.batch" { + return None; + } + let commands = s.params.get("commands").and_then(Value::as_array)?; + commands.iter().enumerate().find_map(|(k, c)| { + let id = c.get("command").and_then(Value::as_str).unwrap_or(""); + refused(id).then(|| (format!("{}.{}", s.place, k + 1), id.to_owned())) + }) +} + +/// `params` of step `id`, with the active artboard of the active document added as a +/// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for +/// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to +/// Selected Art. The active artboard is the index `start` gives for the document (its index as the +/// run started, which the view keeps), past the last artboard the last one, as the view shows it +/// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While +/// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its +/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh +/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the +/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork +/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the +/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch` +/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past +/// the last artboard the last one, and none in a document without artboards, as `command.batch` +/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit +/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept. +pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value { + let mut params = params.clone(); + let Some(st) = s.active() else { return params }; + let n = st.doc.artboards.len(); + let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) { + (Some(_), _) if n == 0 => return params, + (Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)), + (None, Some((_, i))) => (*i).min(n.saturating_sub(1)), + (None, None) => super::dom::active_artboard(st), + }; + let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack"); + let fit_art = id == "artboard.fitToArt"; + let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id) { + "artboard" + } else if crate::FIT_ACTIVE_ARTBOARD.contains(&id) { + "index" + } else { + return params; + }; + let Some(p) = params.as_object_mut() else { return params }; + if p.contains_key(key) || (fit_art && p.contains_key("indices")) || (paste && (n == 0 || p.contains_key("artboards"))) { + return params; + } + let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() }; + let kept: Vec = match start.picks { + Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => { + list.iter().copied().filter(|i| *i < n).collect() + } + _ => Vec::new(), + }; + if kept.len() >= 2 { + p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept)); + } else if picks.is_empty() { + p.insert(key.into(), json!(active)); + } else if fit_art { + p.insert("indices".into(), json!(picks)); + } + params +} + +/// What [`on_active_artboard`] reads besides the session: the index of each open document's active +/// artboard as the run started, by document uid; the Artboard tool's selection as the run started, +/// with its document's uid; and the `artboard` a step's recorded `command.batch` names. +pub(crate) struct Start<'a> { + pub active: &'a [(u64, usize)], + pub picks: Option<&'a (u64, Vec)>, + pub batch: Option, +} diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index a674396f4b..c635db0585 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -21,8 +21,9 @@ use std::collections::VecDeque; use std::rc::Rc; use serde_json::{Map, Value, json}; -use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; +use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind}; +use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep}; use super::{Host, console}; /// The most bytes (UTF-8) of a dialog's message. @@ -48,6 +49,8 @@ pub enum DialogKind { Alert, Confirm, Prompt, + /// A ScriptUI dialog's `show()` ([`super::scriptui`]). + Window, } impl DialogKind { @@ -57,6 +60,7 @@ impl DialogKind { Self::Alert => "alert", Self::Confirm => "confirm", Self::Prompt => "prompt", + Self::Window => "window", } } } @@ -85,6 +89,8 @@ pub enum DialogAnswer { Confirm(bool), /// OK with the field's text, or Cancel (`None`), for `prompt`. Prompt(Option), + /// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask. + Window(Vec), } impl DialogAnswer { @@ -93,13 +99,14 @@ impl DialogAnswer { Self::Ok => DialogKind::Alert, Self::Confirm(_) => DialogKind::Confirm, Self::Prompt(_) => DialogKind::Prompt, + Self::Window(_) => DialogKind::Window, } } /// What the function returns. fn data(&self) -> Data { match self { - Self::Ok => Data::Undefined, + Self::Ok | Self::Window(_) => Data::Undefined, Self::Confirm(b) => Data::Bool(*b), Self::Prompt(Some(t)) => Data::String(t.clone()), Self::Prompt(None) => Data::Null, @@ -112,6 +119,7 @@ impl DialogAnswer { Self::Ok => json!("ok"), Self::Confirm(b) => json!(b), Self::Prompt(t) => json!(t), + Self::Window(steps) => json!(steps.len()), } } } @@ -148,8 +156,9 @@ pub fn cut_to(text: &str, max: usize) -> &str { } /// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: -/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter -/// took before dialogs existed, is an empty list. +/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}` +/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an +/// empty list. pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { let list = match v { None => return Ok(Vec::new()), @@ -166,11 +175,18 @@ pub(crate) fn parse_answers(v: Option<&Value>) -> Result, Stri list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect() } -fn answer(a: &Value) -> Result { - let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") }; +fn answer(a: &Value) -> Result { + let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`".into()) }; if o.len() != 2 || !o.contains_key("value") { - return Err("must have exactly `kind` and `value`"); + return Err("must have exactly `kind` and `value`".into()); } + if o.get("kind").and_then(Value::as_str) == Some("window") { + return super::scriptui::parse_steps(&o["value"]).map(DialogAnswer::Window); + } + known_answer(o).map_err(String::from) +} + +fn known_answer(o: &Map) -> Result { match (o.get("kind").and_then(Value::as_str), &o["value"]) { (Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok), (Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""), @@ -180,7 +196,7 @@ fn answer(a: &Value) -> Result { (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), - _ => Err("must have `kind` alert, confirm or prompt"), + _ => Err("must have `kind` alert, confirm, prompt or window"), } } @@ -199,6 +215,15 @@ pub(crate) struct Dialogs { record_bytes: Cell, count: Cell, truncated: Cell, + /// The ScriptUI dialog whose `show()` is running. + window: RefCell>, + /// Where that dialog's record is in `records`, kept from when it opened so a dialog a handler + /// opens is listed after it; `None` when the list had stopped at its limit. + window_slot: Cell>, + /// That dialog waits for what the person does. + window_waiting: Cell, + /// The `show()` calls the run has made. + shows: Cell, } impl Dialogs { @@ -213,6 +238,10 @@ impl Dialogs { record_bytes: Cell::new(0), count: Cell::new(0), truncated: Cell::new(false), + window: RefCell::default(), + window_slot: Cell::new(None), + window_waiting: Cell::new(false), + shows: Cell::new(0), } } @@ -222,7 +251,176 @@ impl Dialogs { } pub(crate) fn is_waiting(&self) -> bool { - self.waiting.borrow().is_some() + self.waiting.borrow().is_some() || self.window_waiting.get() + } + + /// The ScriptUI dialog that waits for what the person does. + pub(crate) fn waiting_window(&self) -> Option { + if !self.window_waiting.get() { + return None; + } + self.window.borrow().as_ref().map(|s| s.dialog.clone()) + } + + /// The ScriptUI dialog whose `show()` is running, as it last waited, also while a handler runs. + pub(crate) fn showing_window(&self) -> Option { + self.window.borrow().as_ref().map(|s| s.dialog.clone()) + } + + /// Gives the waiting ScriptUI dialog `event`, once it is checked against the dialog. + pub(crate) fn window_answer(&self, realm: &mut Realm, event: UiEvent) -> Result<(), String> { + if !self.window_waiting.get() { + return Err("no script dialog waits".into()); + } + let event = { + let mut window = self.window.borrow_mut(); + let Some(showing) = window.as_mut() else { return Err("no script dialog waits".into()) }; + let event = scriptui::check_event(&showing.dialog, event)?; + showing.events = showing.events.saturating_add(1); + event + }; + self.window_waiting.set(false); + if let Err(e) = realm.answer(event.data()) { + *self.failed.borrow_mut() = Some(e); + } + Ok(()) + } + + fn cannot_wait(&self) -> Result<(), HostError> { + if self.framed && !self.can_wait.get() { + return Err(HostError::Error( + "show: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code" + .into(), + )); + } + Ok(()) + } + + /// `show()` opens `dialog`. A run with nobody to ask takes its next answer, which must be a + /// `window` answer. + pub(crate) fn window_open(&self, mut dialog: ScriptUiDialog) -> Result<(), HostError> { + self.cannot_wait()?; + self.shows.set(self.shows.get().saturating_add(1)); + dialog.shown = self.shows.get(); + let mut showing = Showing { dialog, steps: None, events: 0 }; + if !self.framed { + let next = self.answers.borrow_mut().pop_front(); + match next { + Some(DialogAnswer::Window(steps)) => showing.steps = Some(steps.into()), + Some(a) => { + self.push_record(showing.record(json!("missing"))); + return Err(HostError::Abort(format!("show: the next answer in `answers` is for {}, not window", a.kind().id()))); + } + None => { + self.push_record(showing.record(json!("missing"))); + return Err(HostError::Abort("show: `answers` has no answer left for this dialog".into())); + } + } + } + self.window_slot.set(self.reserve_record()); + *self.window.borrow_mut() = Some(showing); + Ok(()) + } + + /// Keeps a place in the list for the ScriptUI dialog that opens now, counted; its bytes count + /// once the dialog ends. → the place, or `None` when the list stopped at its limit. + fn reserve_record(&self) -> Option { + self.count.set(self.count.get().saturating_add(1)); + let mut records = self.records.borrow_mut(); + if self.truncated.get() || records.len() >= MAX_RECORDS { + self.truncated.set(true); + return None; + } + records.push(Value::Null); + Some(records.len() - 1) + } + + /// Puts the record of the ScriptUI dialog `showing`, with its `answer`, in the place it took + /// in the list when it opened. When the dialogs a handler opened left no room for it, the list + /// drops the last of them until it fits, or stops before the dialog when it does not fit + /// alone, so it still holds the first dialogs in the order they opened, and is marked as + /// stopped at its limit. + fn end_record(&self, showing: &Showing, answer: Value) { + let Some(i) = self.window_slot.take() else { return }; + let size = |r: &Value| serde_json::to_vec(r).map_or(usize::MAX, |b| b.len()); + let r = showing.record(answer); + let bytes = size(&r); + let mut records = self.records.borrow_mut(); + if i >= records.len() { + return; + } + while self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES && records.len() > i + 1 { + let last = records.pop().map_or(0, |r| size(&r)); + self.record_bytes.set(self.record_bytes.get().saturating_sub(last)); + self.truncated.set(true); + } + if self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES { + records.truncate(i); + self.truncated.set(true); + return; + } + self.record_bytes.set(self.record_bytes.get() + bytes); + if let Some(slot) = records.get_mut(i) { + *slot = r; + } + } + + /// The dialog that is showing waits, as `dialog` now is. A run with nobody to ask takes the + /// next step of its answer. + pub(crate) fn window_wait(&self, mut dialog: ScriptUiDialog) -> Result { + self.cannot_wait()?; + let mut window = self.window.borrow_mut(); + let Some(showing) = window.as_mut() else { return Err(HostError::Error("show: no dialog is showing".into())) }; + dialog.shown = showing.dialog.shown; + showing.dialog = dialog; + let Some(steps) = showing.steps.as_mut() else { + drop(window); + self.window_waiting.set(true); + return Err(HostError::Wait); + }; + let failure = match steps.pop_front() { + None => "show: the dialog's answer in `answers` has no step left".to_string(), + Some(step) => match scriptui::step_event(&showing.dialog, &step) { + Ok(event) => { + showing.events = showing.events.saturating_add(1); + return Ok(event.data()); + } + Err(e) => format!("show: a step of the dialog's answer in `answers` cannot be taken: {e}"), + }, + }; + if let Some(showing) = window.take() { + self.end_record(&showing, json!("missing")); + } + Err(HostError::Abort(failure)) + } + + /// `show()` ends with `result`, or with an error when not `normal`. A run with nobody to ask + /// must have used every step of the dialog's answer. + pub(crate) fn window_end(&self, result: f64, normal: bool) -> Result<(), HostError> { + self.window_waiting.set(false); + let Some(showing) = self.window.borrow_mut().take() else { return Ok(()) }; + let left = showing.steps.as_ref().map_or(0, std::collections::VecDeque::len); + let steps = if left == 1 { "step" } else { "steps" }; + let unused = format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use"); + if normal && left > 0 { + self.end_record(&showing, json!("missing")); + return Err(HostError::Abort(unused)); + } + // A show that a handler's error ended still ends the run when steps are left: the script + // can catch that error, and the run must not finish as if it took every step. + if left > 0 { + let mut failed = self.failed.borrow_mut(); + if failed.is_none() { + *failed = Some(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message: unused, line: 0, column: 0, authored: false }); + } + } + let answer = match result { + _ if !normal => json!("error"), + r if r.fract() == 0.0 && r.abs() < 9.0e15 => json!(r as i64), + r => json!(r), + }; + self.end_record(&showing, answer); + Ok(()) } /// The error that ended the run when its answer could not reach the script. @@ -257,10 +455,13 @@ impl Dialogs { if let Some(d) = self.waiting.borrow_mut().take() { self.record(&d, json!("stop")); } + self.window_waiting.set(false); + if let Some(showing) = self.window.borrow_mut().take() { + self.end_record(&showing, json!("stop")); + } } fn record(&self, d: &ScriptDialog, answer: Value) { - self.count.set(self.count.get().saturating_add(1)); let mut r = Map::new(); r.insert("kind".into(), json!(d.kind.id())); r.insert("message".into(), json!(d.message)); @@ -269,9 +470,14 @@ impl Dialogs { DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), + DialogKind::Window => None, }; r.insert("answer".into(), answer); - let r = Value::Object(r); + self.push_record(Value::Object(r)); + } + + fn push_record(&self, r: Value) { + self.count.set(self.count.get().saturating_add(1)); let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len()); let mut records = self.records.borrow_mut(); if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES { @@ -325,6 +531,7 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; (text(args, 2), false, false, preset) } + DialogKind::Window => return Err(HostError::Error("a ScriptUI dialog opens with show()".into())), }; if message.len() > MAX_MESSAGE_BYTES { return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB"))); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7554440ab6..7c50925bf0 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2,8 +2,10 @@ //! them, as the help pages , //! , //! , -//! and -//! describe them. +//! , +//! , +//! and +//! describe them. //! //! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the //! document's [`crate::DocState::uid`] and, for art and layers, the object's id and the document's @@ -46,13 +48,23 @@ //! must be one of that document's that can be selected, or nothing changes. `undefined` throws. //! - `controlBounds` is the visible bounds, widened to take in the direction points of every path //! in the object. +//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]), +//! in view-number order, and none without one. View objects keep their window's identity when +//! windows are renumbered. The screen mode is the app's: +//! setting it on one view sets it on every view. Its `zoom` is 1 at the window's displayed 100%; +//! the physical camera scale ranges from 0.0313 to 640, and the allowed zoom ratios account for +//! the window's display density with Display Print Size at 100% Zoom enabled. `screenMode` reads +//! Presentation Mode as `ScreenMode.FULLSCREEN`. Changing a view runs no command, is not +//! undoable and stays when the run fails. +//! A center outside the canvas after coordinate conversion throws a `RangeError`. //! - Members the help pages list that are not here yet throw an error that says so, and `reflect` //! leaves them out. -//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an -//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change -//! nothing, even for the value the object has. The exception is `opacity` given the value the -//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps -//! another opacity it would still change the graph, so it is refused too. Its `name` and `note` +//! - Assigning `hidden`, `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or +//! `height` to an object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` +//! and change nothing, even for the value the object has. The exception is `opacity` or +//! `blendingMode` given the value the object has when that changes nothing; on a graph's mark or +//! label whose series or kind keeps another opacity or blend mode it would still change the graph, +//! so it is refused too. Its `name` and `note` //! still change. An object that is hidden or locked itself, or is in a hidden or locked group, //! takes them. //! - `name` and `note` take a number or a Boolean as the text `String(value)` gives. @@ -70,15 +82,17 @@ use std::rc::Rc; use std::sync::Arc; use serde_json::{Value, json}; +use vectorcraft_color::BlendMode; use vectorcraft_geom::{Point, Rect}; use vectorcraft_js::{ ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts, }; use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; -use crate::{DocState, Document, NodeId, NodeKind, Session}; +use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; mod tags; +mod text; mod variables; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; @@ -102,6 +116,8 @@ pub const STALE_ITEM: &str = "Stale page item"; pub const STALE_DOCUMENT: &str = "Stale document"; /// The error of `index` and `getByName` when nothing matches. pub const NOT_FOUND: &str = "Not found"; +/// The error for a view whose document no longer has a window, or that came from an earlier run. +pub const STALE_VIEW: &str = "Stale view"; /// The most objects one read of a selection gives, and the most a selection assignment takes. pub const MAX_LISTED: usize = 10_000; /// The longest name an object or a path query may have, in bytes. @@ -152,6 +168,7 @@ pub(super) struct State { items: RefCell>, locked: RefCell>, saving: Cell, + text: text::TextState, presets: RefCell>>, preset_bytes: Cell, preset_limit: u64, @@ -179,19 +196,24 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result HostMember { } /// A member of a class with what `reflect` tells of it. -type Described = (String, HostMember, MemberInfo); +pub(super) type Described = (String, HostMember, MemberInfo); /// A property's or a method's result's type for `reflect`. fn typed(data_type: &str) -> MemberInfo { @@ -284,15 +306,15 @@ fn typed(data_type: &str) -> MemberInfo { } /// A method's result's type and its arguments' names and types, for `reflect`. -fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { +pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect(); MemberInfo { arguments, ..typed(data_type) } } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document or page item `this` is still there. `hasOwnProperty` is false for it, -/// so a script that checks for the member first skips it, and `reflect` leaves it out. -fn later(link: &Link, class: &'static str, name: &'static str) -> Described { +/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is +/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out. +pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -302,9 +324,12 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> Described { "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" => { + "PageItem" | "TextFrame" => { item_of(&h, arg(&a, 0))?; } + "TextRange" => { + text::check_range(&h, arg(&a, 0))?; + } _ => {} } Err(HostError::Error(message.clone())) @@ -551,7 +576,7 @@ struct Frame { } /// The index of the active artboard of `st`, as the view keeps it. -fn active_artboard(st: &DocState) -> usize { +pub(super) fn active_artboard(st: &DocState) -> usize { let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id); st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0) } @@ -766,6 +791,11 @@ fn on_doc( Ok(v) } +/// Marks stale the style objects whose styles a command the run ran removed or renamed. +pub(super) fn after_kept_command(h: &Host) { + text::styles::after_command(h); +} + /// Runs `id` with `params` on the item's document, its selection kept. fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { on_doc(h, item.doc.uid, true, |h| command(h, id, params)) @@ -835,6 +865,13 @@ fn path_key(p: &str) -> String { if windows { p.to_lowercase() } else { p } } +/// `app.redraw()`: returns without changing anything. The app draws a frame between the run's +/// slices on its own, and it draws the documents as they were before the run until the run ends, +/// so there is nothing for the call to draw. It adds no undo step. +fn app_redraw(_: &Host, _: &[Data]) -> Answer { + Ok(Data::Undefined) +} + /// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is /// compared as text with the documents' files and is not resolved; a document whose file the /// automation read roots do not allow does not count, and that check can look the file up on disk. @@ -924,11 +961,19 @@ fn front_docs(s: &Session) -> impl Iterator { s.front_order().into_iter().map(|i| &s.documents()[i]) } -/// `documents[i]`, and `documents["name"]` as `getByName` reads it. +/// `documents[i]`, and `documents["name"]` as `getByName` reads it. A key that is the text of a +/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is +/// looked up as that name, giving `undefined` when no document has it. fn docs_at(h: &Host, a: &[Data]) -> Answer { let s = h.session.borrow(); let at = match arg(a, 1) { - Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)), + Data::Number(n) => match position(*n) { + Some(i) => front_docs(&s).nth(i), + None => { + let name = vectorcraft_js::number_to_string(*n); + front_docs(&s).find(|d| d.title() == name) + } + }, Data::String(name) => match front_docs(&s).find(|d| d.title() == *name) { None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())), found => found, @@ -948,10 +993,11 @@ fn docs_by_name(h: &Host, a: &[Data]) -> Answer { fn docs_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => docs_by_name(h, a), - Data::Number(_) => match docs_at(h, a)? { - Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), - d => Ok(d), - }, + Data::Number(n) => { + let s = h.session.borrow(); + let st = position(*n).and_then(|i| front_docs(&s).nth(i)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; + Ok(doc_ref(h, st.uid)) + } _ => Err(HostError::Type("give a name or an index".into())), } } @@ -1481,6 +1527,179 @@ fn doc_selection(h: &Host, a: &[Data]) -> Answer { selection_of(h, doc.uid) } +fn doc_views(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Views", &[float(h.run), float(doc.uid)])) +} + +// ---- Views and View ---- + +fn views_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Views") +} + +fn window_of(h: &Host, doc: Doc, id: u64) -> Option { + h.session.borrow().window_views.iter().find(|((uid, window), _)| *uid == doc.uid && *window == id).map(|(_, v)| *v) +} + +fn views_length(h: &Host, a: &[Data]) -> Answer { + let doc = views_doc(h, a)?; + Ok(num(h.session.borrow().window_views.iter().filter(|((uid, _), _)| *uid == doc.uid).count() as f64)) +} + +fn views_typename(h: &Host, a: &[Data]) -> Answer { + views_doc(h, a)?; + Ok(text("Views")) +} + +fn views_parent(h: &Host, a: &[Data]) -> Answer { + let doc = views_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn views_to_string(h: &Host, a: &[Data]) -> Answer { + views_doc(h, a)?; + Ok(text("[Views]")) +} + +fn views_at(h: &Host, a: &[Data]) -> Answer { + let doc = views_doc(h, a)?; + let index = match arg(a, 1) { + Data::Number(n) => whole(*n).and_then(|n| usize::try_from(n).ok()), + _ => None, + }; + let Some(index) = index else { return Ok(Data::Undefined) }; + let key = h.session.borrow().window_views.iter().filter(|((uid, _), _)| *uid == doc.uid).nth(index).map(|(key, _)| *key); + Ok(key.map_or(Data::Undefined, |(uid, id)| host_ref("View", &[float(h.run), float(uid), float(id)]))) +} + +/// `views.index(key)`: the view at index `key`. A view has no name, so a name finds nothing. +fn views_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => { + views_doc(h, a)?; + Err(HostError::Error(NOT_FOUND.into())) + } + Data::Number(_) => match views_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// The document of a `View` and its window, which must still be shown. +fn this_view(h: &Host, a: &[Data]) -> std::result::Result<(Doc, u64, WindowView), HostError> { + let Some(handle) = handle_of(arg(a, 0), "View") else { return Err(HostError::Type("this is not a View".into())) }; + let &[run, uid, id] = handle.as_slice() else { return Err(HostError::Type("this is not a View".into())) }; + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let id = whole(id).ok_or_else(|| HostError::Error(STALE_VIEW.into()))?; + let v = window_of(h, doc, id).ok_or_else(|| HostError::Error(STALE_VIEW.into()))?; + Ok((doc, id, v)) +} + +/// Reads the view with `f`, given the document's script coordinates. +fn read_view(h: &Host, a: &[Data], f: impl FnOnce(&Frame, Coords, &WindowView) -> Data) -> Answer { + let (doc, _, v) = this_view(h, a)?; + with_doc(h, doc, |_, st| Ok(f(&frame(st)?, h.dom.coords.get(), &v))) +} + +/// Changes the window of `doc` with `f`. No command runs: the change is not undoable, does not +/// join the run's undo step and stays when the run fails. +fn set_window(h: &Host, doc: Doc, id: u64, f: impl FnOnce(&mut WindowView)) -> Answer { + let mut s = h.session.borrow_mut(); + let v = s + .window_views + .iter_mut() + .find(|((uid, window), _)| *uid == doc.uid && *window == id) + .map(|(_, v)| v) + .ok_or_else(|| HostError::Error(STALE_VIEW.into()))?; + f(v); + Ok(Data::Undefined) +} + +fn view_typename(h: &Host, a: &[Data]) -> Answer { + this_view(h, a)?; + Ok(text("View")) +} + +fn view_parent(h: &Host, a: &[Data]) -> Answer { + let (doc, _, _) = this_view(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn view_to_string(h: &Host, a: &[Data]) -> Answer { + this_view(h, a)?; + Ok(text("[View]")) +} + +/// `bounds`: `[left, top, right, bottom]` of the part of the document the canvas shows. +fn view_bounds(h: &Host, a: &[Data]) -> Answer { + read_view(h, a, |f, c, v| f.bounds(c, v.visible())) +} + +fn view_center(h: &Host, a: &[Data]) -> Answer { + read_view(h, a, |f, c, v| pair(f.to_script(c, v.center))) +} + +fn view_set_center(h: &Host, a: &[Data]) -> Answer { + let (doc, id, _) = this_view(h, a)?; + let p = point(arg(a, 1), "centerPoint")?; + let to = with_doc(h, doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), p)))?; + if to.x.abs() > crate::MAX_COORD || to.y.abs() > crate::MAX_COORD { + return Err(HostError::Range("centerPoint is outside the canvas".into())); + } + set_window(h, doc, id, |v| v.center = to) +} + +fn view_zoom(h: &Host, a: &[Data]) -> Answer { + let (_, _, v) = this_view(h, a)?; + Ok(num(v.zoom)) +} + +fn view_set_zoom(h: &Host, a: &[Data]) -> Answer { + let (doc, id, v) = this_view(h, a)?; + let z = number(arg(a, 1), "zoom")?; + let (min, max) = v.zoom_range(); + if !(min..=max).contains(&z) { + return Err(HostError::Range(format!("zoom must be from {min} to {max}"))); + } + set_window(h, doc, id, |v| v.zoom = z) +} + +/// The `ScreenMode` value of each of the app's screen modes: Presentation Mode reads as +/// `FULLSCREEN`. +fn screen_mode_name(mode: u8) -> &'static str { + match mode { + 0 => "ScreenMode.MULTIWINDOW", + 1 => "ScreenMode.DESKTOP", + _ => "ScreenMode.FULLSCREEN", + } +} + +fn view_screen_mode(h: &Host, a: &[Data]) -> Answer { + let (_, _, v) = this_view(h, a)?; + Ok(text(screen_mode_name(v.screen_mode))) +} + +fn view_set_screen_mode(h: &Host, a: &[Data]) -> Answer { + let (_, _, v) = this_view(h, a)?; + let mode = match arg(a, 1) { + Data::String(s) if s == "ScreenMode.MULTIWINDOW" => 0, + Data::String(s) if s == "ScreenMode.DESKTOP" => 1, + Data::String(s) if s == "ScreenMode.FULLSCREEN" => 2, + _ => return Err(HostError::Type("give a ScreenMode value".into())), + }; + if screen_mode_name(v.screen_mode) == screen_mode_name(mode) { + return Ok(Data::Undefined); + } + // The screen mode is the app's, so every view shows the new one. + for (_, v) in &mut h.session.borrow_mut().window_views { + v.screen_mode = mode; + } + Ok(Data::Undefined) +} + /// The selection of the document `uid`: a new list of the selected objects, topmost first as /// `pageItems` lists them, empty when nothing is selected. fn selection_of(h: &Host, uid: u64) -> Answer { @@ -1620,27 +1839,49 @@ fn probing(a: &[Data]) -> bool { matches!(arg(a, 2), Data::Bool(true)) } -/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. +/// The position an indexer key names when it is an array index, 0 to 2^32 - 2. +fn position(n: f64) -> Option { + whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) +} + +/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a +/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is +/// looked up as that name, giving `undefined` when no object has it. fn items_at(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - if let Data::String(_) = arg(a, 1) { - return match items_by_name(h, a) { + match arg(a, 1) { + Data::String(_) => match items_by_name(h, a) { Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), r => r, - }; + }, + Data::Number(n) => match position(*n) { + Some(i) => Ok(item_at(h, doc, i)), + None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { + Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), + r => r, + }, + }, + _ => Ok(Data::Undefined), } - let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +/// The object at position `i` of `pageItems`, or `undefined` past the end. +fn item_at(h: &Host, doc: Doc, i: usize) -> Data { + with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))) } fn items_by_name(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + items_named(h, doc, name) +} + +/// The first object of `pageItems` named `name`, or `Not found`. +fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { with_doc(h, doc, |_, st| { let ids = page_items(h, st); h.charge_call(ids.len() as u64)?; - let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name)); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) } @@ -1648,10 +1889,13 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer { fn items_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => items_by_name(h, a), - Data::Number(_) => match items_at(h, a)? { - Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), - d => Ok(d), - }, + Data::Number(n) => { + let doc = items_doc(h, a)?; + match position(*n).map(|i| item_at(h, doc, i)) { + None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())), + Some(d) => Ok(d), + } + } _ => Err(HostError::Type("give a name or an index".into())), } } @@ -1838,6 +2082,56 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) } +/// The members of `BlendModes` with the blend mode each one names. +const BLEND_MODES: [(&str, BlendMode); 16] = [ + ("COLORBLEND", BlendMode::Color), + ("COLORBURN", BlendMode::ColorBurn), + ("COLORDODGE", BlendMode::ColorDodge), + ("DARKEN", BlendMode::Darken), + ("DIFFERENCE", BlendMode::Difference), + ("EXCLUSION", BlendMode::Exclusion), + ("HARDLIGHT", BlendMode::HardLight), + ("HUE", BlendMode::Hue), + ("LIGHTEN", BlendMode::Lighten), + ("LUMINOSITY", BlendMode::Luminosity), + ("MULTIPLY", BlendMode::Multiply), + ("NORMAL", BlendMode::Normal), + ("OVERLAY", BlendMode::Overlay), + ("SATURATIONBLEND", BlendMode::Saturation), + ("SCREEN", BlendMode::Screen), + ("SOFTLIGHT", BlendMode::SoftLight), +]; + +fn item_blending_mode(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| { + let name = BLEND_MODES.iter().find(|(_, m)| *m == n.blend).map_or("NORMAL", |(name, _)| name); + Ok(text(format!("BlendModes.{name}"))) + }) +} + +/// `blendingMode = BlendModes.`: the object's own blend mode, as `object.setProps` sets it. +/// The mode the object already has may be assigned while its layer is hidden or locked, unless it +/// would still replace the blend mode a graph keeps for the item's series or kind. +fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer { + let mode = match arg(a, 1) { + Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode), + _ => None, + }; + let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?; + let item = this_item(h, a)?; + let (same, keeps_other) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let same = d.node(item.id).is_some_and(|n| n.blend == mode); + let keeps_other = + crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]); + (same, keeps_other) + }); + if !same || keeps_other { + refuse_protected_edit(h, item)?; + } + set_props(h, a, |_| false, json!({"blend": mode.label()})) +} + fn item_selected(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)))) @@ -2034,7 +2328,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { } /// The error of `remove()` and `removeAll()` for an object on a locked artboard. -const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; +pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; @@ -2329,6 +2623,7 @@ const ENUMS: &[(&str, &[&str])] = &[ ("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]), ("DocumentColorSpace", &["CMYK", "RGB"]), ("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]), + ("ScreenMode", &["DESKTOP", "FULLSCREEN", "MULTIWINDOW"]), ("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]), ("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]), ("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]), @@ -2352,10 +2647,13 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { + text::install_enums(realm)?; for (name, members) in ENUMS { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect(); + realm.define_host_object("BlendModes", blend_modes)?; variables::define_enums(realm)?; realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?; let l = link; @@ -2378,10 +2676,13 @@ fn classes(link: &Link) -> Vec { ("selection", property(l, app_selection, app_set_selection), typed("*")), ("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")), ("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])), + ("redraw", method(l, app_redraw), returns("undefined", &[])), ("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])), ("toString", class_text("Application"), returns("string", &[])), ]); + application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") })); application.push(later(l, "Application", "beep")); + application.extend(super::actions::app_members(l)); let preset = { let l = link.clone(); let f: HostFunction = Rc::new(move |_: Vec| { @@ -2449,17 +2750,47 @@ fn classes(link: &Link) -> Vec { returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]), ), ("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }), + ("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }), + ("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }), ("selection", property(l, doc_selection, doc_set_selection), typed("*")), + ("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }), ("toString", method(l, doc_to_string), returns("string", &[])), ]); + document.extend(text::styles::doc_members(l)); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"] .into_iter() .map(|m| later(l, "Document", m)), ); document.extend(variables::document_members(l)); document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") })); classes.push(class("Document", None, document, None)); + classes.push(class( + "Views", + None, + named(vec![ + ("typename", get(l, views_typename), typed("string")), + ("length", get(l, views_length), typed("number")), + ("parent", get(l, views_parent), typed("Document")), + ("index", method(l, views_index), returns("View", &[("itemKey", "*")])), + ("toString", method(l, views_to_string), returns("string", &[])), + ]), + Some(function(l, views_at)), + )); + classes.push(class( + "View", + None, + named(vec![ + ("typename", get(l, view_typename), typed("string")), + ("parent", get(l, view_parent), typed("Views")), + ("bounds", get(l, view_bounds), typed("Array")), + ("centerPoint", property(l, view_center, view_set_center), typed("Array")), + ("zoom", property(l, view_zoom, view_set_zoom), typed("number")), + ("screenMode", property(l, view_screen_mode, view_set_screen_mode), typed("ScreenMode")), + ("toString", method(l, view_to_string), returns("string", &[])), + ]), + None, + )); classes.push(class( "PageItems", None, @@ -2484,6 +2815,7 @@ fn classes(link: &Link) -> Vec { ("locked", property(l, item_locked, item_set_locked), typed("boolean")), ("selected", property(l, item_selected, item_set_selected), typed("boolean")), ("opacity", property(l, item_opacity, item_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }), + ("blendingMode", property(l, item_blending_mode, item_set_blending_mode), typed("BlendModes")), ("position", property(l, item_position, item_set_position), typed("Array")), ("left", property(l, item_left, item_set_left), typed("number")), ("top", property(l, item_top, item_set_top), typed("number")), @@ -2509,7 +2841,6 @@ fn classes(link: &Link) -> Vec { page_item.extend( [ "artworkKnockout", - "blendingMode", "isIsolated", "layer", "pixelAligned", @@ -2530,7 +2861,8 @@ fn classes(link: &Link) -> Vec { ); page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(text::classes(l)); classes.extend(variables::classes(l)); classes.push(class( "Layer", diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs new file mode 100644 index 0000000000..998652b81c --- /dev/null +++ b/crates/engine/src/script/dom/text.rs @@ -0,0 +1,1841 @@ +//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its +//! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and +//! `paragraphAttributes`, and `app.textFonts`, as the help pages +//! , +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so +//! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves +//! out to the whole character. One item of `characters` is one code point. +//! - `contents` gives each paragraph break as `\r` and each forced line break as `\u0003`; written +//! text may use `\r`, `\n` or `\r\n` for a paragraph break. +//! - A word is a run of characters that are not white space. A paragraph ends after its break, and +//! a range's `words` and `paragraphs` are the whole words and paragraphs it touches. +//! - A range keeps its place while the script edits the frame through the object model: an edit +//! before it moves it, an edit over one of its ends takes that end to the edge of the edit's new +//! text, so a range the edit covers holds the new text, and an insertion at one of its ends joins +//! it. When a member finds the frame's text different from the text the model last saw, because +//! `vc.run` or an undo changed it, every range made before is stale and throws +//! `Stale text range`; a change reversed before that read leaves the ranges as they were. After +//! File › Revert every range made before is stale, even when the file read back holds the same +//! text. +//! - The model keeps the frame's last [`MAX_EDITS`] edits; a range made before an edit that is no +//! longer kept is stale. +//! - Setting a range's `length` moves its end and leaves the text as it is; each read of a member +//! that gives a range gives a new object. +//! - `add` on `characters`, `words` or `paragraphs` inserts after the collection's last item, and +//! `addBefore` before its first. An added word is kept apart from the characters next to it by a +//! space, and an added paragraph by a paragraph break. +//! - A character attribute read on a range whose characters differ gives the first character's +//! value; set on an empty range it changes nothing. A paragraph attribute reads the first +//! paragraph the range touches and sets every one of them. A text range has the members of +//! both its `characterAttributes` and its `paragraphAttributes`. + +use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, VecDeque}; +use std::rc::Rc; +use std::sync::{Arc, Weak}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref}; + +use super::{ + Answer, Described, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item, + editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, + returns, text, typed, typename_of, whole, with_doc, +}; +use crate::{DocState, Document, NodeId, NodeKind}; + +pub(super) mod styles; +pub(super) mod threads; + +/// The error of a text range, or of a collection of one, whose frame's text changed other than +/// through the object model. +pub const STALE_RANGE: &str = "Stale text range"; +/// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit +/// is stale. +const MAX_EDITS: usize = 100_000; + +/// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units. +pub(super) struct Index { + text: String, + /// The UTF-16 offset of each character's start, and the text's length last. + chars: Vec, + /// The byte offset of each character's start, and the text's length in bytes last. + bytes: Vec, + words: Vec<(usize, usize)>, + paras: Vec<(usize, usize)>, +} + +impl Index { + fn new(text: String) -> Self { + let mut chars = Vec::with_capacity(text.len() + 1); + let mut bytes = Vec::with_capacity(text.len() + 1); + let (mut words, mut paras) = (Vec::new(), Vec::new()); + let (mut u, mut word, mut para) = (0, None, 0); + for (b, c) in text.char_indices() { + chars.push(u); + bytes.push(b); + if c.is_whitespace() { + if let Some(w) = word.take() { + words.push((w, u)); + } + } else if word.is_none() { + word = Some(u); + } + u += c.len_utf16(); + if c == '\n' { + paras.push((para, u)); + para = u; + } + } + if let Some(w) = word { + words.push((w, u)); + } + paras.push((para, u)); + chars.push(u); + bytes.push(text.len()); + Self { text, chars, bytes, words, paras } + } + + fn len(&self) -> usize { + self.chars.last().copied().unwrap_or(0) + } + + /// The byte offset of UTF-16 offset `u`; inside a surrogate pair, the start of its character, + /// or with `up` the end of it. + fn byte(&self, u: usize, up: bool) -> usize { + let i = self.chars.partition_point(|&c| c < u); + match self.chars.get(i) { + Some(&c) if c == u || up => self.bytes.get(i).copied().unwrap_or(self.text.len()), + _ => i.checked_sub(1).and_then(|i| self.bytes.get(i)).copied().unwrap_or(0), + } + } + + /// The characters whose start is in `s..e`, each as a UTF-16 span. + fn chars_in(&self, s: usize, e: usize) -> std::ops::Range { + let count = self.chars.len().saturating_sub(1); + let a = self.chars[..count].partition_point(|&c| c < s); + let b = self.chars[..count].partition_point(|&c| c < e); + a..b.max(a) + } + + fn char_span(&self, i: usize) -> Option<(usize, usize)> { + Some((*self.chars.get(i)?, *self.chars.get(i + 1)?)) + } +} + +/// The words or paragraphs of `spans` that `s..e` touches: those it overlaps, or, for an empty +/// range, the one with a character at it, or the last one when it ends there. Only an empty range +/// touches the empty paragraph after a break at the end of the text. +fn touched(spans: &[(usize, usize)], s: usize, e: usize) -> std::ops::Range { + if s == e { + let i = spans.partition_point(|&(_, y)| y <= s); + if spans.get(i).is_some_and(|&(x, _)| x <= s) { + return i..i + 1; + } + return match spans.last() { + Some(&(_, y)) if i == spans.len() && y == s => i - 1..i, + _ => i..i, + }; + } + let a = spans.partition_point(|&(_, y)| y <= s); + let b = spans.partition_point(|&(x, _)| x < e); + a..b.max(a) +} + +#[derive(Clone, Copy)] +struct Edit { + stamp: u64, + at: usize, + removed: usize, + inserted: usize, +} + +/// What the object model knows of one frame's text: the document it was read from and its revert +/// count then, the text, the edits made through the model, and the oldest range generation still +/// valid. +struct Log { + doc: Weak, + reverts: u64, + index: Rc, + stamp: u64, + floor: u64, + edits: VecDeque, +} + +impl Log { + /// Records an edit the model made: `removed` units at `at` replaced by `inserted` units. Past + /// [`MAX_EDITS`] the oldest edit is dropped, and ranges made before it go stale. + fn push(&mut self, at: usize, removed: usize, inserted: usize) { + self.stamp += 1; + self.edits.push_back(Edit { stamp: self.stamp, at, removed, inserted }); + if self.edits.len() > MAX_EDITS + && let Some(dropped) = self.edits.pop_front() + { + self.floor = dropped.stamp; + } + } +} + +/// A document's uid, the document, and the ids of its type objects then. +type FrameList = (u64, Weak, Rc>); + +/// Word or paragraph spans, in UTF-16 units. +type Spans = [(usize, usize)]; + +/// The text state of one run. +#[derive(Default)] +pub(in crate::script) struct TextState { + frames: RefCell>, + /// A document's uid, the document, and the ids of its type objects, topmost first. + list: RefCell>, + /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character + /// names that is not installed is added at the end. + fonts: RefCell>>, + stories: threads::StoryState, + /// The number of text range objects made, which numbers the next one. + made: Cell, + /// The span of each range object, by its number, whose `length` the script set. + resized: RefCell>, + /// The styles the run's style objects name. + styles: styles::StyleState, +} + +fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { + match &st.doc.node(id)?.kind { + NodeKind::Text(t) => Some(t), + _ => None, + } +} + +fn same_text(t: &TextObject, s: &str) -> bool { + let mut rest = s; + for r in &t.runs { + match rest.strip_prefix(r.text.as_str()) { + Some(after) => rest = after, + None => return false, + } + } + rest.is_empty() +} + +/// The frame's index and its generation now, read again when its document changed. After File › +/// Revert every earlier range goes stale, even when the file read back holds the same text. +fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc, u64), HostError> { + let t = text_of(st, id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let mut frames = h.dom.text.frames.borrow_mut(); + let key = (st.uid, id.0); + let now = Arc::as_ptr(&st.doc); + match frames.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => {} + Some(l) => { + if l.reverts != st.reverts || !same_text(t, &l.index.text) { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + l.index = Rc::new(Index::new(t.plain_text())); + } + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + None => { + let l = Log { + doc: Arc::downgrade(&st.doc), + reverts: st.reverts, + index: Rc::new(Index::new(t.plain_text())), + stamp: 0, + floor: 0, + edits: VecDeque::new(), + }; + frames.insert(key, l); + } + } + let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok((l.index.clone(), l.stamp)) +} + +/// A text range: its frame, its span in UTF-16 units and the generation it was made at. +#[derive(Clone, Copy)] +struct Span { + item: Item, + start: usize, + end: usize, + stamp: u64, +} + +/// The span and index of `r` now. +fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u64), HostError> { + with_doc(h, r.item.doc, |_, st| { + let (index, stamp) = observe(h, st, r.item.id)?; + let frames = h.dom.text.frames.borrow(); + let l = frames.get(&(st.uid, r.item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + if r.stamp < l.floor || r.stamp > l.stamp { + return Err(HostError::Error(STALE_RANGE.into())); + } + let (mut s, mut e) = (r.start, r.end); + let from = l.edits.partition_point(|x| x.stamp <= r.stamp); + for x in l.edits.range(from..) { + let moved = |v: usize| v - x.removed + x.inserted; + s = if s <= x.at { + s + } else if s >= x.at + x.removed { + moved(s) + } else { + x.at + }; + // An end inside the removed text goes to the end of the new text. + e = if e < x.at || (e == x.at && x.removed > 0) { + e + } else if e >= x.at + x.removed { + moved(e) + } else { + x.at + x.inserted + }; + } + let len = index.len(); + let e = e.min(len); + Ok((index, s.min(e), e, stamp)) + }) +} + +/// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. +/// When the text is not what that edit gives, every earlier range goes stale. +fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let now = t.plain_text(); + let (a, b) = (before.byte(at, false), before.byte(at + removed, true)); + let expected = before.text.len() - (b - a) + inserted.len() == now.len() + && now.as_bytes().starts_with(&before.text.as_bytes()[..a]) + && now.as_bytes().ends_with(&before.text.as_bytes()[b..]) + && now.get(a..a + inserted.len()) == Some(inserted); + let mut frames = h.dom.text.frames.borrow_mut(); + let l = frames.get_mut(&(st.uid, item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + if expected && l.reverts == st.reverts { + l.push(at, removed, inserted.encode_utf16().count()); + } else { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + } + l.index = Rc::new(Index::new(now)); + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + Ok(()) + }) +} + +// ---- handles ---- + +fn usize_of(n: f64) -> Option { + whole(n).and_then(|v| usize::try_from(v).ok()) +} + +/// A new object of `class` for the span `s..e` of the frame `item` at generation `stamp`. Each +/// object is numbered, so setting one range's `length` leaves every other range as it is. The +/// first five numbers are the frame's page item handle, so a range goes stale with its frame, +/// after `file.revert` too. +fn range_ref(h: &Host, item: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data { + let [high, low] = id_parts(item.id); + let reverts = h.session.borrow().documents().get(item.doc.index).map_or(0, |d| d.reverts); + let made = &h.dom.text.made; + made.set(made.get() + 1); + host_ref( + class, + &[float(h.run), float(item.doc.uid), high, low, float(reverts), float(s as u64), float(e as u64), float(stamp), float(made.get())], + ) +} + +/// The span `d` names, when it is an object of one of `classes`. +fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result { + span_and_number(h, d, classes).map(|(span, _)| span) +} + +/// The span `d` names and the number of its object, when it is an object of one of `classes`. +fn span_and_number(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<(Span, u64), HostError> { + let handle = classes.iter().find_map(|c| handle_of(d, c)); + let Some(&[run, uid, high, low, reverts, s, e, stamp, number]) = handle.as_deref() else { + return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange")))); + }; + let frame = item_of(h, &host_ref("TextFrame", &[run, uid, high, low, reverts])).map_err(|_| HostError::Error(STALE_RANGE.into()))?; + let (Some(start), Some(end), Some(stamp), Some(number)) = (usize_of(s), usize_of(e), whole(stamp), whole(number)) else { + return Err(HostError::Error(STALE_RANGE.into())); + }; + let (start, end, stamp) = h.dom.text.resized.borrow().get(&number).copied().unwrap_or((start, end, stamp)); + Ok((Span { item: frame, start, end, stamp }, number)) +} + +/// The text frame `this` names. +fn this_frame(h: &Host, a: &[Data]) -> std::result::Result { + if handle_of(arg(a, 0), "TextFrame").is_none() { + return Err(HostError::Type("this is not a TextFrame".into())); + } + item_of(h, arg(a, 0)) +} + +/// The whole text of the frame as a span. +fn whole_span(h: &Host, item: Item) -> std::result::Result<(Rc, Span), HostError> { + with_doc(h, item.doc, |_, st| { + let (index, stamp) = observe(h, st, item.id)?; + let len = index.len(); + Ok((index, Span { item, start: 0, end: len, stamp })) + }) +} + +fn this_range(h: &Host, a: &[Data]) -> std::result::Result { + span_of(h, arg(a, 0), &["TextRange"]) +} + +/// Fails when `d` is not a text range, or is a stale one. +pub(super) fn check_range(h: &Host, d: &Data) -> std::result::Result<(), HostError> { + resolve(h, span_of(h, d, &["TextRange"])?).map(|_| ()) +} + +/// The span of `this`: a text range, or a text frame's whole text. +fn this_text(h: &Host, a: &[Data], class: &str) -> std::result::Result { + if handle_of(arg(a, 0), "TextFrame").is_some() { + return Ok(whole_span(h, item_of(h, arg(a, 0))?)?.1); + } + span_of(h, arg(a, 0), &[class]) +} + +// ---- contents ---- + +/// The model's text as `contents` gives it. +fn to_script(s: &str) -> String { + s.chars() + .map(|c| match c { + '\n' => '\r', + '\u{2028}' => '\u{3}', + c => c, + }) + .collect() +} + +/// Text a script wrote, as the model keeps it. +fn from_script(s: &str) -> String { + s.replace("\r\n", "\n") + .chars() + .map(|c| match c { + '\r' => '\n', + '\u{3}' => '\u{2028}', + c => c, + }) + .collect() +} + +fn read_contents(h: &Host, r: Span) -> Answer { + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + Ok(text(to_script(&index.text[a..b]))) +} + +/// The text a script gives as `contents`: a string, or a number as `String(number)` writes it. +fn contents_of(value: &Data) -> std::result::Result { + match value { + Data::String(v) => Ok(from_script(v)), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + _ => Err(HostError::Type("contents must be a string or a number".into())), + } +} + +/// Replaces the text of `r` with `value`, as one `text.editRange`. +fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { + let insert = contents_of(value)?; + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + if index.text[a..b] == insert { + return Ok(Data::Undefined); + } + let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); + edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; + record(h, r.item, &index, s, e - s, &insert)?; + Ok(Data::Undefined) +} + +fn frame_contents(h: &Host, a: &[Data]) -> Answer { + let (_, r) = whole_span(h, this_frame(h, a)?)?; + read_contents(h, r) +} + +fn frame_set_contents(h: &Host, a: &[Data]) -> Answer { + let (_, r) = whole_span(h, this_frame(h, a)?)?; + write_contents(h, r, arg(a, 1)) +} + +fn range_contents(h: &Host, a: &[Data]) -> Answer { + read_contents(h, this_range(h, a)?) +} + +fn range_set_contents(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_range(h, a)?, arg(a, 1)) +} + +// ---- TextFrame ---- + +fn frame_kind(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(text(match t.kind { + TextKind::Point => "TextType.POINTTEXT", + TextKind::Area { .. } => "TextType.AREATEXT", + TextKind::OnPath { .. } => "TextType.PATHTEXT", + })) + }) +} + +fn frame_orientation(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(text(if t.vertical { "TextOrientation.VERTICAL" } else { "TextOrientation.HORIZONTAL" })) + }) +} + +fn frame_range(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + let (_, r) = whole_span(h, item)?; + Ok(range_ref(h, item, r.start, r.end, r.stamp, "TextRange")) +} + +fn sub(h: &Host, a: &[Data], class: &str) -> Answer { + let r = this_text(h, a, "TextRange")?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, class)) +} + +fn characters(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Characters") +} + +fn words(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Words") +} + +fn paragraphs(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Paragraphs") +} + +fn character_attributes(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "CharacterAttributes") +} + +fn paragraph_attributes(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "ParagraphAttributes") +} + +/// The id a command's result, as the command gave it, holds under `ids` (the first) or `id`. It is +/// read from the JSON, where an id above 2^53 is still exact. +fn result_id(v: &Value) -> Option { + v.get("ids").and_then(|ids| ids.get(0)).or_else(|| v.get("id")).and_then(Value::as_u64).map(NodeId) +} + +fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { + let id = id.ok_or_else(|| HostError::Error("the command made no object".into()))?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, id)) +} + +/// `createOutline()`: Type › Create Outlines for the frame alone. → the group of outlines, or +/// `null` when the type has nothing to outline and the command removed it. +fn frame_outline(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + let (_, r) = on_doc(h, item.doc.uid, true, |h| { + command(h, "select.set", &json!({"ids": [item.id.0]}))?; + super::command_value(h, "type.createOutlines", &json!({})) + })?; + match result_id(&r) { + Some(id) => new_ref(h, item.doc, Some(id)), + None => Ok(Data::Null), + } +} + +/// Converts area type to point type (`area` false) or point type to area type. +fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { + let item = this_frame(h, a)?; + let kind_ok = with_doc(h, item.doc, |_, st| { + text_of(st, item.id).map(|t| if to_area { matches!(t.kind, TextKind::Point) } else { matches!(t.kind, TextKind::Area { .. }) }) + }); + match kind_ok { + None => return Err(HostError::Error(STALE_ITEM.into())), + Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))), + Some(true) => {} + } + let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" }; + let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?; + new_ref(h, item.doc, result_id(&r).or(Some(item.id))) +} + +fn frame_to_point(h: &Host, a: &[Data]) -> Answer { + convert(h, a, false) +} + +fn frame_to_area(h: &Host, a: &[Data]) -> Answer { + convert(h, a, true) +} + +// ---- TextRange ---- + +fn range_parent(h: &Host, a: &[Data]) -> Answer { + let r = this_range(h, a)?; + resolve(h, r)?; + Ok(with_doc(h, r.item.doc, |_, st| item_ref(h, st, r.item.id))) +} + +fn range_start(h: &Host, a: &[Data]) -> Answer { + let (_, s, _, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float(s as u64))) +} + +fn range_end(h: &Host, a: &[Data]) -> Answer { + let (_, _, e, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float(e as u64))) +} + +fn range_length(h: &Host, a: &[Data]) -> Answer { + let (_, s, e, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float((e - s) as u64))) +} + +/// Setting `length` moves the range's end to that many UTF-16 units after its start; the text +/// does not change. A length that is not a whole number from 0 to the units left in the frame +/// throws. +fn range_set_length(h: &Host, a: &[Data]) -> Answer { + let (r, number) = span_and_number(h, arg(a, 0), &["TextRange"])?; + let (index, s, _, stamp) = resolve(h, r)?; + let n = super::number(arg(a, 1), "length")?; + let left = index.len() - s; + let Some(n) = usize_of(n).filter(|n| *n <= left) else { + return Err(HostError::Range(format!("length must be a whole number from 0 to {left}"))); + }; + // An end inside a surrogate pair moves out to the end of its character. + let end = s + n; + let end = index.chars.get(index.chars.partition_point(|&c| c < end)).copied().unwrap_or(end); + h.dom.text.resized.borrow_mut().insert(number, (s, end, stamp)); + Ok(Data::Undefined) +} + +/// `remove()`: deletes the range's text. +fn range_remove(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_range(h, a)?, &text("")) +} + +/// `getParagraphLength()`: the length of the first paragraph the range touches, its break included. +fn range_paragraph_length(h: &Host, a: &[Data]) -> Answer { + let (index, s, e, _) = resolve(h, this_range(h, a)?)?; + let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x); + Ok(num(float(p as u64))) +} + +/// `getTextRunLength()`: the length from the range's start to the end of the run of characters +/// with one style it starts in, within the range. +fn range_run_length(h: &Host, a: &[Data]) -> Answer { + let r = this_range(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + let b = index.byte(s, false); + let run_end = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let mut at = 0; + for run in &t.runs { + at += run.text.len(); + if at > b { + return Ok(at); + } + } + Ok(at) + })?; + let u = index.text[..run_end.min(index.text.len())].encode_utf16().count(); + Ok(num(float((u.min(e).max(s) - s) as u64))) +} + +// ---- collections of a range ---- + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Part { + Characters, + Words, + Paragraphs, +} + +const PARTS: [(&str, Part); 3] = [("Characters", Part::Characters), ("Words", Part::Words), ("Paragraphs", Part::Paragraphs)]; + +fn part_of(d: &Data) -> Option { + PARTS.iter().find(|(c, _)| handle_of(d, c).is_some()).map(|(_, p)| *p) +} + +fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(Span, Part), HostError> { + let part = part_of(arg(a, 0)).ok_or_else(|| HostError::Type("this is not a collection of text".into()))?; + Ok((span_of(h, arg(a, 0), &["Characters", "Words", "Paragraphs"])?, part)) +} + +/// The spans of a collection, as a range of item numbers and the spans to look them up in. +fn part_spans(index: &Index, part: Part, s: usize, e: usize) -> (std::ops::Range, Option<&Spans>) { + match part { + Part::Characters => (index.chars_in(s, e), None), + Part::Words => (touched(&index.words, s, e), Some(&index.words)), + Part::Paragraphs => (touched(&index.paras, s, e), Some(&index.paras)), + } +} + +fn part_length(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + Ok(num(float(part_spans(&index, part, s, e).0.len() as u64))) +} + +fn part_parent(h: &Host, a: &[Data]) -> Answer { + let (r, _) = this_part(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, "TextRange")) +} + +fn part_at(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let (index, s, e, stamp) = resolve(h, r)?; + let (items, spans) = part_spans(&index, part, s, e); + let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) }; + let span = match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + Ok(span.map_or(Data::Undefined, |(x, y)| range_ref(h, r.item, x, y, stamp, "TextRange"))) +} + +/// Where `add` puts its text: before or after the relative object. +fn text_placement(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(true), + Data::String(s) if s == "ElementPlacement.PLACEBEFORE" || s == "ElementPlacement.PLACEATBEGINNING" => Ok(false), + Data::String(s) if s == "ElementPlacement.PLACEAFTER" || s == "ElementPlacement.PLACEATEND" => Ok(true), + _ => Err(HostError::Type("insertionLocation must be PLACEBEFORE, PLACEAFTER, PLACEATBEGINNING or PLACEATEND".into())), + } +} + +/// `add(contents, relativeObject?, insertionLocation?)` and, with `before`, `addBefore(contents)`: +/// inserts `contents` after the collection's last item (`addBefore`: before its first item), or +/// before or after `relativeObject`, a text range or text frame of the same frame, as one +/// `text.editRange`. A word gets a space on each side that touches another character that is not +/// white space; a paragraph gets a paragraph break on each side that touches another paragraph. +/// → the range of `contents`. +fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { + let (r, part) = this_part(h, a)?; + let contents = contents_of(arg(a, 1))?; + let (index, s, e, _) = resolve(h, r)?; + let at = if before || matches!(arg(a, 2), Data::Undefined) { + let (items, spans) = part_spans(&index, part, s, e); + let span = |k: usize| match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + if before { + items.clone().next().and_then(span).map_or(s, |(x, _)| x) + } else { + items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + } + } else { + let rel = arg(a, 2); + let target = if handle_of(rel, "TextFrame").is_some() { + whole_span(h, item_of(h, rel)?)?.1 + } else { + span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))? + }; + if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id { + return Err(HostError::Error("relativeObject must be text of the same text frame".into())); + } + let (_, ts, te, _) = resolve(h, target)?; + if text_placement(arg(a, 3))? { te } else { ts } + }; + if contents.is_empty() { + let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; + return Ok(range_ref(h, r.item, at, at, stamp, "TextRange")); + } + let b = index.byte(at, false); + let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next()); + let (lead, trail) = match part { + Part::Characters => ("", ""), + Part::Words => { + let apart = |c: Option| c.is_some_and(|c| !c.is_whitespace()); + let lead = if apart(prev) && !contents.starts_with(char::is_whitespace) { " " } else { "" }; + let trail = if apart(next) && !contents.ends_with(char::is_whitespace) { " " } else { "" }; + (lead, trail) + } + Part::Paragraphs => ( + if prev.is_some_and(|c| c != '\n') && !contents.starts_with('\n') { "\n" } else { "" }, + if next.is_some() && !contents.ends_with('\n') { "\n" } else { "" }, + ), + }; + let insert = format!("{lead}{contents}{trail}"); + edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; + record(h, r.item, &index, at, 0, &insert)?; + let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; + let start = at + lead.encode_utf16().count(); + Ok(range_ref(h, r.item, start, start + contents.encode_utf16().count(), stamp, "TextRange")) +} + +fn part_add_after(h: &Host, a: &[Data]) -> Answer { + part_add(h, a, false) +} + +fn part_add_before(h: &Host, a: &[Data]) -> Answer { + part_add(h, a, true) +} + +// ---- character attributes ---- + +#[derive(Clone, Copy)] +enum Attr { + Size, + Leading, + AutoLeading, + Tracking, + BaselineShift, + HorizontalScale, + VerticalScale, + Rotation, + Underline, + StrikeThrough, + TextFont, +} + +const ATTRS: [(&str, Attr); 11] = [ + ("size", Attr::Size), + ("leading", Attr::Leading), + ("autoLeading", Attr::AutoLeading), + ("tracking", Attr::Tracking), + ("baselineShift", Attr::BaselineShift), + ("horizontalScale", Attr::HorizontalScale), + ("verticalScale", Attr::VerticalScale), + ("rotation", Attr::Rotation), + ("underline", Attr::Underline), + ("strikeThrough", Attr::StrikeThrough), + ("textFont", Attr::TextFont), +]; + +/// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with +/// the paragraph they are in: one entry for each run and paragraph the range covers. For an empty +/// range, the style of the character before it, or of the first one. With `first`, only the first +/// entry. +fn styles_in(t: &TextObject, a: usize, b: usize, first: bool) -> std::result::Result, HostError> { + let mut out = Vec::new(); + let (mut at, mut para) = (0, 0); + let effective = |s: &CharStyle| t.effective_char_style(s).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into())); + for run in &t.runs { + let end = at + run.text.len(); + let bytes = run.text.as_bytes(); + let breaks = |from: usize, to: usize| bytes.get(from - at..to - at).map_or(0, |s| s.iter().filter(|&&c| c == b'\n').count()); + if a == b && at < a.max(1) && a <= end { + let lo = a.saturating_sub(1).max(at); + out.push((effective(&run.style)?, para + breaks(at, lo))); + break; + } + if a < end && at < b { + let (lo, hi) = (a.max(at), b.min(end)); + let style = effective(&run.style)?; + let mut p = para + breaks(at, lo); + out.push((style.clone(), p)); + if first { + return Ok(out); + } + for (k, _) in bytes.get(lo - at..hi - at).unwrap_or_default().iter().enumerate().filter(|&(_, &c)| c == b'\n') { + p += 1; + if lo + k + 1 < hi { + out.push((style.clone(), p)); + } + } + } + para += bytes.iter().filter(|&&c| c == b'\n').count(); + at = end; + } + if out.is_empty() + && let Some(r) = t.runs.first() + { + out.push((effective(&r.style)?, 0)); + } + Ok(out) +} + +/// The bytes in `a..b` whose characters have auto leading, each stretch with the leading its +/// characters' auto leading sets them with, in document points; touching stretches with the same +/// leading are one. +fn auto_leading_spans(t: &TextObject, a: usize, b: usize) -> std::result::Result, HostError> { + let mut out: Vec<(usize, usize, f64)> = Vec::new(); + let mut push = |from: usize, to: usize, leading: f64| match out.last_mut() { + Some(last) if last.1 == from && same(&num(last.2), &num(leading)) => last.1 = to, + _ => out.push((from, to, leading)), + }; + let (mut at, mut para) = (0, 0); + for run in &t.runs { + let end = at + run.text.len(); + let bytes = run.text.as_bytes(); + if a < end && at < b { + let style = t.effective_char_style(&run.style).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into()))?; + if style.leading.is_none() { + let (lo, hi) = (a.max(at), b.min(end)); + let auto = |p: usize| t.para_at(p).justification.auto_leading_for(style.size); + let mut p = para + bytes.get(..lo - at).unwrap_or_default().iter().filter(|&&c| c == b'\n').count(); + let mut from = lo; + for (k, _) in bytes.get(lo - at..hi - at).unwrap_or_default().iter().enumerate().filter(|&(_, &c)| c == b'\n') { + let to = lo + k + 1; + push(from, to, auto(p)); + p += 1; + from = to; + } + if from < hi { + push(from, hi, auto(p)); + } + } + } + para += bytes.iter().filter(|&&c| c == b'\n').count(); + at = end; + } + Ok(out) +} + +fn same(a: &Data, b: &Data) -> bool { + match (a, b) { + (Data::Number(x), Data::Number(y)) => (x - y).abs() < 1e-9, + _ => a == b, + } +} + +fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize) -> Data { + match attr { + Attr::Size => num(s.size), + Attr::Leading => num(s.leading.unwrap_or_else(|| t.para_at(para).justification.auto_leading_for(s.size))), + Attr::AutoLeading => Data::Bool(s.leading.is_none()), + Attr::Tracking => num(s.tracking), + Attr::BaselineShift => num(s.baseline_shift), + Attr::HorizontalScale => num(s.h_scale), + Attr::VerticalScale => num(s.v_scale), + Attr::Rotation => num(s.rotation), + Attr::Underline => Data::Bool(s.underline), + Attr::StrikeThrough => Data::Bool(s.strikethrough), + Attr::TextFont => font_ref(h, &s.font_family, &s.font_style), + } +} + +/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after. +fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> { + let finite = || number(v, name); + Ok(match attr { + Attr::Size => { + let n = finite()?; + if !(0.1..=1296.0).contains(&n) { + return Err(HostError::Range("size must be from 0.1 to 1296 points".into())); + } + (json!({"size": n}), num(n)) + } + Attr::Leading => { + let n = finite()?; + if !(0.1..=5000.0).contains(&n) { + return Err(HostError::Range("leading must be from 0.1 to 5000 points".into())); + } + (json!({"leading": n}), num(n)) + } + Attr::AutoLeading => { + if boolean(v, name)? { + (json!({"leading": "auto"}), Data::Bool(true)) + } else { + let (t, s, para) = first; + let n = s.leading.unwrap_or_else(|| t.para_at(para).justification.auto_leading_for(s.size)); + (json!({"leading": n}), Data::Bool(false)) + } + } + Attr::Tracking => { + let n = finite()?; + if !(-1000.0..=10_000.0).contains(&n) { + return Err(HostError::Range("tracking must be from -1000 to 10000".into())); + } + (json!({"tracking": n}), num(n)) + } + Attr::BaselineShift => { + let n = finite()?; + if n.abs() > 1296.0 { + return Err(HostError::Range("baselineShift must be from -1296 to 1296 points".into())); + } + (json!({"baselineShift": n}), num(n)) + } + Attr::HorizontalScale | Attr::VerticalScale => { + let n = finite()?; + if !(1.0..=10_000.0).contains(&n) { + return Err(HostError::Range(format!("{name} must be from 1 to 10000 percent"))); + } + let key = if matches!(attr, Attr::HorizontalScale) { "hScale" } else { "vScale" }; + (json!({ key: n }), num(n)) + } + Attr::Rotation => { + let n = finite()?; + if n.abs() > 360.0 { + return Err(HostError::Range("rotation must be from -360 to 360 degrees".into())); + } + (json!({"rotation": n}), num(n)) + } + Attr::Underline => { + let b = boolean(v, name)?; + (json!({"underline": b}), Data::Bool(b)) + } + Attr::StrikeThrough => { + let b = boolean(v, name)?; + (json!({"strikethrough": b}), Data::Bool(b)) + } + Attr::TextFont => { + let (family, style) = font_of(h, v)?; + (json!({"font": family, "style": style}), font_ref(h, &family, &style)) + } + }) +} + +/// The span of `this` for a character or paragraph attribute: a text range, its +/// `characterAttributes` or `paragraphAttributes`, or a text frame's whole text. +fn attr_span(h: &Host, a: &[Data], class: &str) -> std::result::Result { + if handle_of(arg(a, 0), "TextRange").is_some() { + return this_range(h, a); + } + this_text(h, a, class) +} + +fn read_attr(h: &Host, a: &[Data], attr: Attr) -> Answer { + let r = attr_span(h, a, "CharacterAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (ba, bb) = (index.byte(s, false), index.byte(e, true)); + with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(styles_in(t, ba, bb, true)?.first().map_or(Data::Undefined, |(st, p)| attr_value(h, attr, t, st, *p))) + }) +} + +fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { + let r = attr_span(h, a, "CharacterAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (ba, bb) = (index.byte(s, false), index.byte(e, true)); + let (param, unchanged, fixed) = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let styles = styles_in(t, ba, bb, false)?; + let first = styles.first().map(|(s, p)| (s.clone(), *p)).unwrap_or_else(|| (CharStyle::default(), 0)); + let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; + // A leading set on characters with auto leading fixes it even where auto gives that value. + let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants); + let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p)); + let fixed = match (attr, &wants) { + (Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?), + _ => None, + }; + if let Some(bad) = fixed.iter().flatten().map(|(_, _, l)| *l).find(|l| !(0.1..=5000.0).contains(l)) { + return Err(HostError::Range(format!("autoLeading cannot be turned off: the auto leading here is {bad} points, outside 0.1 to 5000"))); + } + Ok::<_, HostError>((param, unchanged, fixed)) + })?; + if unchanged { + return Ok(Data::Undefined); + } + if let Some(spans) = fixed { + // Each character with auto leading keeps the leading it is set with now. + super::atomically(h, |h| { + for (start, end, leading) in &spans { + let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading}); + edit_item(h, r.item, "text.setRangeStyle", &p)?; + } + Ok(()) + })?; + return Ok(Data::Undefined); + } + let mut p = param; + if let Some(o) = p.as_object_mut() { + o.insert("id".into(), json!(r.item.id.0)); + o.insert("start".into(), json!(ba)); + o.insert("end".into(), json!(bb)); + } + let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?; + if let Attr::TextFont = attr { + let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?; + } + Ok(Data::Undefined) +} + +/// Fails, after the font is set, when `text.setRangeStyle` warned that the font is not available +/// or when characters in bytes `a..b` kept another font because Missing Glyph Protection is on. +fn font_applied(h: &Host, item: Item, (a, b): (usize, usize), (family, style): (&str, &str), answer: &Data) -> std::result::Result<(), HostError> { + if let Data::Object(o) = answer + && let Some((_, Data::String(w))) = o.iter().find(|(k, _)| k == "warning") + { + return Err(HostError::Error(format!("textFont: {w}"))); + } + let kept = with_doc(h, item.doc, |_, st| { + let Some(t) = text_of(st, item.id) else { return 0 }; + let mut at = 0; + let mut kept = 0; + for run in &t.runs { + let end = at + run.text.len(); + let other = !run.style.font_family.eq_ignore_ascii_case(family) || !run.style.font_style.eq_ignore_ascii_case(style); + if other && a < end && at < b { + kept += run.text.get(a.max(at) - at..b.min(end) - at).map_or(0, |s| s.chars().count()); + } + at = end; + } + kept + }); + if kept > 0 { + let noun = if kept == 1 { "character, which keeps its" } else { "characters, which keep their" }; + return Err(HostError::Error(format!("textFont: the font has no glyph for {kept} {noun} font because Missing Glyph Protection is on"))); + } + Ok(()) +} + +// ---- paragraph attributes ---- + +#[derive(Clone, Copy)] +enum ParaAttr { + Justification, + FirstLineIndent, + LeftIndent, + RightIndent, + SpaceBefore, + SpaceAfter, +} + +const PARA_ATTRS: [(&str, ParaAttr); 6] = [ + ("justification", ParaAttr::Justification), + ("firstLineIndent", ParaAttr::FirstLineIndent), + ("leftIndent", ParaAttr::LeftIndent), + ("rightIndent", ParaAttr::RightIndent), + ("spaceBefore", ParaAttr::SpaceBefore), + ("spaceAfter", ParaAttr::SpaceAfter), +]; + +const JUSTIFICATIONS: [(&str, &str); 7] = [ + ("LEFT", "left"), + ("CENTER", "center"), + ("RIGHT", "right"), + ("FULLJUSTIFYLASTLINELEFT", "justifyLeft"), + ("FULLJUSTIFYLASTLINECENTER", "justifyCenter"), + ("FULLJUSTIFYLASTLINERIGHT", "justifyRight"), + ("FULLJUSTIFY", "justifyAll"), +]; + +/// The text of paragraph `i` of `index`, its break included. +fn para_text(index: &Index, i: usize) -> &str { + index.paras.get(i).and_then(|&(x, y)| index.text.get(index.byte(x, false)..index.byte(y, false))).unwrap_or_default() +} + +/// The value of `attr` in paragraph `i` of `t`, whose text `index` holds. Auto alignment reads as +/// the side it aligns to: right in a right-to-left paragraph, left otherwise. +fn para_value(attr: ParaAttr, t: &TextObject, index: &Index, i: usize) -> Data { + let p = t.para_at(i); + match attr { + ParaAttr::Justification => text(format!( + "Justification.{}", + match p.justify { + Justify::Auto if vectorcraft_text::paragraph_is_rtl(para_text(index, i), p.direction) => "RIGHT", + Justify::Auto | Justify::Left => "LEFT", + Justify::Center => "CENTER", + Justify::Right => "RIGHT", + Justify::JustifyLeft => "FULLJUSTIFYLASTLINELEFT", + Justify::JustifyCenter => "FULLJUSTIFYLASTLINECENTER", + Justify::JustifyRight => "FULLJUSTIFYLASTLINERIGHT", + Justify::JustifyAll => "FULLJUSTIFY", + } + )), + ParaAttr::FirstLineIndent => num(p.first_line_indent), + ParaAttr::LeftIndent => num(p.left_indent), + ParaAttr::RightIndent => num(p.right_indent), + ParaAttr::SpaceBefore => num(p.space_before), + ParaAttr::SpaceAfter => num(p.space_after), + } +} + +/// The command and parameter that set `attr` to `v`, and the value it reads as after. +fn para_param(attr: ParaAttr, name: &str, v: &Data) -> std::result::Result<(&'static str, Value, Data), HostError> { + if let ParaAttr::Justification = attr { + let found = match v { + Data::String(s) => s.strip_prefix("Justification.").and_then(|m| JUSTIFICATIONS.iter().find(|(k, _)| *k == m)), + _ => None, + }; + let (_, value) = found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?; + return Ok(("text.setStyle", json!({"justify": value}), v.clone())); + } + let n = number(v, name)?; + if n.abs() > 1296.0 { + return Err(HostError::Range(format!("{name} must be from -1296 to 1296 points"))); + } + let key = match attr { + ParaAttr::FirstLineIndent => "firstLineIndent", + ParaAttr::LeftIndent => "leftIndent", + ParaAttr::RightIndent => "rightIndent", + ParaAttr::SpaceBefore => "spaceBefore", + _ => "spaceAfter", + }; + Ok(("text.setFormat", json!({ key: n }), num(n))) +} + +/// The paragraphs a range touches, by number, and the bytes from the first one's start to the last +/// one's start, which select exactly those paragraphs for `text.setFormat` and `text.setStyle`. +fn para_range(index: &Index, s: usize, e: usize) -> (std::ops::Range, usize, usize) { + let paras = touched(&index.paras, s, e); + let start = |i: usize| index.paras.get(i).map_or(index.text.len(), |&(x, _)| index.byte(x, false)); + let (ba, bb) = (start(paras.start), start(paras.end.saturating_sub(1).max(paras.start))); + (paras, ba, bb) +} + +fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer { + let r = attr_span(h, a, "ParagraphAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (paras, _, _) = para_range(&index, s, e); + with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(para_value(attr, t, &index, paras.start)) + }) +} + +fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { + let r = attr_span(h, a, "ParagraphAttributes")?; + let (id, param, wants) = para_param(attr, name, arg(a, 1))?; + let (index, s, e, _) = resolve(h, r)?; + let (paras, ba, bb) = para_range(&index, s, e); + let unchanged = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + // An explicit alignment replaces Auto even where Auto aligns to the same side. + let auto = |i: usize| matches!(attr, ParaAttr::Justification) && t.para_at(i).justify == Justify::Auto; + Ok::<_, HostError>(paras.clone().all(|i| !auto(i) && same(¶_value(attr, t, &index, i), &wants))) + })?; + if unchanged { + return Ok(Data::Undefined); + } + let mut p = param; + if let Some(o) = p.as_object_mut() { + o.insert("id".into(), json!(r.item.id.0)); + o.insert("start".into(), json!(ba)); + o.insert("end".into(), json!(bb)); + } + edit_item(h, r.item, id, &p)?; + Ok(Data::Undefined) +} + +// ---- TextFrames ---- + +fn doc_text_frames_impl(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("TextFrames", &[float(h.run), float(doc.uid)])) +} + +/// `document.textFrames`. +pub(super) fn doc_text_frames(link: &Link) -> HostMember { + get(link, doc_text_frames_impl) +} + +/// The ids of the document's type objects, topmost first as `pageItems` lists them, kept while the +/// document is unchanged. +fn frame_ids(h: &Host, st: &DocState) -> Rc> { + if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow() + && *uid == st.uid + && std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc)) + { + return ids.clone(); + } + let ids: Vec = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect(); + let ids = Rc::new(ids); + *h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone())); + ids +} + +fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "TextFrames") +} + +fn frames_length(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64))) +} + +fn frames_parent(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn frames_at(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn frames_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = frame_ids(h, st); + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn frames_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => frames_by_name(h, a), + Data::Number(_) => match frames_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `TextOrientation` as `text.create`'s `vertical`, `undefined` horizontal. +fn vertical_of(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(false), + Data::String(s) if s == "TextOrientation.HORIZONTAL" => Ok(false), + Data::String(s) if s == "TextOrientation.VERTICAL" => Ok(true), + _ => Err(HostError::Type("orientation must be a TextOrientation value".into())), + } +} + +/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`. +fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer { + let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?; + let (_, r) = + on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; + new_ref(h, doc, result_id(&r)) +} + +/// `add()`: empty point type at the origin. +fn frames_add(h: &Host, a: &[Data]) -> Answer { + point_text(h, frames_doc(h, a)?, None, false) +} + +/// `pointText(anchor, orientation?)`. +fn frames_point_text(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let anchor = point(arg(a, 1), "anchor")?; + point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?) +} + +/// Turns the path `d` names into area type or type on a path with `text.createInPath`. +fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { + let doc = frames_doc(h, a)?; + if handle_of(arg(a, 1), "PathItem").is_none() { + return Err(HostError::Type("textPath must be a PathItem".into())); + } + let path = item_of(h, arg(a, 1))?; + if path.doc.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { + return Err(HostError::Error("TextFrames: path positions are not available yet".into())); + } + let (orientation, base) = if on_path { (4, 5) } else { (2, 3) }; + let vertical = vertical_of(arg(a, orientation))?; + let base = threads::base_frame(h, doc, arg(a, base), arg(a, base + 1))?; + if base.is_some() { + threads::check_base_path(h, path)?; + } + let mode = if on_path { "onPath" } else { "area" }; + let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical}); + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; + let id = result_id(&r); + if let (Some((base, postfix)), Some(id)) = (base, id) { + threads::thread_new(h, base, id, postfix)?; + } + new_ref(h, doc, id) +} + +/// `areaText(textPath, orientation?, baseFrame?, postFix?)`. +fn frames_area_text(h: &Host, a: &[Data]) -> Answer { + in_path(h, a, false, &[]) +} + +/// `pathText(textPath, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)`. +fn frames_path_text(h: &Host, a: &[Data]) -> Answer { + in_path(h, a, true, &[2, 3]) +} + +/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a +/// locked artboard, stops it first, as `PageItems.removeAll()` does. +fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let ids = frame_ids(h, st); + let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) + }); + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); + } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- fonts ---- + +/// The run's font list, read once. +fn with_fonts(h: &Host, f: impl FnOnce(&mut Vec<(String, String)>) -> T) -> T { + let mut fonts = h.dom.text.fonts.borrow_mut(); + let list = fonts.get_or_insert_with(|| { + let db = vectorcraft_text::FontDb::global(); + let mut v = Vec::new(); + for family in db.menu_family_list().iter() { + for style in db.styles(family) { + v.push((family.clone(), style)); + } + } + v + }); + f(list) +} + +/// A `TextFont` for `family` and `style`, added to the run's list when it is not there. +fn font_ref(h: &Host, family: &str, style: &str) -> Data { + let i = with_fonts(h, |list| match list.iter().position(|(f, s)| f.eq_ignore_ascii_case(family) && s.eq_ignore_ascii_case(style)) { + Some(i) => i, + None => { + list.push((family.to_string(), style.to_string())); + list.len() - 1 + } + }); + host_ref("TextFont", &[float(h.run), float(i as u64)]) +} + +/// The family and style of the `TextFont` `d`. +fn font_of(h: &Host, d: &Data) -> std::result::Result<(String, String), HostError> { + let Some(&[run, i]) = handle_of(d, "TextFont").as_deref() else { return Err(HostError::Type("textFont must be a TextFont".into())) }; + if whole(run) != Some(h.run) { + return Err(HostError::Error("Stale text font".into())); + } + usize_of(i).and_then(|i| with_fonts(h, |list| list.get(i).cloned())).ok_or_else(|| HostError::Error("Stale text font".into())) +} + +fn fonts_length(h: &Host, _: &[Data]) -> Answer { + Ok(num(float(with_fonts(h, |l| l.len()) as u64))) +} + +fn fonts_at(h: &Host, a: &[Data]) -> Answer { + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let found = with_fonts(h, |l| i < l.len()); + Ok(if found { host_ref("TextFont", &[float(h.run), float(i as u64)]) } else { Data::Undefined }) +} + +/// `textFonts.getByName(name)`: the PostScript name of a bundled or installed face, then the family +/// and style with a space. +fn fonts_by_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + if name.len() > super::MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let named = vectorcraft_text::FontDb::global().find_postscript(name).map(|f| (f.family.clone(), f.style.clone())); + let i = with_fonts(h, |l| { + h.charge_call(l.len() as u64)?; + let by_ps = named.as_ref().and_then(|(f, s)| l.iter().position(|(lf, ls)| lf.eq_ignore_ascii_case(f) && ls.eq_ignore_ascii_case(s))); + Ok::<_, HostError>(by_ps.or_else(|| l.iter().position(|(f, s)| format!("{f} {s}").eq_ignore_ascii_case(name)))) + })?; + match (i, named) { + (Some(i), _) => Ok(host_ref("TextFont", &[float(h.run), float(i as u64)])), + (None, Some((family, style))) => Ok(font_ref(h, &family, &style)), + (None, None) => Err(HostError::Error(NOT_FOUND.into())), + } +} + +fn fonts_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => fonts_by_name(h, a), + Data::Number(_) => match fonts_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +fn font_family(h: &Host, a: &[Data]) -> Answer { + Ok(text(font_of(h, arg(a, 0))?.0)) +} + +fn font_style(h: &Host, a: &[Data]) -> Answer { + Ok(text(font_of(h, arg(a, 0))?.1)) +} + +/// The font's PostScript name, or its family and style joined by a hyphen when the font is not +/// installed. +fn font_name(h: &Host, a: &[Data]) -> Answer { + let (family, style) = font_of(h, arg(a, 0))?; + let face = vectorcraft_text::FontDb::global().face(&family, &style); + Ok(text(face.map_or_else(|| format!("{family}-{style}").replace(' ', ""), |f| f.postscript_name()))) +} + +fn app_text_fonts_impl(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("TextFonts", &[])) +} + +/// `app.textFonts`. +pub(super) fn app_text_fonts(link: &Link) -> HostMember { + get(link, app_text_fonts_impl) +} + +fn app_ref(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Application", &[])) +} + +/// A font's `parent`, `app`, once the font is checked. +fn font_parent(h: &Host, a: &[Data]) -> Answer { + font_of(h, arg(a, 0))?; + Ok(host_ref("Application", &[])) +} + +// ---- classes ---- + +fn range_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, this_range(h, a)?)?; + Ok(text("TextRange")) +} + +fn part_typename(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + resolve(h, r)?; + Ok(text(PARTS.iter().find(|(_, p)| *p == part).map_or("Characters", |(c, _)| c))) +} + +fn char_attrs_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, span_of(h, arg(a, 0), &["CharacterAttributes"])?)?; + Ok(text("CharacterAttributes")) +} + +fn para_attrs_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, span_of(h, arg(a, 0), &["ParagraphAttributes"])?)?; + Ok(text("ParagraphAttributes")) +} + +fn frames_typename(h: &Host, a: &[Data]) -> Answer { + frames_doc(h, a)?; + Ok(text("TextFrames")) +} + +fn font_typename(h: &Host, a: &[Data]) -> Answer { + font_of(h, arg(a, 0))?; + Ok(text("TextFont")) +} + +/// A member listed on the help pages that a script cannot set yet. Assigning it throws, after the +/// read's own checks of `this`. +fn read_only(link: &Link, g: super::Member, class: &'static str, name: &'static str) -> HostMember { + let message = format!("{class}.{name} cannot be set yet"); + let get = function(link, g); + let read = get.clone(); + HostMember::Property { + get, + set: Rc::new(move |a: Vec| { + read(a.into_iter().take(1).collect())?; + Err(HostError::Error(message.clone())) + }), + } +} + +/// The type `reflect` gives for character attribute `attr`. +fn attr_type(attr: Attr) -> &'static str { + match attr { + Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", + Attr::TextFont => "TextFont", + _ => "number", + } +} + +/// The type `reflect` gives for paragraph attribute `attr`. +fn para_type(attr: ParaAttr) -> &'static str { + match attr { + ParaAttr::Justification => "Justification", + _ => "number", + } +} + +fn attr_members(link: &Link) -> Vec { + let mut out = Vec::new(); + for (name, attr) in ATTRS { + let l = link.clone(); + let g: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + read_attr(&h, &a, attr) + }); + let l = link.clone(); + let s: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write_attr(&h, &a, attr, name) + }); + out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(attr_type(attr)))); + } + out +} + +fn para_members(link: &Link) -> Vec { + let mut out = Vec::new(); + for (name, attr) in PARA_ATTRS { + let l = link.clone(); + let g: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + read_para(&h, &a, attr) + }); + let l = link.clone(); + let s: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write_para(&h, &a, attr, name) + }); + out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(para_type(attr)))); + } + out +} + +/// The enumerations type uses. +const ENUMS: &[(&str, &[&str])] = &[ + ("TextType", &["AREATEXT", "PATHTEXT", "POINTTEXT"]), + ("TextOrientation", &["HORIZONTAL", "VERTICAL"]), + ( + "Justification", + &["CENTER", "FULLJUSTIFY", "FULLJUSTIFYLASTLINECENTER", "FULLJUSTIFYLASTLINELEFT", "FULLJUSTIFYLASTLINERIGHT", "LEFT", "RIGHT"], + ), +]; + +/// Adds the enumerations type uses to `realm`. +pub(super) fn install_enums(realm: &mut Realm) -> std::result::Result<(), RunError> { + for (name, members) in ENUMS { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } + Ok(()) +} + +/// The classes of type, `TextFrame` among them, which inherits from `PageItem`. +pub(super) fn classes(l: &Link) -> Vec { + let collection = |t: &str| MemberInfo { collection: true, ..typed(t) }; + let mut frame = named(vec![ + ("kind", get(l, frame_kind), typed("TextType")), + ("contents", property(l, frame_contents, frame_set_contents), typed("string")), + ("textRange", get(l, frame_range), typed("TextRange")), + ("characters", get(l, characters), collection("Characters")), + ("words", get(l, words), collection("Words")), + ("paragraphs", get(l, paragraphs), collection("Paragraphs")), + ("orientation", read_only(l, frame_orientation, "TextFrame", "orientation"), typed("TextOrientation")), + ("createOutline", method(l, frame_outline), returns("GroupItem", &[])), + ("convertAreaObjectToPointObject", method(l, frame_to_point), returns("TextFrame", &[])), + ("convertPointObjectToAreaObject", method(l, frame_to_area), returns("TextFrame", &[])), + ]); + frame.extend(super::variables::item_members(l, "TextFrame")); + frame.extend(threads::frame_members(l)); + frame.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "textPath", + "anchor", + "antialias", + "columnCount", + "columnGutter", + "rowCount", + "rowGutter", + "startTValue", + "endTValue", + "opticalAlignment", + "matrix", + "textSelection", + ] + .into_iter() + .map(|m| super::later(l, "TextFrame", m)), + ); + let mut range = named(vec![ + ("typename", get(l, range_typename), typed("string")), + ("parent", get(l, range_parent), typed("*")), + ("contents", property(l, range_contents, range_set_contents), typed("string")), + ("start", read_only(l, range_start, "TextRange", "start"), typed("number")), + ("end", read_only(l, range_end, "TextRange", "end"), typed("number")), + ("characterOffset", read_only(l, range_start, "TextRange", "characterOffset"), typed("number")), + ("length", property(l, range_length, range_set_length), typed("number")), + ("characters", get(l, characters), collection("Characters")), + ("words", get(l, words), collection("Words")), + ("paragraphs", get(l, paragraphs), collection("Paragraphs")), + ("characterAttributes", get(l, character_attributes), typed("CharacterAttributes")), + ("paragraphAttributes", get(l, paragraph_attributes), typed("ParagraphAttributes")), + ("getParagraphLength", method(l, range_paragraph_length), returns("number", &[("charIndex", "number")])), + ("getTextRunLength", method(l, range_run_length), returns("number", &[("charIndex", "number")])), + ("remove", method(l, range_remove), returns("undefined", &[])), + ]); + range.extend(attr_members(l)); + range.push(threads::range_member(l)); + range.extend(para_members(l)); + range.extend(styles::range_members(l)); + range.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "kerning", + "textSelection", + "changeCaseTo", + "select", + "deSelect", + "duplicate", + "move", + "getLocalCharOverridesJSON", + "getLocalParaOverridesJSON", + ] + .into_iter() + .map(|m| super::later(l, "TextRange", m)), + ); + let part = |name: &'static str| { + class( + name, + None, + named(vec![ + ("typename", get(l, part_typename), typed("string")), + ("length", get(l, part_length), typed("number")), + ("parent", get(l, part_parent), typed("TextRange")), + ("add", method(l, part_add_after), returns("TextRange", &[("contents", "string"), ("relativeObject", "TextRange")])), + ("addBefore", method(l, part_add_before), returns("TextRange", &[("contents", "string")])), + ]), + Some(function(l, part_at)), + ) + }; + let mut chars = named(vec![("typename", get(l, char_attrs_typename), typed("string"))]); + chars.extend(attr_members(l)); + let mut paras = named(vec![("typename", get(l, para_attrs_typename), typed("string"))]); + paras.extend(para_members(l)); + let stories = threads::classes(l); + let mut out = vec![ + class("TextFrame", Some("PageItem"), frame, None), + class("TextRange", None, range, None), + part("Characters"), + part("Words"), + part("Paragraphs"), + class("CharacterAttributes", None, chars, None), + class("ParagraphAttributes", None, paras, None), + class( + "TextFrames", + None, + named(vec![ + ("typename", get(l, frames_typename), typed("string")), + ("length", get(l, frames_length), typed("number")), + ("parent", get(l, frames_parent), typed("Document")), + ("index", method(l, frames_index), returns("number", &[("itemKey", "*")])), + ("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])), + ("add", method(l, frames_add), returns("TextFrame", &[])), + ("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])), + ( + "areaText", + method(l, frames_area_text), + returns("TextFrame", &[("textPath", "PathItem"), ("orientation", "TextOrientation"), ("baseFrame", "TextFrame")]), + ), + ( + "pathText", + method(l, frames_path_text), + returns( + "TextFrame", + &[ + ("textPath", "PathItem"), + ("startTValue", "number"), + ("endTValue", "number"), + ("orientation", "TextOrientation"), + ("baseFrame", "TextFrame"), + ], + ), + ), + ("removeAll", method(l, frames_remove_all), returns("undefined", &[])), + ]), + Some(function(l, frames_at)), + ), + class( + "TextFonts", + None, + named(vec![ + ("typename", typename_of("TextFonts"), typed("string")), + ("length", get(l, fonts_length), typed("number")), + ("parent", get(l, app_ref), typed("Application")), + ("index", method(l, fonts_index), returns("number", &[("itemKey", "*")])), + ("getByName", method(l, fonts_by_name), returns("TextFont", &[("name", "string")])), + ]), + Some(function(l, fonts_at)), + ), + class( + "TextFont", + None, + named(vec![ + ("typename", get(l, font_typename), typed("string")), + ("name", get(l, font_name), typed("string")), + ("family", get(l, font_family), typed("string")), + ("style", get(l, font_style), typed("string")), + ("parent", get(l, font_parent), typed("Application")), + ]), + None, + ), + ]; + out.extend(styles::classes(l)); + out.extend(stories); + out +} + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::rc::Rc; + use std::sync::Weak; + + use super::{Index, Log, MAX_EDITS, touched}; + + #[test] + fn the_edit_log_keeps_the_last_edits_and_drops_only_older_ones() { + let mut l = Log { doc: Weak::new(), reverts: 0, index: Rc::new(Index::new(String::new())), stamp: 0, floor: 0, edits: VecDeque::new() }; + for _ in 0..MAX_EDITS { + l.push(0, 0, 1); + } + assert_eq!((l.edits.len(), l.floor), (MAX_EDITS, 0)); + l.push(0, 0, 1); + // Only the first edit is dropped: a range made after it still moves through every later edit. + assert_eq!((l.edits.len(), l.floor), (MAX_EDITS, 1)); + assert_eq!(l.edits.front().map(|x| x.stamp), Some(2)); + } + + #[test] + fn index_counts_utf16_units_and_splits_words_and_paragraphs() { + let i = Index::new("a\u{1F600}b c\nd".into()); + assert_eq!(i.len(), 8); + assert_eq!(i.chars, vec![0, 1, 3, 4, 5, 6, 7, 8]); + assert_eq!(i.byte(2, false), 1); + assert_eq!(i.byte(2, true), 5); + assert_eq!(i.words, vec![(0, 4), (5, 6), (7, 8)]); + assert_eq!(i.paras, vec![(0, 7), (7, 8)]); + assert_eq!(i.chars_in(1, 4), 1..3); + } + + #[test] + fn only_an_empty_range_touches_the_empty_paragraph_at_the_end() { + let i = Index::new("a\n".into()); + assert_eq!(i.paras, vec![(0, 2), (2, 2)]); + assert_eq!(touched(&i.paras, 0, 2), 0..1); + assert_eq!(touched(&i.paras, 0, 1), 0..1); + assert_eq!(touched(&i.paras, 2, 2), 1..2); + assert_eq!(touched(&i.paras, 1, 1), 0..1); + let e = Index::new(String::new()); + assert_eq!(touched(&e.paras, 0, 0), 0..1); + assert_eq!(touched(&e.words, 0, 0), 0..0); + } +} diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs new file mode 100644 index 0000000000..8317e1ae04 --- /dev/null +++ b/crates/engine/src/script/dom/text/styles.rs @@ -0,0 +1,802 @@ +//! Character and paragraph styles in the script object model: `document.characterStyles` and +//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text +//! of a `TextRange` uses, as the help pages +//! , +//! , +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A document's collection lists its Normal style first, then its other styles in the order the +//! panel lists them. +//! - A style object names its style for the rest of the run, also after the script renames it +//! through `name`. Once the style is removed, or renamed or removed other than through the object +//! model, or its document is closed or reverted with File › Revert, every member throws +//! `Stale style`; a style added later under the same name is another style. +//! - A style name is trimmed, and must then be 1 to 256 characters long with no control +//! characters. +//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the +//! style does not set. Setting one redefines the style: text in the style takes the new value +//! where it had the style's old one and keeps its other changes. +//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words +//! or paragraphs of one, in the style's document. A character style styles exactly that text and +//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches. +//! `clearingOverrides` left out is false; true resets the text to the Normal style first. +//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or +//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in +//! no other style. They do not add or remove styles. +//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its +//! look and is in the Normal style after. +//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`, +//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef}; +use vectorcraft_geom::Point; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref}; + +use super::{ + ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref, + function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text, + text_of, this_range, typename_of, usize_of, whole_span, with_doc, +}; +use crate::DocState; +use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs}; +use crate::script::dom::{Described, returns, typed}; + +/// The error of a style object whose style is gone. +pub const STALE_STYLE: &str = "Stale style"; +/// The longest style name, in characters, after trimming. +pub const MAX_STYLE_NAME: usize = 256; +/// The most styles one run's style objects name. +pub const MAX_HELD: usize = 4096; + +/// A style that a run's style objects name: its document and the document's revert count then, its +/// kind and its name now. +struct Slot { + uid: u64, + reverts: u64, + para: bool, + name: String, + live: bool, +} + +/// A document's uid and its character and paragraph style lists when the slots were last checked. +type Seen = (u64, Shared>, Shared>); + +/// The styles a run's style objects name; an object holds its slot's number. +#[derive(Default)] +pub(super) struct StyleState { + slots: RefCell>, + seen: RefCell>, +} + +/// Marks stale each style object whose style the command just run removed or renamed, so a style +/// removed and made again under its name by later commands, or by later steps of the same batch, +/// is another style. A document whose style lists did not change is not checked again. A live +/// slot's style was in its document's list when the command started, so a step that removed or +/// renamed it is in the trail's removed names. +pub(in crate::script) fn after_command(h: &Host) { + let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail); + let mut slots = h.dom.text.styles.slots.borrow_mut(); + if !slots.iter().any(|s| s.live) { + return; + } + for slot in slots.iter_mut().filter(|x| x.live) { + if trail.reverted.contains(&slot.uid) + || (!trail.gone.is_empty() && slot.name != normal(slot.para) && trail.gone.contains(&(slot.uid, slot.para, slot.name.clone()))) + { + slot.live = false; + } + } + let s = h.session.borrow(); + let mut seen = h.dom.text.styles.seen.borrow_mut(); + seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid)); + for st in s.documents() { + let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles)); + if same { + continue; + } + seen.retain(|(uid, ..)| *uid != st.uid); + seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone())); + for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) { + slot.live = slot.reverts == st.reverts && has_style(st, slot.para, &slot.name); + } + } + for slot in slots.iter_mut().filter(|x| x.live) { + if !s.documents().iter().any(|d| d.uid == slot.uid) { + slot.live = false; + } + } +} + +/// The style objects' state when a savepoint was taken: each slot's name and whether it was +/// live, and the style lists last checked. +pub(in crate::script) struct Mark { + slots: Vec<(String, bool)>, + seen: Vec, +} + +/// The style objects' state now, for [`put_back`] when the savepoint taken with it is restored. +pub(in crate::script) fn mark(h: &Host) -> Mark { + let styles = &h.dom.text.styles; + let slots = styles.slots.borrow().iter().map(|s| (s.name.clone(), s.live)).collect(); + Mark { slots, seen: styles.seen.borrow().clone() } +} + +/// Puts the style objects back as they were at `mark`, after the documents were put back to the +/// savepoint taken with it. A slot added since then stays live only while its document has the +/// style and no older live slot names it. +pub(in crate::script) fn put_back(h: &Host, mark: Mark) { + let styles = &h.dom.text.styles; + let mut slots = styles.slots.borrow_mut(); + let kept = mark.slots.len(); + for (slot, (name, live)) in slots.iter_mut().zip(mark.slots) { + slot.name = name; + slot.live = live; + } + let s = h.session.borrow(); + for i in kept..slots.len() { + let (older, newer) = slots.split_at_mut(i); + let Some(slot) = newer.first_mut() else { break }; + let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name); + slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && st.reverts == slot.reverts && has_style(st, slot.para, &slot.name)); + } + *styles.seen.borrow_mut() = mark.seen; +} + +fn normal(para: bool) -> &'static str { + if para { NORMAL_PARA } else { NORMAL_CHAR } +} + +fn cmd(para: bool, verb: &str) -> String { + format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" }) +} + +fn style_class(para: bool) -> &'static str { + if para { "ParagraphStyle" } else { "CharacterStyle" } +} + +fn list_class(para: bool) -> &'static str { + if para { "ParagraphStyles" } else { "CharacterStyles" } +} + +fn defs(st: &DocState, para: bool) -> &Vec { + if para { &st.doc.para_styles } else { &st.doc.char_styles } +} + +/// The document's style names of a kind, the Normal style first. +fn names(st: &DocState, para: bool) -> Vec { + let mut out = vec![normal(para).to_string()]; + out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para))); + out +} + +fn has_style(st: &DocState, para: bool, name: &str) -> bool { + name == normal(para) || defs(st, para).iter().any(|d| d.name == name) +} + +fn stale() -> HostError { + HostError::Error(STALE_STYLE.into()) +} + +fn held_too_many() -> HostError { + HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run")) +} + +/// The style object for the style `name` of the document `uid`: the same slot as every other +/// object naming it in this run. +fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { + let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts); + let mut slots = h.dom.text.styles.slots.borrow_mut(); + let i = match slots.iter().position(|s| s.live && s.uid == uid && s.reverts == reverts && s.para == para && s.name == name) { + Some(i) => i, + None => { + if slots.len() >= MAX_HELD { + return Err(held_too_many()); + } + slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true }); + slots.len() - 1 + } + }; + Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)])) +} + +/// A style a style object names. +struct Style { + doc: Doc, + para: bool, + slot: usize, + name: String, +} + +/// The style `d` names, when it is an object of one of `classes` (with the kind each names). +fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result { + let found = classes.iter().find_map(|(c, para)| handle_of(d, c).map(|handle| (handle, *para))); + let Some((handle, para)) = found else { + return Err(HostError::Type(format!("this is not a {}", classes.first().map_or("CharacterStyle", |c| c.0)))); + }; + let [run, uid, slot] = handle.as_slice() else { return Err(stale()) }; + let doc = super::super::find_doc(h, *run, *uid).ok_or_else(stale)?; + let slot = usize_of(*slot).ok_or_else(stale)?; + let mut slots = h.dom.text.styles.slots.borrow_mut(); + let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?; + if !with_doc(h, doc, |_, st| st.reverts == s.reverts && has_style(st, para, &s.name)) { + s.live = false; + return Err(stale()); + } + Ok(Style { doc, para, slot, name: s.name.clone() }) +} + +fn this_style(h: &Host, a: &[Data]) -> std::result::Result { + style_of(h, arg(a, 0), &[("CharacterStyle", false), ("ParagraphStyle", true)]) +} + +/// Marks the slots of the styles `names` of the document `uid` as removed. +fn forget(h: &Host, uid: u64, para: bool, names: &[String]) { + for s in h.dom.text.styles.slots.borrow_mut().iter_mut() { + if s.uid == uid && s.para == para && names.contains(&s.name) { + s.live = false; + } + } +} + +/// A style name a script gave, trimmed. +fn style_name(v: &Data) -> std::result::Result { + let Data::String(s) = v else { return Err(HostError::Type("a style name must be a string".into())) }; + if s.len() > super::super::MAX_TEXT_BYTES { + return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters"))); + } + let t = s.trim(); + if t.is_empty() { + return Err(HostError::Range("a style name must not be empty".into())); + } + if t.chars().count() > MAX_STYLE_NAME { + return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters"))); + } + if t.chars().any(char::is_control) { + return Err(HostError::Range("a style name must not hold control characters".into())); + } + Ok(t.to_string()) +} + +/// Runs the style command `verb` of the kind on the document of `doc`. +fn run(h: &Host, doc: Doc, para: bool, verb: &str, params: &Value) -> std::result::Result { + on_doc(h, doc.uid, true, |h| command(h, &cmd(para, verb), params)) +} + +// ---- CharacterStyle and ParagraphStyle ---- + +fn style_name_get(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_style(h, a)?.name)) +} + +/// `name = …`: renames the style; the Normal style keeps its name. +fn style_name_set(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + let to = style_name(arg(a, 1))?; + if to == style.name { + return Ok(Data::Undefined); + } + if style.name == normal(style.para) { + return Err(HostError::Error(format!("{} cannot be renamed", style.name))); + } + if with_doc(h, style.doc, |_, st| has_style(st, style.para, &to)) { + return Err(HostError::Error(format!("a style named {to} already exists"))); + } + run(h, style.doc, style.para, "rename", &json!({"name": style.name, "to": to}))?; + forget(h, style.doc.uid, style.para, std::slice::from_ref(&to)); + if let Some(s) = h.dom.text.styles.slots.borrow_mut().get_mut(style.slot) { + s.name = to; + s.live = true; + } + Ok(Data::Undefined) +} + +fn style_parent(h: &Host, a: &[Data]) -> Answer { + Ok(doc_ref(h, this_style(h, a)?.doc.uid)) +} + +fn style_typename(h: &Host, a: &[Data]) -> Answer { + Ok(text(style_class(this_style(h, a)?.para))) +} + +fn attributes(h: &Host, a: &[Data], class: &str) -> Answer { + let style = this_style(h, a)?; + Ok(host_ref(class, &[float(h.run), float(style.doc.uid), float(style.slot as u64)])) +} + +fn style_character_attributes(h: &Host, a: &[Data]) -> Answer { + attributes(h, a, "CharacterStyleAttributes") +} + +fn style_paragraph_attributes(h: &Host, a: &[Data]) -> Answer { + attributes(h, a, "ParagraphStyleAttributes") +} + +/// `remove()`: deletes the style; its text keeps its look and is in the Normal style after. +fn style_remove(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + if style.name == normal(style.para) { + return Err(HostError::Error(format!("{} cannot be removed", style.name))); + } + run(h, style.doc, style.para, "delete", &json!({"name": style.name}))?; + forget(h, style.doc.uid, style.para, &[style.name]); + Ok(Data::Undefined) +} + +/// The text a style is applied to: a text range, a text frame, or the characters, words or +/// paragraphs of one. +fn target_span(h: &Host, d: &Data) -> std::result::Result { + if handle_of(d, "TextFrame").is_some() { + return Ok(whole_span(h, item_of(h, d)?)?.1); + } + const TEXT: [&str; 4] = ["TextRange", "Characters", "Words", "Paragraphs"]; + if !TEXT.iter().any(|c| handle_of(d, c).is_some()) { + return Err(HostError::Type("applyTo takes a TextRange or a TextFrame".into())); + } + span_of(h, d, &TEXT) +} + +/// `applyTo(textItem, clearingOverrides?)`. +fn style_apply_to(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + let target = target_span(h, arg(a, 1))?; + let clear = match arg(a, 2) { + Data::Undefined => false, + Data::Bool(b) => *b, + _ => return Err(HostError::Type("clearingOverrides must be true or false".into())), + }; + if target.item.doc.uid != style.doc.uid { + return Err(HostError::Error("the text is in another document than the style".into())); + } + let (index, s, e, _) = resolve(h, target)?; + h.charge_call(16 + (e - s) as u64)?; + let (start, end) = if style.para { + let (_, ba, bb) = para_range(&index, s, e); + (ba, bb) + } else { + // An empty range inside text changes nothing; empty text takes the style on its runs. + if s == e && index.len() > 0 { + return Ok(Data::Undefined); + } + (index.byte(s, false), index.byte(e, true)) + }; + let p = json!({"name": style.name, "clearOverrides": clear, "id": target.item.id.0, "start": start, "end": end}); + run(h, style.doc, style.para, "apply", &p)?; + Ok(Data::Undefined) +} + +// ---- the attributes of a style ---- + +/// The style attribute each `text.setRangeStyle` parameter `attr_param` gives sets. +const CHAR_KEYS: [(&str, &str); 11] = [ + ("size", "size"), + ("leading", "leading"), + ("tracking", "tracking"), + ("baselineShift", "baseline_shift"), + ("hScale", "h_scale"), + ("vScale", "v_scale"), + ("rotation", "rotation"), + ("underline", "underline"), + ("strikethrough", "strikethrough"), + ("font", "font_family"), + ("style", "font_style"), +]; + +/// The script's `Justification` members and the alignments a paragraph style stores. +const JUSTIFY: [(&str, &str); 7] = [ + ("LEFT", "Left"), + ("CENTER", "Center"), + ("RIGHT", "Right"), + ("FULLJUSTIFYLASTLINELEFT", "JustifyLeft"), + ("FULLJUSTIFYLASTLINECENTER", "JustifyCenter"), + ("FULLJUSTIFYLASTLINERIGHT", "JustifyRight"), + ("FULLJUSTIFY", "JustifyAll"), +]; + +/// The style an attributes object belongs to and the attributes it sets. +fn attrs_of(h: &Host, a: &[Data], para: bool) -> std::result::Result<(Style, Map), HostError> { + let class = if para { "ParagraphStyleAttributes" } else { "CharacterStyleAttributes" }; + let style = style_of(h, arg(a, 0), &[(class, para)])?; + let attrs = with_doc(h, style.doc, |_, st| style_attrs(&st.doc, para, &style.name)).ok_or_else(stale)?; + Ok((style, attrs)) +} + +fn char_value(h: &Host, attr: Attr, m: &Map) -> Data { + let n = |k: &str| m.get(k).and_then(Value::as_f64).map_or(Data::Undefined, num); + let b = |k: &str| m.get(k).and_then(Value::as_bool).map_or(Data::Undefined, Data::Bool); + match attr { + Attr::Size => n("size"), + Attr::Leading => n("leading"), + Attr::AutoLeading => match m.get("leading") { + Some(Value::Null) => Data::Bool(true), + Some(v) if v.is_number() => Data::Bool(false), + _ => Data::Undefined, + }, + Attr::Tracking => n("tracking"), + Attr::BaselineShift => n("baseline_shift"), + Attr::HorizontalScale => n("h_scale"), + Attr::VerticalScale => n("v_scale"), + Attr::Rotation => n("rotation"), + Attr::Underline => b("underline"), + Attr::StrikeThrough => b("strikethrough"), + Attr::TextFont => match m.get("font_family").and_then(Value::as_str) { + Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")), + None => Data::Undefined, + }, + } +} + +/// The `typename` of a style's `characterAttributes`, which throws once the style is gone. +fn attrs_typename_char(h: &Host, a: &[Data]) -> Answer { + attrs_of(h, a, false)?; + Ok(text("CharacterAttributes")) +} + +/// The `typename` of a style's `paragraphAttributes`, which throws once the style is gone. +fn attrs_typename_para(h: &Host, a: &[Data]) -> Answer { + attrs_of(h, a, true)?; + Ok(text("ParagraphAttributes")) +} + +fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer { + let (_, m) = attrs_of(h, a, false)?; + Ok(char_value(h, attr, &m)) +} + +/// Redefines the style with `attrs`, unless they are what it has. +fn redefine(h: &Host, style: &Style, old: &Map, attrs: Map) -> Answer { + if attrs == *old { + return Ok(Data::Undefined); + } + run(h, style.doc, style.para, "setAttrs", &json!({"name": style.name, "attrs": attrs}))?; + Ok(Data::Undefined) +} + +fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { + let (style, old) = attrs_of(h, a, false)?; + // `autoLeading = false` keeps the leading auto leading gives the style's size in a paragraph + // with the default justification. + let base = CharStyle::default(); + let size = old.get("size").and_then(Value::as_f64).unwrap_or(base.size); + let leading = old.get("leading").and_then(Value::as_f64); + let sample = CharStyle { size, leading, ..base }; + let t = TextObject::point(Point::default(), "", sample.clone()); + let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?; + let mut attrs = old.clone(); + for (k, v) in param.as_object().into_iter().flatten() { + let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue }; + let v = if *key == "leading" && v == "auto" { Value::Null } else { v.clone() }; + attrs.insert((*key).to_string(), v); + } + redefine(h, &style, &old, attrs) +} + +fn para_key(attr: ParaAttr) -> &'static str { + match attr { + ParaAttr::Justification => "justify", + ParaAttr::FirstLineIndent => "first_line_indent", + ParaAttr::LeftIndent => "left_indent", + ParaAttr::RightIndent => "right_indent", + ParaAttr::SpaceBefore => "space_before", + ParaAttr::SpaceAfter => "space_after", + } +} + +fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer { + let (_, m) = attrs_of(h, a, true)?; + let v = m.get(para_key(attr)); + Ok(match attr { + ParaAttr::Justification => match v.and_then(Value::as_str) { + Some("Auto") => text("Justification.LEFT"), + Some(s) => JUSTIFY.iter().find(|(_, j)| *j == s).map_or(Data::Undefined, |(k, _)| text(format!("Justification.{k}"))), + None => Data::Undefined, + }, + _ => v.and_then(Value::as_f64).map_or(Data::Undefined, num), + }) +} + +fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { + let (style, old) = attrs_of(h, a, true)?; + let (_, _, wants) = para_param(attr, name, arg(a, 1))?; + let value = match (&wants, attr) { + (Data::String(s), ParaAttr::Justification) => { + let m = s.strip_prefix("Justification.").unwrap_or(s); + let found = JUSTIFY.iter().find(|(k, _)| *k == m).map(|(_, j)| *j); + json!(found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?) + } + (Data::Number(n), _) => json!(n), + _ => return Err(HostError::Type(format!("{name} must be a finite number"))), + }; + let mut attrs = old.clone(); + attrs.insert(para_key(attr).to_string(), value); + redefine(h, &style, &old, attrs) +} + +/// The body of a member that captures what it reads or sets. +type Body = Rc Answer>; + +/// Members whose getter and setter each charge the call, as [`function`] does. +fn charged(link: &Link, g: impl Fn(&Host, &[Data]) -> Answer + 'static, s: impl Fn(&Host, &[Data]) -> Answer + 'static) -> HostMember { + let wrap = |f: Body| -> HostFunction { + let l = link.clone(); + Rc::new(move |a: Vec| { + let h = super::super::current(&l)?; + h.charge_call(16 + a.iter().map(super::super::data_size).sum::())?; + f(&h, &a) + }) + }; + HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) } +} + +fn char_members(link: &Link) -> Vec { + ATTRS + .iter() + .map(|&(name, attr)| { + let data_type = match attr { + Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", + Attr::TextFont => "TextFont", + _ => "number", + }; + (name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name)), typed(data_type)) + }) + .collect() +} + +fn para_members(link: &Link) -> Vec { + PARA_ATTRS + .iter() + .map(|&(name, attr)| { + let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" }; + (name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name)), typed(data_type)) + }) + .collect() +} + +// ---- CharacterStyles and ParagraphStyles ---- + +/// What a collection of styles lists: a document's styles, or those a text range uses. +enum Of { + Doc(Doc), + Range(Span), +} + +fn list_of(h: &Host, d: &Data) -> std::result::Result<(Of, bool), HostError> { + let para = match (handle_of(d, "CharacterStyles"), handle_of(d, "ParagraphStyles")) { + (Some(_), _) => false, + (_, Some(_)) => true, + _ => return Err(HostError::Type("this is not a CharacterStyles".into())), + }; + let class = list_class(para); + let len = handle_of(d, class).map_or(0, |v| v.len()); + Ok((if len == 2 { Of::Doc(doc_of(h, d, class)?) } else { Of::Range(span_of(h, d, &[class])?) }, para)) +} + +/// The document and the names of the styles a collection lists. +fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec), HostError> { + match of { + Of::Doc(doc) => { + let names = with_doc(h, *doc, |_, st| names(st, para)); + h.charge_call(names.len() as u64)?; + Ok((*doc, names)) + } + Of::Range(r) => { + let (index, s, e, _) = resolve(h, *r)?; + let used = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let used: Vec> = if para { + let (paras, _, _) = para_range(&index, s, e); + paras.map(|i| t.para_at(i).style_name.clone()).collect() + } else { + styles_in(t, index.byte(s, false), index.byte(e, true), false)?.into_iter().map(|(c, _)| c.style_name).collect() + }; + h.charge_call(used.len() as u64)?; + let mut out: Vec = Vec::new(); + for n in used { + let n = n.filter(|n| has_style(st, para, n)).unwrap_or_else(|| normal(para).to_string()); + if !out.contains(&n) { + out.push(n); + } + } + if out.is_empty() { + out.push(normal(para).to_string()); + } + Ok::<_, HostError>(out) + })?; + Ok((r.item.doc, used)) + } + } +} + +fn list_length(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + Ok(num(float(listed(h, &of, para)?.1.len() as u64))) +} + +fn list_parent(h: &Host, a: &[Data]) -> Answer { + let (of, _) = list_of(h, arg(a, 0))?; + match of { + Of::Doc(doc) => Ok(doc_ref(h, doc.uid)), + Of::Range(r) => { + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, "TextRange")) + } + } +} + +fn list_at(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let found = match &of { + Of::Doc(doc) => with_doc(h, *doc, |_, st| match i { + 0 => Some(normal(para).to_string()), + _ => defs(st, para).iter().map(|d| &d.name).filter(|n| *n != normal(para)).nth(i - 1).cloned(), + }) + .map(|n| (*doc, n)), + Of::Range(_) => { + let (doc, names) = listed(h, &of, para)?; + names.get(i).cloned().map(|n| (doc, n)) + } + }; + match found { + Some((doc, name)) => style_ref(h, doc.uid, para, &name), + None => Ok(Data::Undefined), + } +} + +fn list_by_name(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + if name.len() > super::super::MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let (doc, names) = listed(h, &of, para)?; + match names.iter().find(|n| *n == name) { + Some(n) => style_ref(h, doc.uid, para, n), + None => Err(HostError::Error(NOT_FOUND.into())), + } +} + +fn list_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => list_by_name(h, a), + Data::Number(_) => match list_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// The document of a document's collection; a range's collection cannot be changed. +fn changed_doc(h: &Host, a: &[Data]) -> std::result::Result<(Doc, bool), HostError> { + match list_of(h, arg(a, 0))? { + (Of::Doc(doc), para) => Ok((doc, para)), + (Of::Range(_), _) => Err(HostError::Error("the styles of a text range cannot be added or removed".into())), + } +} + +/// `add(name)`: a new style that sets no attributes. +fn list_add(h: &Host, a: &[Data]) -> Answer { + let (doc, para) = changed_doc(h, a)?; + let name = style_name(arg(a, 1))?; + if with_doc(h, doc, |_, st| has_style(st, para, &name)) { + return Err(HostError::Error(format!("a style named {name} already exists"))); + } + // The new style needs a slot of its own: a run that names as many styles as it may adds none. + if h.dom.text.styles.slots.borrow().len() >= MAX_HELD { + return Err(held_too_many()); + } + run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?; + // An object of a removed style of this name stays stale. + forget(h, doc.uid, para, std::slice::from_ref(&name)); + style_ref(h, doc.uid, para, &name) +} + +/// `removeAll()`: deletes every style but the Normal style, in one command. +fn list_remove_all(h: &Host, a: &[Data]) -> Answer { + let (doc, para) = changed_doc(h, a)?; + let gone: Vec = with_doc(h, doc, |_, st| names(st, para)).into_iter().skip(1).collect(); + if gone.is_empty() { + return Ok(Data::Undefined); + } + run(h, doc, para, "delete", &json!({"names": gone}))?; + forget(h, doc.uid, para, &gone); + Ok(Data::Undefined) +} + +fn doc_char_styles(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("CharacterStyles", &[float(h.run), float(doc.uid)])) +} + +fn doc_para_styles(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("ParagraphStyles", &[float(h.run), float(doc.uid)])) +} + +fn range_styles(h: &Host, a: &[Data], para: bool) -> Answer { + let r = this_range(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, list_class(para))) +} + +fn range_char_styles(h: &Host, a: &[Data]) -> Answer { + range_styles(h, a, false) +} + +fn range_para_styles(h: &Host, a: &[Data]) -> Answer { + range_styles(h, a, true) +} + +/// `document.characterStyles` and `document.paragraphStyles`. +pub(in crate::script) fn doc_members(l: &Link) -> Vec { + named(vec![ + ("characterStyles", get(l, doc_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }), + ("paragraphStyles", get(l, doc_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }), + ]) +} + +/// `TextRange.characterStyles` and `TextRange.paragraphStyles`. +pub(super) fn range_members(l: &Link) -> Vec { + named(vec![ + ("characterStyles", get(l, range_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }), + ("paragraphStyles", get(l, range_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }), + ]) +} + +/// The style classes. +pub(super) fn classes(l: &Link) -> Vec { + let style = |para: bool| { + let mut members = named(vec![ + ("typename", get(l, style_typename), typed("string")), + ("name", property(l, style_name_get, style_name_set), typed("string")), + ("parent", get(l, style_parent), typed("Document")), + ("applyTo", method(l, style_apply_to), returns("undefined", &[("textItem", "*"), ("clearingOverrides", "boolean")])), + ("remove", method(l, style_remove), returns("undefined", &[])), + ]); + if para { + members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes), typed("ParagraphStyleAttributes"))); + members.push(super::super::later(l, "ParagraphStyle", "characterAttributes")); + } else { + members.push(("characterAttributes".into(), get(l, style_character_attributes), typed("CharacterStyleAttributes"))); + } + class(style_class(para), None, members, None) + }; + let list = |para: bool| { + let name = list_class(para); + let item = style_class(para); + class( + name, + None, + named(vec![ + ("typename", typename_of(name), typed("string")), + ("length", get(l, list_length), typed("number")), + ("parent", get(l, list_parent), typed("*")), + ("index", method(l, list_index), returns(item, &[("itemKey", "*")])), + ("getByName", method(l, list_by_name), returns(item, &[("name", "string")])), + ("add", method(l, list_add), returns(item, &[("name", "string")])), + ("removeAll", method(l, list_remove_all), returns("undefined", &[])), + ]), + Some(function(l, list_at)), + ) + }; + let mut chars = named(vec![("typename", get(l, attrs_typename_char), typed("string"))]); + chars.extend(char_members(l)); + let mut paras = named(vec![("typename", get(l, attrs_typename_para), typed("string"))]); + paras.extend(para_members(l)); + vec![ + style(false), + style(true), + list(false), + list(true), + class("CharacterStyleAttributes", None, chars, None), + class("ParagraphStyleAttributes", None, paras, None), + ] +} diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs new file mode 100644 index 0000000000..e159893e8d --- /dev/null +++ b/crates/engine/src/script/dom/text/threads.rs @@ -0,0 +1,829 @@ +//! Threaded type in the script object model: a text frame's `nextFrame`, `previousFrame` and +//! `story`, `document.stories`, and each `Story` with its frames and its text, as the help pages +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - Assigning `nextFrame` links the last frame of a story to the first frame of another story, +//! whose text then flows on after it; `previousFrame` links the other way. Assigning `null` +//! breaks that link, and no text moves across it. Point type, a frame of another +//! document, the frame itself, a frame inside a story, a link that would make a loop and a hidden +//! or locked frame in either story are refused with nothing changed. Assigning the frame that is +//! already linked, or `null` where there is no link, changes nothing. +//! - A `Story` is the story of the frame it was read from as that frame is threaded now; when the +//! frame is deleted, it throws `Stale story`. +//! - `document.stories` lists one story for each type object in no thread and one for each thread, +//! in the order of their first frames in `document.textFrames`, topmost first. `index` with a string finds the first story whose +//! first frame has that name. +//! - The text of a story of two or more frames is its frames' text in thread order. Its ranges keep +//! their place through edits made through them, as a frame's ranges do, and are stale after any +//! other change to the story's text and after File › Revert. A story of one frame gives that +//! frame's own ranges. +//! - `areaText` and `pathText` with a `baseFrame` thread the new frame after it, or before it when +//! `postFix` is false; `postFix` is true when it is left out. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::rc::Rc; +use std::sync::{Arc, Weak}; + +use serde_json::json; +use vectorcraft_doc::TextKind; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref}; + +use super::super::{ + Answer, Described, Doc, Host, Item, Link, NOT_FOUND, arg, boolean, class, current, doc_of, doc_ref, edit_item, find_doc, float, function, get, + handle_of, id_of, id_parts, in_compound, item_of, item_ref, method, named, num, property, returns, text, typed, whole, with_doc, +}; +use super::{ + ATTRS, Index, Log, Part, STALE_RANGE, frame_ids, from_script, part_spans, range_ref, read_only, text_of, this_frame, to_script, touched, + usize_of, whole_span, +}; +use crate::cmd::threads::story_of; +use crate::{DocState, Document, NodeId}; + +/// The error of a `Story` whose frame was deleted, or that came from an earlier run. +pub const STALE_STORY: &str = "Stale story"; + +/// A document's uid, the document, and the first frame of each of its stories then. +type StoryList = (u64, Weak, Rc>); + +/// The story state of one run: the text of each story of two or more frames that a range was made +/// of, by document and the frame the `Story` was read from, and the last list of stories. +#[derive(Default)] +pub(in crate::script) struct StoryState { + logs: RefCell>, + list: RefCell>, +} + +/// The frames of the story `id` is a frame of, in thread order, each once, or `id` alone. +fn frames_of(st: &DocState, id: NodeId) -> Vec { + let mut frames = story_of(&st.doc, id); + let mut seen = HashSet::new(); + frames.retain(|f| seen.insert(*f)); + if frames.len() < 2 { vec![id] } else { frames } +} + +/// The frames of the story `id` is a frame of, charged to the run. +fn charged_frames(h: &Host, st: &DocState, id: NodeId) -> std::result::Result, HostError> { + h.charge_call(st.doc.text_threads.len() as u64)?; + let frames = frames_of(st, id); + h.charge_call(frames.len() as u64)?; + Ok(frames) +} + +/// Whether type object `id` is area type or type on a path. +fn threadable(st: &DocState, id: NodeId) -> bool { + text_of(st, id).is_some_and(|t| !matches!(t.kind, TextKind::Point)) +} + +// ---- nextFrame and previousFrame ---- + +fn neighbor(h: &Host, a: &[Data], next: bool) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let frames = charged_frames(h, st, item.id)?; + let i = frames.iter().position(|f| *f == item.id); + let other = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) }); + Ok(other.map_or(Data::Null, |f| item_ref(h, st, *f))) + }) +} + +fn next_frame(h: &Host, a: &[Data]) -> Answer { + neighbor(h, a, true) +} + +fn previous_frame(h: &Host, a: &[Data]) -> Answer { + neighbor(h, a, false) +} + +/// Assigns `nextFrame` (`next`) or `previousFrame` with `text.thread.setNeighbor`. +fn set_neighbor(h: &Host, a: &[Data], next: bool) -> Answer { + let name = if next { "nextFrame" } else { "previousFrame" }; + let item = this_frame(h, a)?; + let other = match arg(a, 1) { + Data::Null => None, + d if handle_of(d, "TextFrame").is_some() => Some(item_of(h, d)?), + _ => return Err(HostError::Type(format!("{name} must be a TextFrame or null"))), + }; + if other.is_some_and(|o| o.doc.uid != item.doc.uid) { + return Err(HostError::Error(format!("{name}: the two frames are in different documents"))); + } + let now = with_doc(h, item.doc, |_, st| { + if !threadable(st, item.id) || other.is_some_and(|o| !threadable(st, o.id)) { + return Err(HostError::Error(format!("{name}: only area type and type on a path can be threaded"))); + } + let frames = charged_frames(h, st, item.id)?; + let i = frames.iter().position(|f| *f == item.id); + let current = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) }); + Ok(current.copied()) + })?; + if now == other.map(|o| o.id) { + return Ok(Data::Undefined); + } + let side = if next { "next" } else { "previous" }; + let params = json!({"id": item.id.0, "side": side, "neighbor": other.map(|o| o.id.0)}); + edit_item(h, item, "text.thread.setNeighbor", ¶ms).map_err(|e| match e { + HostError::Error(m) => HostError::Error(format!("{name}: {m}")), + e => e, + })?; + Ok(Data::Undefined) +} + +fn set_next_frame(h: &Host, a: &[Data]) -> Answer { + set_neighbor(h, a, true) +} + +fn set_previous_frame(h: &Host, a: &[Data]) -> Answer { + set_neighbor(h, a, false) +} + +/// `TextFrame.story`. +fn frame_story(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + Ok(story_ref(h, item)) +} + +/// `TextRange.story`: the story of the range's frame. +fn range_story(h: &Host, a: &[Data]) -> Answer { + let r = super::this_range(h, a)?; + super::resolve(h, r)?; + Ok(story_ref(h, r.item)) +} + +// ---- creating a frame threaded to another ---- + +/// The `baseFrame` and `postFix` arguments of `areaText` and `pathText`, checked before the frame +/// is made: the frame to thread the new one to, and whether the new one goes after it. +pub(super) fn base_frame(h: &Host, doc: Doc, base: &Data, post: &Data) -> std::result::Result, HostError> { + if matches!(base, Data::Undefined | Data::Null) { + return Ok(None); + } + if handle_of(base, "TextFrame").is_none() { + return Err(HostError::Type("baseFrame must be a TextFrame".into())); + } + let item = item_of(h, base)?; + if item.doc.uid != doc.uid { + return Err(HostError::Error("baseFrame: the frame is in another document".into())); + } + let postfix = match post { + Data::Undefined => true, + d => boolean(d, "postFix")?, + }; + with_doc(h, item.doc, |_, st| { + if !threadable(st, item.id) { + return Err(HostError::Error("baseFrame: only area type and type on a path can be threaded".into())); + } + let editable = st.doc.editable(); + if charged_frames(h, st, item.id)?.iter().any(|f| !editable(*f)) { + return Err(HostError::Error("baseFrame: a frame of its story is hidden or locked".into())); + } + Ok(()) + })?; + Ok(Some((item, postfix))) +} + +/// Refuses a `baseFrame` for a path inside a compound path before the path is turned into type: +/// `text.thread.add` does not thread type there. +pub(super) fn check_base_path(h: &Host, path: Item) -> std::result::Result<(), HostError> { + if in_compound(h, path) { + return Err(HostError::Error("baseFrame: type made from a path inside a compound path cannot be threaded".into())); + } + Ok(()) +} + +/// Threads the new frame `id` after `base`, or before it when `postfix` is false. +pub(super) fn thread_new(h: &Host, base: Item, id: NodeId, postfix: bool) -> std::result::Result<(), HostError> { + edit_item(h, base, "text.thread.add", &json!({"from": base.id.0, "to": id.0, "before": !postfix}))?; + Ok(()) +} + +// ---- Story ---- + +fn story_ref(h: &Host, item: Item) -> Data { + let [high, low] = id_parts(item.id); + host_ref("Story", &[float(h.run), float(item.doc.uid), high, low]) +} + +/// The frame the story `d` was read from, which must still be a type object. +fn story_of_data(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "Story") else { return Err(HostError::Type("this is not a Story".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Story".into())) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_STORY.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_STORY.into()))?; + match with_doc(h, doc, |_, st| text_of(st, id).is_some()) { + true => Ok(Item { doc, id }), + false => Err(HostError::Error(STALE_STORY.into())), + } +} + +fn this_story(h: &Host, a: &[Data]) -> std::result::Result { + story_of_data(h, arg(a, 0)) +} + +fn story_frames(h: &Host, a: &[Data]) -> Answer { + let story = this_story(h, a)?; + with_doc(h, story.doc, |_, st| Ok(Data::Array(charged_frames(h, st, story.id)?.iter().map(|f| item_ref(h, st, *f)).collect()))) +} + +fn story_parent(h: &Host, a: &[Data]) -> Answer { + let story = this_story(h, a)?; + Ok(doc_ref(h, story.doc.uid)) +} + +/// The story's one frame, or `None` for a story of two or more frames. +fn single(h: &Host, story: Item) -> std::result::Result, HostError> { + with_doc(h, story.doc, |_, st| { + let frames = charged_frames(h, st, story.id)?; + Ok(match frames[..] { + [one] => Some(Item { doc: story.doc, id: one }), + _ => None, + }) + }) +} + +fn story_length(h: &Host, a: &[Data]) -> Answer { + let story = this_story(h, a)?; + let (index, _) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?; + Ok(num(float(index.len() as u64))) +} + +/// A range or a collection of the whole story, as `frame_class` for a story of one frame and +/// `story_class` for a longer one. +fn story_whole(h: &Host, a: &[Data], frame_class: &str, story_class: &str) -> Answer { + let story = this_story(h, a)?; + if let Some(frame) = single(h, story)? { + let (_, r) = whole_span(h, frame)?; + return Ok(range_ref(h, frame, r.start, r.end, r.stamp, frame_class)); + } + let (index, stamp) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?; + Ok(span_ref(h, story, 0, index.len(), stamp, story_class)) +} + +fn story_text_range(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "TextRange", "StoryRange") +} + +fn story_characters(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "Characters", "StoryCharacters") +} + +fn story_words(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "Words", "StoryWords") +} + +fn story_paragraphs(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "Paragraphs", "StoryParagraphs") +} + +// ---- the text of a story of two or more frames ---- + +/// The frames of the story and the text of each, in thread order. +fn story_text(st: &DocState, frames: &[NodeId]) -> String { + frames.iter().filter_map(|f| text_of(st, *f)).flat_map(|t| t.runs.iter().map(|r| r.text.as_str())).collect() +} + +/// The story's index and its generation now, read again when its document changed. The stories +/// read from the frames of one story share one index of its text while the document is unchanged. +fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc, u64), HostError> { + if text_of(st, anchor).is_none() { + return Err(HostError::Error(STALE_STORY.into())); + } + let mut logs = h.dom.text.stories.logs.borrow_mut(); + let key = (st.uid, anchor.0); + let now = Arc::as_ptr(&st.doc); + let current = |l: &Log| std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts; + if !logs.get(&key).is_some_and(current) { + let frames = charged_frames(h, st, anchor)?; + // Another frame of the same story read at this state of the document has the same text; + // a frame listed in two threads can belong to another story, so its frames must match. + let mut shared = None; + if frames.len() > 1 { + h.charge_call(frames.len() as u64)?; + if let Some((f, l)) = + frames.iter().filter(|f| **f != anchor).find_map(|f| logs.get(&(st.uid, f.0)).filter(|l| current(l)).map(|l| (*f, l))) + && charged_frames(h, st, f)? == frames + { + shared = Some(l.index.clone()); + } + } + let index = match shared { + Some(index) => index, + None => { + let text = story_text(st, &frames); + // Joining the frames' text costs its length, as rebuilding the index does elsewhere. + h.charge_call(text.len() as u64)?; + match logs.get(&key) { + Some(l) if l.reverts == st.reverts && l.index.text == text => l.index.clone(), + _ => Rc::new(Index::new(text)), + } + } + }; + match logs.get_mut(&key) { + Some(l) => { + if l.reverts != st.reverts || index.text != l.index.text { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + } + l.index = index; + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + None => { + logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() }); + } + } + } + let l = logs.get(&key).ok_or_else(|| HostError::Error(STALE_STORY.into()))?; + Ok((l.index.clone(), l.stamp)) +} + +/// A range of a story: the frame the story was read from, its span in UTF-16 units and the +/// generation it was made at. +#[derive(Clone, Copy)] +struct StorySpan { + story: Item, + start: usize, + end: usize, + stamp: u64, +} + +const STORY_PARTS: [(&str, Part); 3] = [("StoryCharacters", Part::Characters), ("StoryWords", Part::Words), ("StoryParagraphs", Part::Paragraphs)]; + +fn span_ref(h: &Host, story: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data { + let [high, low] = id_parts(story.id); + host_ref(class, &[float(h.run), float(story.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)]) +} + +/// The story span `d` names, when it is an object of one of `classes`. +fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result { + let handle = classes.iter().find_map(|c| handle_of(d, c)); + let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else { + return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange")))); + }; + let story = story_of_data(h, &host_ref("Story", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?; + let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) }; + Ok(StorySpan { story, start, end, stamp }) +} + +fn this_span(h: &Host, a: &[Data]) -> std::result::Result { + span_of(h, arg(a, 0), &["StoryRange"]) +} + +/// The span and index of `r` now. +fn resolve(h: &Host, r: StorySpan) -> std::result::Result<(Rc, usize, usize, u64), HostError> { + with_doc(h, r.story.doc, |_, st| { + let (index, stamp) = observe(h, st, r.story.id)?; + let logs = h.dom.text.stories.logs.borrow(); + let l = logs.get(&(st.uid, r.story.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + if r.stamp < l.floor || r.stamp > l.stamp { + return Err(HostError::Error(STALE_RANGE.into())); + } + let (mut s, mut e) = (r.start, r.end); + let from = l.edits.partition_point(|x| x.stamp <= r.stamp); + for x in l.edits.range(from..) { + let moved = |v: usize| v - x.removed + x.inserted; + s = if s <= x.at { + s + } else if s >= x.at + x.removed { + moved(s) + } else { + x.at + }; + // An end inside the removed text goes to the end of the new text. + e = if e < x.at || (e == x.at && x.removed > 0) { + e + } else if e >= x.at + x.removed { + moved(e) + } else { + x.at + x.inserted + }; + } + let e = e.min(index.len()); + Ok((index, s.min(e), e, stamp)) + }) +} + +/// Records an edit the model made to the story: `removed` units at `at` replaced by `inserted`. +/// When the text is not what that edit gives, every earlier range goes stale. The ranges of the +/// same story read from its other frames record the edit too, when they knew the text before it. +fn record(h: &Host, story: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { + with_doc(h, story.doc, |_, st| { + if text_of(st, story.id).is_none() { + return Err(HostError::Error(STALE_STORY.into())); + } + let frames = charged_frames(h, st, story.id)?; + let now = story_text(st, &frames); + let (a, b) = (before.byte(at, false), before.byte(at + removed, true)); + let expected = before.text.len() - (b - a) + inserted.len() == now.len() + && now.as_bytes().starts_with(&before.text.as_bytes()[..a]) + && now.as_bytes().ends_with(&before.text.as_bytes()[b..]) + && now.get(a..a + inserted.len()) == Some(inserted); + let members: HashSet = frames.iter().map(|f| f.0).collect(); + let index = Rc::new(Index::new(now)); + let inserted = inserted.encode_utf16().count(); + let mut logs = h.dom.text.stories.logs.borrow_mut(); + let mut found = false; + for (&(uid, anchor), l) in logs.iter_mut() { + if uid != st.uid || !members.contains(&anchor) { + continue; + } + let own = anchor == story.id.0; + let current = l.reverts == st.reverts; + if !own { + h.charge_call(l.index.text.len() as u64)?; + if !expected || !current || l.index.text != before.text { + continue; + } + } + found |= own; + if expected && current { + l.push(at, removed, inserted); + } else { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + } + l.index = index.clone(); + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + if found { Ok(()) } else { Err(HostError::Error(STALE_RANGE.into())) } + }) +} + +/// Replaces bytes `a..b` of the story's text with `insert`, a frame at a time from the end, with +/// `text.editRange`: the frames before the one an edit changes keep their text, so `a` stays in +/// place while the frames after it flow again. +fn replace(h: &Host, story: Item, a: usize, mut b: usize, insert: &str) -> std::result::Result<(), HostError> { + loop { + let spans: Vec<(NodeId, usize, usize)> = with_doc(h, story.doc, |_, st| { + if text_of(st, story.id).is_none() { + return Err(HostError::Error(STALE_STORY.into())); + } + let mut at = 0; + let spans = charged_frames(h, st, story.id)? + .into_iter() + .map(|f| { + let n: usize = text_of(st, f).map_or(0, |t| t.runs.iter().map(|r| r.text.len()).sum()); + at += n; + (f, at - n, at) + }) + .collect(); + Ok(spans) + })?; + let target = + if b > a { spans.iter().find(|(_, x, y)| *x < b && b <= *y) } else { spans.iter().find(|(_, x, y)| *x < a && a <= *y).or(spans.first()) }; + let Some(&(f, x, _)) = target else { return Err(HostError::Error(STALE_RANGE.into())) }; + let item = Item { doc: story.doc, id: f }; + if x <= a { + edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": a - x, "end": b - x, "insert": insert}))?; + return Ok(()); + } + edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": 0, "end": b - x, "insert": ""}))?; + b = x; + } +} + +fn write_contents(h: &Host, r: StorySpan, value: &Data) -> Answer { + let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) }; + let insert = from_script(v); + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + if index.text[a..b] == insert { + return Ok(Data::Undefined); + } + let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); + replace(h, r.story, a, b, &insert)?; + record(h, r.story, &index, s, e - s, &insert)?; + Ok(Data::Undefined) +} + +fn span_contents(h: &Host, a: &[Data]) -> Answer { + let (index, s, e, _) = resolve(h, this_span(h, a)?)?; + let (x, y) = (index.byte(s, false), index.byte(e, true)); + Ok(text(to_script(&index.text[x..y]))) +} + +fn span_set_contents(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_span(h, a)?, arg(a, 1)) +} + +fn span_remove(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_span(h, a)?, &text("")) +} + +fn span_start(h: &Host, a: &[Data]) -> Answer { + let (_, s, _, _) = resolve(h, this_span(h, a)?)?; + Ok(num(float(s as u64))) +} + +fn span_end(h: &Host, a: &[Data]) -> Answer { + let (_, _, e, _) = resolve(h, this_span(h, a)?)?; + Ok(num(float(e as u64))) +} + +fn span_length(h: &Host, a: &[Data]) -> Answer { + let (_, s, e, _) = resolve(h, this_span(h, a)?)?; + Ok(num(float((e - s) as u64))) +} + +fn span_story(h: &Host, a: &[Data]) -> Answer { + let r = this_span(h, a)?; + resolve(h, r)?; + Ok(story_ref(h, r.story)) +} + +fn span_paragraph_length(h: &Host, a: &[Data]) -> Answer { + let (index, s, e, _) = resolve(h, this_span(h, a)?)?; + let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x); + Ok(num(float(p as u64))) +} + +fn span_part(h: &Host, a: &[Data], class: &str) -> Answer { + let r = this_span(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(span_ref(h, r.story, s, e, stamp, class)) +} + +fn span_characters(h: &Host, a: &[Data]) -> Answer { + span_part(h, a, "StoryCharacters") +} + +fn span_words(h: &Host, a: &[Data]) -> Answer { + span_part(h, a, "StoryWords") +} + +fn span_paragraphs(h: &Host, a: &[Data]) -> Answer { + span_part(h, a, "StoryParagraphs") +} + +fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(StorySpan, Part), HostError> { + let part = STORY_PARTS.iter().find(|(c, _)| handle_of(arg(a, 0), c).is_some()).map(|(_, p)| *p); + let part = part.ok_or_else(|| HostError::Type("this is not a collection of text".into()))?; + Ok((span_of(h, arg(a, 0), &STORY_PARTS.map(|(c, _)| c))?, part)) +} + +fn part_typename(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + resolve(h, r)?; + Ok(text(match part { + Part::Characters => "Characters", + Part::Words => "Words", + Part::Paragraphs => "Paragraphs", + })) +} + +fn span_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, this_span(h, a)?)?; + Ok(text("TextRange")) +} + +fn story_typename(h: &Host, a: &[Data]) -> Answer { + this_story(h, a)?; + Ok(text("Story")) +} + +fn part_length(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + Ok(num(float(part_spans(&index, part, s, e).0.len() as u64))) +} + +fn part_parent(h: &Host, a: &[Data]) -> Answer { + let (r, _) = this_part(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(span_ref(h, r.story, s, e, stamp, "StoryRange")) +} + +fn part_at(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let (index, s, e, stamp) = resolve(h, r)?; + let (items, spans) = part_spans(&index, part, s, e); + let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) }; + let span = match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + Ok(span.map_or(Data::Undefined, |(x, y)| span_ref(h, r.story, x, y, stamp, "StoryRange"))) +} + +// ---- Stories ---- + +fn doc_stories_impl(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Stories", &[float(h.run), float(doc.uid)])) +} + +/// `document.stories`. +pub(in crate::script::dom) fn doc_stories(link: &Link) -> HostMember { + get(link, doc_stories_impl) +} + +/// The first frame of each story of the document in paint order, kept while the document is +/// unchanged. +fn heads(h: &Host, st: &DocState) -> std::result::Result>, HostError> { + if let Some((uid, doc, ids)) = &*h.dom.text.stories.list.borrow() + && *uid == st.uid + && std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc)) + { + return Ok(ids.clone()); + } + let ids = frame_ids(h, st); + h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::())?; + // A frame listed by an earlier thread belongs to that one, as `story_of` finds it. + let (mut threaded, mut first) = (HashSet::new(), HashSet::new()); + let mut seen = HashSet::new(); + for thread in &st.doc.text_threads { + let live: Vec = thread.iter().copied().filter(|f| threadable(st, *f) && seen.insert(*f)).collect(); + if live.len() >= 2 { + first.insert(live[0]); + threaded.extend(live); + } + } + let heads: Vec = ids.iter().copied().filter(|id| !threaded.contains(id) || first.contains(id)).collect(); + let heads = Rc::new(heads); + *h.dom.text.stories.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), heads.clone())); + Ok(heads) +} + +fn stories_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Stories") +} + +fn stories_length(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + let n = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.len()))?; + Ok(num(float(n as u64))) +} + +fn stories_typename(h: &Host, a: &[Data]) -> Answer { + stories_doc(h, a)?; + Ok(text("Stories")) +} + +fn stories_parent(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn stories_at(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let id = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.get(i).copied()))?; + Ok(id.map_or(Data::Undefined, |id| story_ref(h, Item { doc, id }))) +} + +/// `stories.index(key)`: by number, or by the name of a story's first frame. +fn stories_index(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + match arg(a, 1) { + Data::Number(_) => match stories_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + Data::String(name) => { + let id = with_doc(h, doc, |_, st| { + let list = heads(h, st)?; + h.charge_call(list.len() as u64)?; + Ok::<_, HostError>(list.iter().copied().find(|i| st.doc.node(*i).and_then(|n| n.name.as_deref()) == Some(name.as_str()))) + })?; + id.map(|id| story_ref(h, Item { doc, id })).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + } + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +// ---- classes ---- + +/// A member of the range of a story of two or more frames that is not available yet: reading or +/// assigning it throws, after the check that the range is still there, and `reflect` leaves it out. +fn range_later(link: &Link, name: &'static str) -> Described { + let message = format!("TextRange.{name} is not available yet"); + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + resolve(&h, this_span(&h, &a)?)?; + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() }) +} + +/// A member of `Story` that is not available yet: reading or assigning it throws, after the check +/// that the story is still there, and `reflect` leaves it out. +fn story_later(link: &Link, name: &'static str) -> Described { + let message = format!("Story.{name} is not available yet"); + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + this_story(&h, &a)?; + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() }) +} + +/// The members of `TextFrame` this module adds. +pub(super) fn frame_members(l: &Link) -> Vec { + named(vec![ + ("nextFrame", property(l, next_frame, set_next_frame), typed("TextFrame")), + ("previousFrame", property(l, previous_frame, set_previous_frame), typed("TextFrame")), + ("story", get(l, frame_story), typed("Story")), + ]) +} + +/// `TextRange.story`. +pub(super) fn range_member(l: &Link) -> Described { + ("story".into(), get(l, range_story), typed("Story")) +} + +/// `Story`, `Stories` and the range and collections of the text of a story of two or more frames. +pub(super) fn classes(l: &Link) -> Vec { + let collection = |t: &str| MemberInfo { collection: true, ..typed(t) }; + let mut story = named(vec![ + ("typename", get(l, story_typename), typed("string")), + ("parent", get(l, story_parent), typed("Document")), + ("length", get(l, story_length), typed("number")), + ("textFrames", get(l, story_frames), typed("Array")), + ("textRange", get(l, story_text_range), typed("*")), + ("characters", get(l, story_characters), collection("*")), + ("words", get(l, story_words), collection("*")), + ("paragraphs", get(l, story_paragraphs), collection("*")), + ]); + story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| story_later(l, m))); + let mut range = named(vec![ + ("typename", get(l, span_typename), typed("string")), + ("parent", get(l, span_story), typed("Story")), + ("story", get(l, span_story), typed("Story")), + ("contents", property(l, span_contents, span_set_contents), typed("string")), + ("start", read_only(l, span_start, "TextRange", "start"), typed("number")), + ("end", read_only(l, span_end, "TextRange", "end"), typed("number")), + ("characterOffset", read_only(l, span_start, "TextRange", "characterOffset"), typed("number")), + ("length", read_only(l, span_length, "TextRange", "length"), typed("number")), + ("characters", get(l, span_characters), collection("StoryCharacters")), + ("words", get(l, span_words), collection("StoryWords")), + ("paragraphs", get(l, span_paragraphs), collection("StoryParagraphs")), + ("getParagraphLength", method(l, span_paragraph_length), returns("number", &[])), + ("remove", method(l, span_remove), returns("undefined", &[])), + ]); + range.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "characterAttributes", + "paragraphAttributes", + "kerning", + "characterStyles", + "paragraphStyles", + "textSelection", + "changeCaseTo", + "select", + "deSelect", + "duplicate", + "move", + "getTextRunLength", + "getLocalCharOverridesJSON", + "getLocalParaOverridesJSON", + ] + .into_iter() + .chain(ATTRS.iter().map(|(n, _)| *n)) + .map(|m| range_later(l, m)), + ); + let part = |name: &'static str| { + class( + name, + None, + named(vec![ + ("typename", get(l, part_typename), typed("string")), + ("length", get(l, part_length), typed("number")), + ("parent", get(l, part_parent), typed("StoryRange")), + ]), + Some(function(l, part_at)), + ) + }; + vec![ + class("Story", None, story, None), + class("StoryRange", None, range, None), + part("StoryCharacters"), + part("StoryWords"), + part("StoryParagraphs"), + class( + "Stories", + None, + named(vec![ + ("typename", get(l, stories_typename), typed("string")), + ("length", get(l, stories_length), typed("number")), + ("parent", get(l, stories_parent), typed("Document")), + ("index", method(l, stories_index), returns("number", &[("itemKey", "*")])), + ]), + Some(function(l, stories_at)), + ), + ] +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 2a17cb69b0..47f9896c9b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -48,13 +48,16 @@ //! that holds the run's host only while the run goes on. An error, a limit or a stop puts the //! documents back and keeps the engine's globals; an internal error drops the engine. +pub mod actions; pub mod console; pub mod dialogs; pub mod dollar; pub mod dom; pub mod include; +pub mod scriptui; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; +pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; @@ -135,7 +138,7 @@ impl Written { /// The version `vc.api.version` gives. pub const API_VERSION: &str = "1.0"; /// The features `vc.api.has` knows. -pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"]; +pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar", "scriptui"]; /// The most commands a run's report lists in `slowestCommands`. pub const SLOWEST_COMMANDS: usize = 5; @@ -205,6 +208,8 @@ pub(crate) struct Request { pub locale: String, /// The answers to the dialogs of a run with nobody to ask, in order. pub answers: Vec, + /// The actions `app.doScript` can play. + pub actions: Vec, } thread_local! { @@ -805,6 +810,15 @@ struct Host { args: RefCell<(Data, u64)>, /// The run's state of the script object model (`app`). dom: dom::State, + /// The actions `app.doScript` can play. + actions: Vec, + /// The index of each open document's active artboard as the run starts, by document uid. The + /// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it. + active_artboards: Vec<(u64, usize)>, + /// The artboards the Artboard tool had selected in the active document as the run starts (two or + /// more), with that document's uid. The run gives the tool fresh state, which drops them, so the + /// steps `app.doScript` plays read them here. + artboard_picks: Option<(u64, Vec)>, /// The documents open when the run began as the person last left them, each with its own file /// and the file it was read from ([`crate::DocState::as_person_left`], /// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files @@ -1282,6 +1296,7 @@ fn note_ids(s: &mut Session) { /// it, for a result that cannot cross to the script. fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); + s.script_style_trail = StyleTrail::start(s); let mutating = waits_for_tool_edit(id); // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); @@ -1329,6 +1344,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value Ok((v, objects, bytes, save)) } Err(e) => { + s.script_style_trail = StyleTrail::default(); if let Some(save) = save && !save.restore(s) { @@ -1407,9 +1423,76 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( } } dom::after_command(host, before); + // Style objects follow only a command that is kept. + if crossed.is_ok() { + dom::after_kept_command(host); + } else { + session.borrow_mut().script_style_trail = StyleTrail::default(); + } crossed.map(|data| (data, value)) } +/// A document's uid, revert count, and character and paragraph style lists. +pub(crate) type StyleLists = + (u64, u64, vectorcraft_doc::Shared>, vectorcraft_doc::Shared>); + +/// What the steps of a command a script runs did to the documents' style lists +/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step +/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the +/// documents a step reverted. +#[derive(Default)] +pub(crate) struct StyleTrail { + lists: Vec, + pub(crate) gone: std::collections::HashSet<(u64, bool, String)>, + pub(crate) reverted: Vec, +} + +impl StyleTrail { + /// A trail that starts from the documents' style lists now. + fn start(s: &Session) -> Self { + let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect(); + StyleTrail { lists, ..Default::default() } + } +} + +/// After a step of a batch a script runs: notes the styles the step removed or renamed and the +/// documents it reverted, so the style objects see a style the batch removed and made again under +/// its name as another style ([`dom::after_kept_command`]). The trail keeps one copy of each open +/// document's lists, however many steps change them. +pub(crate) fn note_style_lists(s: &mut Session) { + let trail = &mut s.script_style_trail; + trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid)); + for st in &s.docs { + let (c, p) = (&st.doc.char_styles, &st.doc.para_styles); + let Some(last) = trail.lists.iter_mut().find(|(uid, ..)| *uid == st.uid) else { + trail.lists.push((st.uid, st.reverts, c.clone(), p.clone())); + continue; + }; + if last.1 != st.reverts { + if !trail.reverted.contains(&st.uid) { + trail.reverted.push(st.uid); + } + } else { + for (para, old, new) in [(false, &last.2, c), (true, &last.3, p)] { + if vectorcraft_doc::Shared::ptr_eq(old, new) { + continue; + } + let names: std::collections::HashSet<&str> = new.iter().map(|d| d.name.as_str()).collect(); + for d in old.iter().filter(|d| !names.contains(d.name.as_str())) { + trail.gone.insert((st.uid, para, d.name.clone())); + } + } + } + *last = (st.uid, st.reverts, c.clone(), p.clone()); + } +} + +/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]). +#[cfg(test)] +pub(crate) fn retained_style_lists(s: &Session) -> usize { + s.script_style_trail.lists.len() +} + /// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits /// of a crossing throws a `RangeError`. fn vc_document(host: &Host) -> std::result::Result { @@ -1643,7 +1726,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { /// `e`'s message, with what to do about a failure that comes from a script written for another /// program. A message the script supplied itself ([`RunError::authored`]) is given as it is. fn explained(e: &RunError) -> String { - const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"]; + const HOST_OBJECTS: &[&str] = &["BridgeTalk"]; let message = &e.message; let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next()); let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f)); @@ -1909,6 +1992,32 @@ impl Session { with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) } + /// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run + /// asked to stop no longer waits: the next [`Session::script_pump`] ends it. + pub fn script_window(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting_window())).flatten() + } + + /// The ScriptUI dialog whose `show()` the running script is in, whether it waits at it or runs + /// one of its handlers. A run asked to stop is in none. + pub fn script_window_showing(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.showing_window())).flatten() + } + + /// Gives the ScriptUI dialog the running script waits at `event`; the next + /// [`Session::script_pump`] runs the control's handler. → an error, and the dialog still + /// waits, when nothing waits or the dialog cannot take the event ([`scriptui::check_event`]). + pub fn script_window_answer(&mut self, event: UiEvent) -> std::result::Result<(), String> { + let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return Err("no script dialog waits".into()) }; + with_job(k, |j| j.host.dialogs.window_answer(&mut j.realm, event)).unwrap_or_else(|| Err("no script dialog waits".into())) + } + /// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' /// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no /// longer waits. @@ -2036,6 +2145,9 @@ impl Session { if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { return Err(EngineError::Other(NO_RECOVERY_COPY.to_string())); } + // The Artboard tool's selection, which the fresh tool state below drops. + let picks = cmd::artboard_tool_picks(self); + let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks)); self.reset_tool(); let open: Vec = self.docs.iter().map(|d| d.uid).collect(); self.script_high_water.retain(|uid, _| open.contains(uid)); @@ -2155,6 +2267,9 @@ impl Session { dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), dom: dom::State::new(heap_bytes), + actions: request.actions, + active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), + artboard_picks, run_docs: RefCell::new( self.docs .iter() @@ -2201,6 +2316,7 @@ impl Session { .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) + .and_then(|()| if fresh { scriptui::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { @@ -2289,6 +2405,12 @@ impl Session { } job.host.calls_this_slice.set(0); let outcome = run_slice(self, &mut job); + // A failure a dialog recorded in the slice (steps a show left unused) ends the run, even + // when the script went on. + let outcome = match (outcome, job.host.dialogs.take_failure()) { + (Ok(Ok(_)), Some(e)) => Ok(Err(e)), + (outcome, _) => outcome, + }; match outcome { Err(panic) => { let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false }; diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs new file mode 100644 index 0000000000..4226196239 --- /dev/null +++ b/crates/engine/src/script/scriptui.rs @@ -0,0 +1,736 @@ +//! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run +//! gives when it shows one, checked and laid out here before the app draws it, and the events the +//! person or `script.run`'s `answers` give back. +//! +//! A description lists the dialog first and each control after the container that holds it. It is +//! refused with an error thrown at `show()` when a control's container comes after it or is not a +//! group or panel, when it holds more than [`MAX_CONTROLS`] controls, nests deeper than +//! [`MAX_DEPTH`], has more than [`MAX_ITEMS`] list items or a text longer than [`MAX_TEXT_BYTES`], +//! names an orientation or an alignment that does not exist, or gives a slider a minimum above its +//! maximum. Sizes, places, spacing and margins are clamped to [`MAX_EXTENT`] pixels, and a slider's +//! or progress bar's value to its range. +//! +//! The layout follows each container's `orientation` (row, column or stack), `alignChildren`, +//! `spacing` and `margins`, a control's `alignment`, `preferredSize` (or `size`), `minimumSize`, +//! `maximumSize` and `bounds` (left, top, right and bottom in its container); a width or height of +//! 0 or less in a size leaves that side to the layout. A control's size comes from its text, items and kind, by +//! VectorCraft's own estimates of a 7-pixel character and a 16-pixel line. The layout is worked out +//! with loops over the list, from the last control to the first for sizes and from the first to the +//! last for places, so a description's nesting takes no native stack. +//! +//! A run with nobody to ask takes one answer from `answers` for each `show()`: `{kind: "window", +//! value: [step, ...]}`, where a step is `{control, event: "click"}`, `{control, event: "change", +//! value}` or `{event: "close"}`. `control` is a control's `name`, or else its text; `value` is an +//! edit field's text, a slider's number, or a list's item index or `null`. Each time the dialog +//! waits it takes the next step; a dialog that waits with no step left, a step for a control the +//! dialog does not hold or cannot take it, and steps left when the dialog closes end the run. +//! +//! The limits here are VectorCraft's own: [`MAX_EXTENT`], and the js crate's [`MAX_CONTROLS`], +//! [`MAX_DEPTH`], [`MAX_ITEMS`] and [`MAX_TEXT_BYTES`]. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; + +pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES}; + +use super::Host; + +/// The largest size or place, in pixels, of a dialog or a control in it. +pub const MAX_EXTENT: f32 = 8192.0; +/// A character's width and a line's height in VectorCraft's size estimates, in pixels. +const CHAR: f32 = 7.0; +const LINE: f32 = 16.0; + +/// A dialog's element. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UiKind { + Dialog, + Group, + Panel, + StaticText, + EditText, + Button, + CheckBox, + RadioButton, + DropDownList, + ListBox, + Slider, + ProgressBar, +} + +impl UiKind { + fn parse(s: &str) -> Option { + Some(match s { + "dialog" => Self::Dialog, + "group" => Self::Group, + "panel" => Self::Panel, + "statictext" => Self::StaticText, + "edittext" => Self::EditText, + "button" => Self::Button, + "checkbox" => Self::CheckBox, + "radiobutton" => Self::RadioButton, + "dropdownlist" => Self::DropDownList, + "listbox" => Self::ListBox, + "slider" => Self::Slider, + "progressbar" => Self::ProgressBar, + _ => return None, + }) + } + + /// Does it hold controls? + pub fn container(self) -> bool { + matches!(self, Self::Dialog | Self::Group | Self::Panel) + } + + /// Does a click reach it? + pub fn clicks(self) -> bool { + matches!(self, Self::Button | Self::CheckBox | Self::RadioButton) + } +} + +/// How a container places its controls. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Orientation { + Row, + Column, + Stack, +} + +/// Where a control goes across its container: left or top, right or bottom, the middle, or the +/// whole width or height. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Align { + Start, + End, + Center, + Fill, +} + +/// A control's place and size in the dialog, from its top left corner. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct UiRect { + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, +} + +/// One element of a [`ScriptUiDialog`]. +#[derive(Clone, Debug, PartialEq)] +pub struct UiNode { + pub kind: UiKind, + /// A number no other element of the run has, which stays with the element while the script + /// adds and removes controls; its index in the description when the description gives none. + pub id: u64, + /// The index of its container; the dialog's own is 0. + pub parent: usize, + pub name: String, + pub text: String, + /// It and every container around it are enabled. + pub enabled: bool, + /// It and every container around it are visible. + pub visible: bool, + /// A check box's or radio button's value. + pub checked: bool, + /// A slider's or progress bar's value, within `min` to `max`. + pub value: f64, + pub min: f64, + pub max: f64, + pub items: Vec, + /// How many times the script replaced a list's items (removed or added some), which tells a + /// list from one that holds the same texts again. + pub items_revision: u64, + pub selection: Option, + pub multiline: bool, + pub readonly: bool, + pub rect: UiRect, + orientation: Orientation, + align_children: (Option, Option), + alignment: (Option, Option), + spacing: f32, + margins: [f32; 4], + size: [Option; 2], + min_size: [Option; 2], + max_size: [Option; 2], + bounds: Option, + /// The characters an edit field or static text reserves room for in its width. + characters: Option, +} + +impl UiNode { + /// How much of a progress bar is done, from 0 to 1. + pub fn fraction(&self) -> f32 { + if self.max <= self.min || self.value <= self.min { + return 0.0; + } + if self.value >= self.max { + return 1.0; + } + let span = self.max - self.min; + // A range wider than the largest number is measured at half scale. + let part = + if span.is_finite() { (self.value - self.min) / span } else { (self.value / 2.0 - self.min / 2.0) / (self.max / 2.0 - self.min / 2.0) }; + part.clamp(0.0, 1.0) as f32 + } +} + +/// A dialog a run shows, checked and laid out. +#[derive(Clone, Debug, PartialEq)] +pub struct ScriptUiDialog { + /// The dialog first, then each control after the container that holds it. + pub nodes: Vec, + /// The button Enter clicks and the one Escape clicks. + pub default_element: Option, + pub cancel_element: Option, + /// Which `show()` of the run this is, counted from 1; 0 before it shows. + pub shown: u64, +} + +impl ScriptUiDialog { + /// The dialog's title. + pub fn title(&self) -> &str { + self.nodes.first().map_or("", |n| n.text.as_str()) + } + + /// The size of the dialog's content. + pub fn size(&self) -> (f32, f32) { + self.nodes.first().map_or((0.0, 0.0), |n| (n.rect.w, n.rect.h)) + } + + /// The first control whose name is `control`, or else the first control without a name + /// whose text is `control`. + pub fn find(&self, control: &str) -> Option { + let by = |name: bool| { + let hit = |n: &UiNode| if name { !control.is_empty() && n.name == control } else { n.name.is_empty() && n.text == control }; + self.nodes.iter().enumerate().skip(1).find(|(_, n)| hit(n)).map(|(i, _)| i) + }; + by(true).or_else(|| by(false)) + } +} + +/// A value a control takes in a change. +#[derive(Clone, Debug, PartialEq)] +pub enum UiValue { + Text(String), + Number(f64), + Index(Option), +} + +/// What the person did with a dialog. +#[derive(Clone, Debug, PartialEq)] +pub enum UiEvent { + /// A click on a button, check box or radio button. + Click(usize), + /// A new value for an edit field, a slider or a list. + Change(usize, UiValue), + /// The dialog's close box. + Close, +} + +impl UiEvent { + /// The event as `show()` takes it. + pub(crate) fn data(&self) -> Data { + let event = |e: &str| ("event".to_string(), Data::String(e.into())); + let id = |i: usize| ("id".to_string(), Data::Number(i as f64)); + match self { + Self::Click(i) => Data::Object(vec![event("click"), id(*i)]), + Self::Change(i, v) => { + let value = match v { + UiValue::Text(t) => Data::String(t.clone()), + UiValue::Number(n) => Data::Number(*n), + UiValue::Index(Some(k)) => Data::Number(*k as f64), + UiValue::Index(None) => Data::Null, + }; + Data::Object(vec![event("change"), id(*i), ("value".into(), value)]) + } + Self::Close => Data::Object(vec![event("close")]), + } + } +} + +/// Checks `event` against `dialog`. → the event as the dialog takes it: a slider's value clamped +/// to its range. +pub fn check_event(dialog: &ScriptUiDialog, event: UiEvent) -> Result { + let id = match &event { + UiEvent::Close => return Ok(event), + UiEvent::Click(i) | UiEvent::Change(i, _) => *i, + }; + let Some(n) = dialog.nodes.get(id).filter(|_| id > 0) else { return Err(format!("the dialog has no control {id}")) }; + if !n.enabled || !n.visible { + return Err(format!("the control {} is disabled or hidden", label(n))); + } + match event { + UiEvent::Click(_) if n.kind.clicks() => Ok(event), + UiEvent::Click(_) => Err(format!("the control {} cannot be clicked", label(n))), + UiEvent::Change(_, UiValue::Text(t)) if n.kind == UiKind::EditText && !n.readonly => { + if t.len() > MAX_TEXT_BYTES { + return Err("the text is longer than 16 KiB".into()); + } + Ok(UiEvent::Change(id, UiValue::Text(t))) + } + UiEvent::Change(_, UiValue::Number(v)) if n.kind == UiKind::Slider && v.is_finite() => { + Ok(UiEvent::Change(id, UiValue::Number(v.clamp(n.min, n.max)))) + } + UiEvent::Change(_, UiValue::Index(k)) if matches!(n.kind, UiKind::DropDownList | UiKind::ListBox) => match k { + Some(k) if k >= n.items.len() => Err(format!("the list {} has no item {k}", label(n))), + k => Ok(UiEvent::Change(id, UiValue::Index(k))), + }, + UiEvent::Change(..) => Err(format!("the control {} cannot take that change", label(n))), + UiEvent::Close => Ok(UiEvent::Close), + } +} + +fn label(n: &UiNode) -> String { + let shown = if n.name.is_empty() { &n.text } else { &n.name }; + super::dialogs::cut_to(shown, 64).to_string() +} + +/// A step of a `window` answer in `script.run`'s `answers`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UiStep { + /// The control's name or text; none for a close. + pub control: Option, + pub event: String, + pub value: Option, +} + +/// The steps of a `window` answer: `[{control, event: "click"} | {control, event: "change", value} +/// | {event: "close"}]`, where `control` is a string of at most 16 KiB and `value` a string, a +/// number or null. +pub(crate) fn parse_steps(v: &Value) -> Result, String> { + let Some(list) = v.as_array() else { return Err("is a window's answer, whose `value` must be a list of steps".into()) }; + list.iter().enumerate().map(|(i, s)| step(s).ok_or_else(|| format!("has a step {i} that is not a valid click, change or close"))).collect() +} + +fn step(s: &Value) -> Option { + let o = s.as_object()?; + if o.keys().any(|k| !matches!(k.as_str(), "control" | "event" | "value")) { + return None; + } + let control = match o.get("control") { + None => None, + Some(Value::String(c)) if c.len() <= MAX_TEXT_BYTES => Some(c.clone()), + Some(_) => return None, + }; + let value = o.get("value").cloned(); + let event = o.get("event").and_then(Value::as_str)?; + let fits = match event { + "close" => control.is_none() && value.is_none(), + "click" => control.is_some() && value.is_none(), + "change" => control.is_some() && matches!(value, Some(Value::String(_) | Value::Number(_) | Value::Null)), + _ => false, + }; + fits.then(|| UiStep { control, event: event.to_string(), value }) +} + +/// The event `step` is for `dialog`. +pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result { + let Some(control) = &step.control else { return Ok(UiEvent::Close) }; + let Some(id) = dialog.find(control) else { return Err(format!("the dialog has no control named {}", super::dialogs::cut_to(control, 64))) }; + let event = match (step.event.as_str(), &step.value) { + ("click", _) => UiEvent::Click(id), + (_, Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), + (_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match list_index(n) { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))), + None => return Err("a list's `value` must be an item index or null".into()), + }, + (_, Some(Value::Number(n))) => UiEvent::Change(id, UiValue::Number(n.as_f64().unwrap_or(f64::NAN))), + (_, Some(Value::Null)) => UiEvent::Change(id, UiValue::Index(None)), + _ => return Err("a change's `value` must be a string, a number or null".into()), + }; + check_event(dialog, event) +} + +/// A list's item index written as a JSON number: a whole number of 0 or more, as an integer or as +/// a float such as `1.0`; an index past the end stays past it. `None` for a fraction or a negative +/// number. +pub fn list_index(n: &serde_json::Number) -> Option { + if let Some(k) = n.as_u64() { + return Some(usize::try_from(k).unwrap_or(usize::MAX)); + } + let f = n.as_f64()?; + // `as` saturates a whole number too large for usize at usize::MAX. + (f >= 0.0 && f.fract() == 0.0).then_some(f as usize) +} + +fn field<'a>(fields: &'a [(String, Data)], name: &str) -> &'a Data { + fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v) +} + +fn bad(what: &str) -> HostError { + HostError::Type(format!("show: the dialog's description {what}")) +} + +/// A finite number. +fn number(d: &Data) -> Option { + match d { + Data::Number(n) if n.is_finite() => Some(*n), + _ => None, + } +} + +fn text(d: &Data, what: &str) -> Result { + match d { + Data::String(s) if s.len() <= MAX_TEXT_BYTES => Ok(s.clone()), + Data::String(_) => Err(HostError::Range(format!("show: {what} is longer than 16 KiB"))), + _ => Err(bad(&format!("has no {what}"))), + } +} + +fn extent(n: f64) -> f32 { + (n as f32).clamp(-MAX_EXTENT, MAX_EXTENT) +} + +fn align_name(s: &str, horizontal: Option) -> Result<(Option, Option), HostError> { + let a = match (s, horizontal) { + ("left", Some(true) | None) => (Some(Align::Start), None), + ("right", Some(true) | None) => (Some(Align::End), None), + ("top", Some(false) | None) => (None, Some(Align::Start)), + ("bottom", Some(false) | None) => (None, Some(Align::End)), + ("center", _) => (Some(Align::Center), Some(Align::Center)), + ("fill", _) => (Some(Align::Fill), Some(Align::Fill)), + _ => return Err(HostError::Error(format!("show: there is no alignment {}", super::dialogs::cut_to(s, 64)))), + }; + Ok(match horizontal { + Some(true) => (a.0, None), + Some(false) => (None, a.1), + None => a, + }) +} + +fn alignment(d: &Data) -> Result<(Option, Option), HostError> { + match d { + Data::Null | Data::Undefined => Ok((None, None)), + Data::String(s) => align_name(s, None), + Data::Array(a) if a.len() == 2 => { + let part = |d: &Data, h: bool| match d { + Data::String(s) => align_name(s, Some(h)), + _ => Err(bad("has an alignment that is not a name")), + }; + Ok((part(&a[0], true)?.0, part(&a[1], false)?.1)) + } + _ => Err(bad("has an alignment that is not a name or a pair of names")), + } +} + +fn numbers(d: &Data) -> Result, HostError> { + match d { + Data::Null | Data::Undefined => Ok(None), + Data::Array(a) if a.len() == N => { + let mut out = [0.0; N]; + for (o, v) in out.iter_mut().zip(a) { + *o = number(v).ok_or_else(|| bad("has a size that is not a number"))?; + } + Ok(Some(out)) + } + _ => Err(bad("has a size with the wrong count of numbers")), + } +} + +/// Reads, checks and lays out a dialog's description. +pub fn parse(d: &Data) -> Result { + let Data::Object(top) = d else { return Err(bad("is not an object")) }; + let Data::Array(list) = field(top, "nodes") else { return Err(bad("has no list of controls")) }; + if list.is_empty() { + return Err(bad("has no dialog")); + } + if list.len() > MAX_CONTROLS + 1 { + return Err(HostError::Range(format!("show: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + let mut nodes: Vec = Vec::with_capacity(list.len()); + let mut depth: Vec = Vec::with_capacity(list.len()); + let mut items_total = 0usize; + for (i, n) in list.iter().enumerate() { + let Data::Object(f) = n else { return Err(bad("has a control that is not an object")) }; + let kind = match field(f, "kind") { + Data::String(k) => UiKind::parse(k).ok_or_else(|| bad("has a control of a kind that does not exist"))?, + _ => return Err(bad("has a control without a kind")), + }; + let parent = number(field(f, "parent")).ok_or_else(|| bad("has a control without its container"))?; + let parent = if i == 0 { + if kind != UiKind::Dialog || parent != -1.0 { + return Err(bad("does not start with the dialog")); + } + 0 + } else { + let p = parent as usize; + if parent < 0.0 || parent.fract() != 0.0 || p >= i || kind == UiKind::Dialog { + return Err(bad("has a control before its container")); + } + if !nodes[p].kind.container() { + return Err(bad("has a control inside a control that holds none")); + } + p + }; + let level = if i == 0 { 0 } else { depth[parent] + 1 }; + if level > MAX_DEPTH { + return Err(HostError::Range(format!("show: controls can be nested at most {MAX_DEPTH} deep"))); + } + depth.push(level); + let flag = |name: &str| matches!(field(f, name), Data::Bool(true)); + let (parent_enabled, parent_visible) = if i == 0 { (true, true) } else { (nodes[parent].enabled, nodes[parent].visible) }; + let items = match field(f, "items") { + Data::Array(a) => a.iter().map(|t| text(t, "a list item's text")).collect::, _>>()?, + _ => Vec::new(), + }; + items_total = items_total.saturating_add(items.len()); + if items_total > MAX_ITEMS { + return Err(HostError::Range(format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let selection = number(field(f, "selection")).map(|k| k as usize).filter(|k| *k < items.len()); + let (min, max) = (number(field(f, "minvalue")).unwrap_or(0.0), number(field(f, "maxvalue")).unwrap_or(100.0)); + if min > max { + return Err(HostError::Range("show: a slider's or progress bar's minvalue is larger than its maxvalue".into())); + } + let orientation = match field(f, "orientation") { + Data::String(s) if s == "row" => Orientation::Row, + Data::String(s) if s == "column" => Orientation::Column, + Data::String(s) if s == "stack" => Orientation::Stack, + Data::Undefined => Orientation::Column, + _ => return Err(HostError::Error("show: a container's orientation must be row, column or stack".into())), + }; + let bounds = numbers::<4>(field(f, "bounds"))?.map(|[l, t, r, b]| { + let (l, t) = (extent(l), extent(t)); + UiRect { x: l, y: t, w: (extent(r) - l).clamp(0.0, MAX_EXTENT), h: (extent(b) - t).clamp(0.0, MAX_EXTENT) } + }); + // A width or height of 0 or less leaves that side to the layout. + let sides = |name: &str| -> Result<[Option; 2], HostError> { + Ok(numbers::<2>(field(f, name))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))])) + }; + let (size, min_size, max_size) = (sides("size")?, sides("min")?, sides("max")?); + let margins = numbers::<4>(field(f, "margins"))?.map_or([0.0; 4], |m| m.map(|v| extent(v).max(0.0))); + nodes.push(UiNode { + kind, + id: number(field(f, "id")).filter(|n| *n >= 0.0 && n.fract() == 0.0 && *n < 9.0e15).map_or(i as u64, |n| n as u64), + parent, + name: text(field(f, "name"), "a control's name")?, + text: text(field(f, "text"), "a control's text")?, + enabled: flag("enabled") && parent_enabled, + visible: flag("visible") && parent_visible, + checked: flag("value"), + value: number(field(f, "value")).unwrap_or(0.0).clamp(min, max), + min, + max, + items, + items_revision: number(field(f, "itemsRevision")).map_or(0, |n| n as u64), + selection, + multiline: flag("multiline"), + readonly: flag("readonly"), + rect: UiRect::default(), + orientation, + align_children: alignment(field(f, "alignChildren"))?, + alignment: alignment(field(f, "alignment"))?, + spacing: number(field(f, "spacing")).map_or(0.0, |s| extent(s).max(0.0)), + margins, + size, + min_size, + max_size, + bounds, + // At most as many characters as the longest text holds. + characters: number(field(f, "characters")).filter(|c| *c > 0.0).map(|c| (c as f32).min(MAX_TEXT_BYTES as f32)), + }); + } + let target = |name: &str| number(field(top, name)).map(|k| k as usize).filter(|k| nodes.get(*k).is_some_and(|n| n.kind == UiKind::Button)); + let (default_element, cancel_element) = (target("defaultElement"), target("cancelElement")); + let mut dialog = ScriptUiDialog { nodes, default_element, cancel_element, shown: 0 }; + layout(&mut dialog); + Ok(dialog) +} + +/// A control's own size, by VectorCraft's estimates. +fn own_size(n: &UiNode) -> [f32; 2] { + let chars = |s: &str| s.chars().count() as f32; + let widest = |lines: &mut dyn Iterator| lines.map(chars).fold(0.0, f32::max); + let lines = |s: &str| s.lines().count().max(1) as f32; + let longest_item = n.items.iter().map(|t| chars(t)).fold(0.0, f32::max); + // `characters` reserves room for that many characters, however long the text is now. + let reserved = n.characters.unwrap_or(0.0); + match n.kind { + UiKind::StaticText => [widest(&mut n.text.lines()).max(reserved) * CHAR + 4.0, lines(&n.text) * LINE + 4.0], + UiKind::Button => [(chars(&n.text) * CHAR + 24.0).max(80.0), 24.0], + UiKind::CheckBox | UiKind::RadioButton => [chars(&n.text) * CHAR + 24.0, 20.0], + UiKind::EditText if n.multiline => { + [(widest(&mut n.text.lines()).max(reserved) * CHAR + 12.0).max(160.0), lines(&n.text).max(3.0) * LINE + 10.0] + } + UiKind::EditText => [(chars(&n.text).max(reserved) * CHAR + 12.0).max(80.0), 24.0], + UiKind::DropDownList => [(longest_item * CHAR + 40.0).max(100.0), 24.0], + UiKind::ListBox => [(longest_item * CHAR + 24.0).max(120.0), (n.items.len() as f32).clamp(3.0, 10.0) * 18.0 + 6.0], + UiKind::Slider => [160.0, 20.0], + UiKind::ProgressBar => [160.0, 12.0], + UiKind::Dialog | UiKind::Group | UiKind::Panel => [0.0, 0.0], + } +} + +/// Lays the dialog out: each control's size from the last to the first, then each place from the +/// first to the last. +fn layout(d: &mut ScriptUiDialog) { + let n = d.nodes.len(); + let mut kids: Vec> = vec![Vec::new(); n]; + for (i, node) in d.nodes.iter().enumerate().skip(1) { + kids[node.parent].push(i); + } + let mut size = vec![[0.0f32; 2]; n]; + for i in (0..n).rev() { + let node = &d.nodes[i]; + let mut s = if node.kind.container() { + let [l, t, r, b] = node.margins; + let (mut main, mut cross, mut count, mut reach) = (0.0f32, 0.0f32, 0usize, [0.0f32; 2]); + for &k in &kids[i] { + // A hidden control, and everything in it, takes no room. + if !d.nodes[k].visible { + continue; + } + if let Some(bounds) = d.nodes[k].bounds { + reach = [reach[0].max(bounds.x + bounds.w), reach[1].max(bounds.y + bounds.h)]; + continue; + } + let [w, h] = size[k]; + count += 1; + match node.orientation { + Orientation::Row => (main, cross) = (main + w, cross.max(h)), + Orientation::Column => (main, cross) = (main + h, cross.max(w)), + Orientation::Stack => (main, cross) = (main.max(w), cross.max(h)), + } + } + if node.orientation != Orientation::Stack { + main += node.spacing * count.saturating_sub(1) as f32; + } + let (w, h) = match node.orientation { + Orientation::Row | Orientation::Stack => (main, cross), + Orientation::Column => (cross, main), + }; + [(w + l + r).max(reach[0]), (h + t + b).max(reach[1])] + } else { + own_size(node) + }; + for axis in 0..2 { + if let Some(v) = node.size[axis] { + s[axis] = v; + } + if let Some(v) = node.min_size[axis] { + s[axis] = s[axis].max(v); + } + if let Some(v) = node.max_size[axis] { + s[axis] = s[axis].min(v); + } + } + if let Some(b) = node.bounds { + s = [b.w, b.h]; + } + size[i] = [s[0].clamp(0.0, MAX_EXTENT), s[1].clamp(0.0, MAX_EXTENT)]; + } + d.nodes[0].rect = UiRect { x: 0.0, y: 0.0, w: size[0][0], h: size[0][1] }; + for i in 0..n { + if !d.nodes[i].kind.container() { + continue; + } + let node = d.nodes[i].clone(); + let [l, t, r, b] = node.margins; + let (x, y) = (node.rect.x + l, node.rect.y + t); + let (cw, ch) = ((node.rect.w - l - r).max(0.0), (node.rect.h - t - b).max(0.0)); + let mut cursor = 0.0f32; + for &k in &kids[i] { + let kid = &d.nodes[k]; + let rect = if !kid.visible { + UiRect { x, y, w: 0.0, h: 0.0 } + } else if let Some(bounds) = kid.bounds { + UiRect { x: node.rect.x + bounds.x, y: node.rect.y + bounds.y, w: bounds.w, h: bounds.h } + } else { + let [w, h] = size[k]; + let h_align = kid.alignment.0.or(node.align_children.0).unwrap_or(Align::Center); + let v_align = kid.alignment.1.or(node.align_children.1).unwrap_or(Align::Center); + let max = kid.max_size; + // A control that fills its container's room stays within its maximum. + let place = |align: Align, own: f32, room: f32, axis: usize| match align { + Align::Start => (0.0, own), + Align::End => ((room - own).max(0.0), own), + Align::Center => (((room - own) / 2.0).max(0.0), own), + Align::Fill => (0.0, max[axis].map_or(room.max(own), |m| room.max(own).min(m.max(own)))), + }; + match node.orientation { + Orientation::Row => { + let (dy, kh) = place(v_align, h, ch, 1); + let r = UiRect { x: x + cursor, y: y + dy, w, h: kh }; + cursor += w + node.spacing; + r + } + Orientation::Column => { + let (dx, kw) = place(h_align, w, cw, 0); + let r = UiRect { x: x + dx, y: y + cursor, w: kw, h }; + cursor += h + node.spacing; + r + } + Orientation::Stack => { + let (dx, kw) = place(h_align, w, cw, 0); + let (dy, kh) = place(v_align, h, ch, 1); + UiRect { x: x + dx, y: y + dy, w: kw, h: kh } + } + } + }; + d.nodes[k].rect = UiRect { + x: rect.x.clamp(-MAX_EXTENT, MAX_EXTENT), + y: rect.y.clamp(-MAX_EXTENT, MAX_EXTENT), + w: rect.w.clamp(0.0, MAX_EXTENT), + h: rect.h.clamp(0.0, MAX_EXTENT), + }; + } + } +} + +/// The dialog of one `show()`: the steps left for a run with nobody to ask, and how many events it +/// took. +pub(crate) struct Showing { + pub(crate) dialog: ScriptUiDialog, + pub(crate) steps: Option>, + pub(crate) events: u64, +} + +impl Showing { + /// The report's record of the dialog, with its `answer`: the result of `show()`, `"stop"`, + /// `"missing"` or `"error"`. + pub(crate) fn record(&self, answer: Value) -> Value { + let mut r = Map::new(); + r.insert("kind".into(), json!("window")); + r.insert("title".into(), json!(super::dialogs::cut_to(self.dialog.title(), super::dialogs::MAX_TITLE_BYTES))); + r.insert("controls".into(), json!(self.dialog.nodes.len().saturating_sub(1))); + r.insert("events".into(), json!(self.events)); + r.insert("answer".into(), answer); + Value::Object(r) + } +} + +/// The host function `name` of `Window`, for the run `link` holds. +fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> HostItem { + let l = link.clone(); + HostItem::Function(Rc::new(move |a| f(&*super::current(&l)?, &a))) +} + +/// Adds `Window` to the realm, for the run `link` holds. +pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> { + realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))]) +} + +fn described(host: &Host, args: &[Data]) -> Result { + host.charge_call(args.iter().map(super::data_size).sum())?; + parse(args.first().unwrap_or(&Data::Undefined)) +} + +fn open(host: &Host, args: &[Data]) -> Result { + let dialog = described(host, args)?; + host.dialogs.window_open(dialog)?; + Ok(Data::Undefined) +} + +fn wait(host: &Host, args: &[Data]) -> Result { + let dialog = described(host, args)?; + host.dialogs.window_wait(dialog) +} + +fn end(host: &Host, args: &[Data]) -> Result { + let result = number(args.first().unwrap_or(&Data::Undefined)).unwrap_or(0.0); + let normal = matches!(args.get(1), Some(Data::Bool(true))); + host.dialogs.window_end(result, normal)?; + Ok(Data::Undefined) +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 11b5c4965f..8a9eea3b4a 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -190,7 +190,9 @@ impl Session { startup_loading: None, startup_failures: vec![], script_high_water: Default::default(), + script_style_trail: Default::default(), script_in_run: false, + window_views: vec![], script_copy_first: cfg!(target_arch = "wasm32"), } } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 8b8bef8679..eec49be0c7 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -129,6 +129,9 @@ impl Session { self.execute_spec(spec, id, params) }; self.reading = outer; + if self.script_in_run && self.depth > 0 && r.is_ok() { + crate::script::note_style_lists(self); + } r } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6b3dcf0822..62da1ac085 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -49,7 +49,7 @@ mod css; mod curvature_circle; mod cut; mod dashalign; -mod dcs; +pub(super) mod dcs; mod delete_keeps_joined; mod distort; mod docsetup; @@ -177,6 +177,7 @@ mod repeat_edit; mod save; mod saveoptions; mod scalestrokes; +mod script_actions; mod script_console; mod script_dialogs; mod script_dollar; @@ -186,7 +187,11 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_scriptui; +mod script_styles; mod script_tags; +mod script_text; +mod script_threads; mod script_variables; mod script_xmp; mod scripts; @@ -4521,6 +4526,69 @@ fn object_mosaic_tiles_follow_the_image_colours() { assert!(!st.doc.layers[0].children().unwrap().iter().any(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)))); } +/// On an image changed by Perspective Distort, each tile is its cell placed between the image's corners: its four +/// anchors are the cell's corners mapped as the image's pixels are, in one undo step. A new size resizes the warped +/// tiles as it resizes the image's bounds, and spacing is measured at the mean length of the image's sides. +#[test] +fn object_mosaic_tiles_of_a_distorted_image_follow_its_corners() { + use vectorcraft_geom::Point; + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [a.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true, "ids": [a.0]})).unwrap(); + let b = rect(&mut s, 50.0, 0.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": [b.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true, "ids": [b.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + s.execute("object.distort", &json!({"corners": [[20, 0], [80, 0], [100, 50], [0, 50]]})).unwrap(); + let image = s.doc().unwrap().selection.objects.clone(); + let node = s.doc().unwrap().doc.node(image[0]).unwrap().clone(); + assert!(node.is_distorted_image()); + let vectorcraft_doc::NodeKind::Image(im) = &node.kind else { panic!("not an image") }; + let (w, h) = (f64::from(im.width), f64::from(im.height)); + let map = node.image_map().unwrap(); + let at = |x: f64, y: f64| map.apply(Point::new(x, y)).unwrap(); + let anchors = |n: &vectorcraft_doc::Node| n.path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect::>(); + let near = |got: &[Point], want: &[Point]| got.len() == want.len() && got.iter().zip(want).all(|(g, w)| g.distance(*w) < 1e-6); + let tiles_of = |s: &Session, r: &serde_json::Value| { + s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().children().unwrap().iter().map(|t| (**t).clone()).collect::>() + }; + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("object.createObjectMosaic", &json!({"columns": 2, "rows": 2})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let tiles = tiles_of(&s, &r); + assert_eq!(tiles.len(), 4); + for (i, t) in tiles.iter().enumerate() { + let (x0, y0) = ((i % 2) as f64 * w / 2.0, (i / 2) as f64 * h / 2.0); + let want = [at(x0, y0), at(x0 + w / 2.0, y0), at(x0 + w / 2.0, y0 + h / 2.0), at(x0, y0 + h / 2.0)]; + assert!(near(&anchors(t), &want), "tile {i}: {:?} against {want:?}", anchors(t)); + } + // The first tile starts at the image's top left corner and its right side halves the top edge; the row line is + // nearer the narrow top, as the perspective puts the image's middle row there. + assert!(anchors(&tiles[0])[0].distance(Point::new(20.0, 0.0)) < 1e-6, "{:?}", anchors(&tiles[0])); + assert!((anchors(&tiles[0])[1].x - 50.0).abs() < 1e-6, "{:?}", anchors(&tiles[0])); + assert!(anchors(&tiles[0])[2].y < 24.0, "{:?}", anchors(&tiles[0])); + let fill = |n: &vectorcraft_doc::Node| n.appearance.fill_paint(); + assert_eq!(fill(&tiles[0]), vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(fill(&tiles[1]), vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))); + // Twice the width: the warped tiles stretch from the left of the image's bounds. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({ "ids": image })).unwrap(); + let r = s.execute("object.createObjectMosaic", &json!({"columns": 2, "rows": 2, "width": 200, "percentages": true})).unwrap(); + let tiles = tiles_of(&s, &r); + let stretched = |p: Point| Point::new(p.x * 2.0, p.y); + assert!(near(&anchors(&tiles[3]), &[at(w / 2.0, h / 2.0), at(w, h / 2.0), at(w, h), at(w / 2.0, h)].map(stretched)), "{:?}", anchors(&tiles[3])); + // 8 pt between columns: the image's top and bottom sides are 60 and 100 pt long, so a pixel is 80 / w pt across + // and the gap is w / 10 pixels, half of it on each side of a tile. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({ "ids": image })).unwrap(); + let r = s.execute("object.createObjectMosaic", &json!({"columns": 2, "rows": 1, "spacingX": 8})).unwrap(); + let tiles = tiles_of(&s, &r); + let g = w / 20.0; + assert!(near(&anchors(&tiles[0]), &[at(g, 0.0), at(w / 2.0 - g, 0.0), at(w / 2.0 - g, h), at(g, h)]), "{:?}", anchors(&tiles[0])); +} + /// Columns and rows that are not whole numbers (a fraction, a negative number, a string or another value) are an /// error naming the key, and no mosaic is made; 2.0 columns are two columns. #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 7ac6b8c4e2..032e3ddb8c 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -242,6 +242,70 @@ fn options_of_selected_object_keep_each_paths_largest_width_when_the_width_chang assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((40.0, 120.0), (40.0, 120.0))); } +/// The scales (%) the first stroke of `id`, painted with Stitches, draws with where the pen reads 0 +/// and 1. +fn stitches_scale_range(s: &Session, id: NodeId) -> (f64, f64) { + let lib = vectorcraft_brush::library(&s.doc().unwrap().doc); + let b = lib.iter().find(|b| b.name == "Stitches").unwrap(); + match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind { + vectorcraft_brush::BrushKind::Pattern(p) => p.scale_range(), + k => panic!("not a pattern brush: {k:?}"), + } +} + +#[test] +fn options_of_selected_object_keep_each_paths_second_scale_when_the_scale_changes() { + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + s.execute("brush.apply", &json!({"name": "Stitches", "ids": [a.0, b.0]})).unwrap(); + // Both scales follow the pressure; the first path's second scale is its scale, the second + // path's is its own. + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100, "scale_mode": "pressure"}})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"scale": 100, "scale_mode": "pressure", "scale_max": 150}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((100.0, 100.0), (100.0, 150.0))); + // The scale the path has already changes nothing. + let steps = undo_steps(&s); + assert_eq!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100}})).unwrap()["changed"], json!([])); + assert_eq!(own_options(&s, a), json!({"scale_mode": "pressure"})); + assert_eq!(undo_steps(&s), steps); + // A new first scale leaves each path's second scale as it was. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 50}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((50.0, 100.0), (50.0, 150.0))); + // A second scale the params give is set on each path, and the brush keeps its own. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 40, "scale_max": 120}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((40.0, 120.0), (40.0, 120.0))); + let def = s.execute("brush.get", &json!({"name": "Stitches"})).unwrap(); + assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}"); + // A mode that is not one is refused, and nothing changes. + let steps = undo_steps(&s); + assert!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale_mode": "sideways"}})).is_err()); + assert_eq!(undo_steps(&s), steps); +} + +/// Pattern Brush Options' Scale mode and second scale go through `brush.new`, `brush.options` +/// and `brush.get`; a partial edit keeps the other fields, and Fixed leaves both out. +#[test] +fn pattern_brush_scale_mode_goes_through_the_brush_commands() { + let mut s = session(); + let side = rect(&mut s, 0.0, 0.0, 40.0, 8.0); + let params = json!({"scale": 50, "scale_mode": "tilt", "scale_max": 300}); + s.execute("brush.new", &json!({"type": "pattern", "name": "Rail", "params": params, "ids": [side.0]})).unwrap(); + let get = |s: &mut Session| s.execute("brush.get", &json!({"name": "Rail"})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(300.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_max": 200, "spacing": 10}})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(200.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "stylusWheel", "scale_max": 1e9}})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale_mode"], &def["scale_max"]), (&json!("stylusWheel"), &json!(10000.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": null, "scale_max": null}})).unwrap(); + let def = get(&mut s); + assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}"); + assert!(s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "sideways"}})).is_err()); +} + #[test] fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() { let mut s = session(); @@ -1810,6 +1874,82 @@ fn scatter_hue_jitter_saves_and_exports() { assert_eq!(piece_fills(&s.doc().unwrap().doc, id), plain); } +/// Scatter Brush Options' `saturation_jitter`: shown by `brush.get`, set by `brush.options` (a value +/// past 100 clamped), saved with the document, and the moved colors drawn the same after Open and +/// written by SVG export. +#[test] +fn scatter_saturation_jitter_saves_and_exports() { + let mut s = session(); + let r = rect(&mut s, 10.0, 200.0, 8.0, 8.0); + s.execute("paint.setFill", &json!({"color": "#cc6666"})).unwrap(); + let name = s.execute("brush.new", &json!({"type": "scatter", "name": "Confetti", "ids": [r.0]})).unwrap()["name"].as_str().unwrap().to_string(); + let id = line(&mut s); + select(&mut s, &[id]); + s.execute("brush.apply", &json!({ "name": name })).unwrap(); + let plain = piece_fills(&s.doc().unwrap().doc, id); + assert!(plain.len() > 10 && plain.iter().all(|c| c == "#cc6666"), "{plain:?}"); + let get = |s: &mut Session| s.execute("brush.get", &json!({ "name": name })).unwrap()["saturation_jitter"].clone(); + assert_eq!(get(&mut s), json!(0.0), "brush.get shows the option at 0"); + s.execute("brush.options", &json!({"name": name, "params": {"saturation_jitter": 250}})).unwrap(); + assert_eq!(get(&mut s), json!(100.0), "a value past 100 is clamped"); + s.execute("brush.options", &json!({"name": name, "params": {"saturation_jitter": 40}})).unwrap(); + assert_eq!(get(&mut s), json!(40.0)); + let doc = s.doc().unwrap().doc.clone(); + let moved = piece_fills(&doc, id); + assert_eq!(moved.len(), plain.len()); + let distinct: std::collections::HashSet<&String> = moved.iter().collect(); + assert!(distinct.len() > 5, "{moved:?}"); + // Saved and opened again, the stroke draws the same colors. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert_eq!(piece_fills(&back, id), moved); + // SVG export writes each copy's moved color. + let svg = vectorcraft_svg::export(&doc, &Default::default()); + for c in &distinct { + assert!(svg.contains(&format!("fill=\"{c}\"")), "{c} missing from the SVG"); + } + // Back to 0, the copies draw the art's own color. + s.execute("brush.options", &json!({"name": name, "params": {"saturation_jitter": 0}})).unwrap(); + assert_eq!(piece_fills(&s.doc().unwrap().doc, id), plain); +} + +/// Scatter Brush Options' `brightness_jitter`: shown by `brush.get`, set by `brush.options` (a value +/// past 100 clamped), saved with the document, and the moved colors drawn the same after Open and +/// written by SVG export. +#[test] +fn scatter_brightness_jitter_saves_and_exports() { + let mut s = session(); + let r = rect(&mut s, 10.0, 200.0, 8.0, 8.0); + s.execute("paint.setFill", &json!({"color": "#cc6666"})).unwrap(); + let name = s.execute("brush.new", &json!({"type": "scatter", "name": "Confetti", "ids": [r.0]})).unwrap()["name"].as_str().unwrap().to_string(); + let id = line(&mut s); + select(&mut s, &[id]); + s.execute("brush.apply", &json!({ "name": name })).unwrap(); + let plain = piece_fills(&s.doc().unwrap().doc, id); + assert!(plain.len() > 10 && plain.iter().all(|c| c == "#cc6666"), "{plain:?}"); + let get = |s: &mut Session| s.execute("brush.get", &json!({ "name": name })).unwrap()["brightness_jitter"].clone(); + assert_eq!(get(&mut s), json!(0.0), "brush.get shows the option at 0"); + s.execute("brush.options", &json!({"name": name, "params": {"brightness_jitter": 250}})).unwrap(); + assert_eq!(get(&mut s), json!(100.0), "a value past 100 is clamped"); + s.execute("brush.options", &json!({"name": name, "params": {"brightness_jitter": 15}})).unwrap(); + assert_eq!(get(&mut s), json!(15.0)); + let doc = s.doc().unwrap().doc.clone(); + let moved = piece_fills(&doc, id); + assert_eq!(moved.len(), plain.len()); + let distinct: std::collections::HashSet<&String> = moved.iter().collect(); + assert!(distinct.len() > 5, "{moved:?}"); + // Saved and opened again, the stroke draws the same colors. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert_eq!(piece_fills(&back, id), moved); + // SVG export writes each copy's moved color. + let svg = vectorcraft_svg::export(&doc, &Default::default()); + for c in &distinct { + assert!(svg.contains(&format!("fill=\"{c}\"")), "{c} missing from the SVG"); + } + // Back to 0, the copies draw the art's own color. + s.execute("brush.options", &json!({"name": name, "params": {"brightness_jitter": 0}})).unwrap(); + assert_eq!(piece_fills(&s.doc().unwrap().doc, id), plain); +} + /// The bounds of the brush art `id`'s strokes draw. fn brushed_bounds(s: &Session, id: NodeId) -> Rect { let st = s.doc().unwrap(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 320d6ba70f..6ccdfad0a5 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4046,6 +4046,26 @@ fn live_paint_bucket_refuses_a_bad_target_or_aligned() { } } +/// With nothing selected, Invert and Complement refuse a bad `target` or `aligned` and leave the +/// default fill and stroke as they are. +#[test] +fn invert_and_complement_refuse_a_bad_target_or_aligned_with_nothing_selected() { + let mut s = session(); + s.execute("paint.setFill", &json!({"color": "#336699", "defaultsOnly": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = (s.paint.fill.clone(), s.paint.stroke.clone()); + for cmd in ["paint.invert", "paint.complement"] { + for p in + [json!({"stroke": false, "target": "content"}), json!({"stroke": false, "aligned": "yes"}), json!({"stroke": true, "target": "bogus"})] + { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone()), before, "{cmd} {p}"); + } + } + s.execute("paint.invert", &json!({"stroke": false})).unwrap(); + assert_ne!(s.paint.fill, before.0, "a good call still inverts the default"); +} + /// While the Live Paint Bucket is active, each preview of a paint command in one interaction starts /// from the colors the interaction began with, so previewing a swap twice and committing swaps once. #[test] diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index ffb842bca8..7b72a06089 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -847,6 +847,87 @@ fn pie_legend_labels_follow_wedges_that_take_the_documents_swatch() { assert_eq!(north, Some(Paint::solid(Color::WHITE)), "in an opacity mask"); } +/// A pie in the art of a symbol or a pattern that a paste brings in follows the document's swatch as a pasted pie does: +/// with Merge, its legend label in the wedge that turned dark is white, and pasting again uses the symbol or pattern the +/// first paste added. With Add the label stays black. +#[test] +fn pie_legend_labels_in_a_pasted_symbol_or_pattern_follow_wedges_that_take_the_documents_swatch() { + let csv = ",North,South\nP,1,1"; + /// A pie with Legends in Wedges whose first wedge is filled with the global swatch "Brand", light yellow. + fn branded_pie(s: &mut Session, csv: &str) -> NodeId { + if doc(s).swatch("Brand").is_none() { + s.execute("swatch.new", &json!({"name": "Brand", "color": "#ffff66", "global": true})).unwrap(); + } + let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap()); + s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap(); + let mut wedges = vec![]; + for c in node(s, g).children().unwrap().iter().filter(|c| c.extras().series_index == Some(0)) { + c.walk(&mut |m| { + if matches!(m.kind, NodeKind::Path { .. }) { + wedges.push(m.id.0); + } + }); + } + assert!(!wedges.is_empty()); + s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Brand"})).unwrap(); + s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap(); + g + } + /// The fill of the legend label that says `name` in `art`. + fn label_in(art: &[std::sync::Arc], name: &str) -> Paint { + let mut out = None; + for a in art { + a.walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && t.plain_text() == name + { + out = Some(t.first_style().fill.clone()); + } + }); + } + out.unwrap() + } + let symbol_art = |s: &Session| vec![doc(s).symbols.iter().find(|x| x.name == "Chart").unwrap().art.clone()]; + let pattern_art = |s: &Session| doc(s).pattern("Chart").unwrap().art.clone(); + + let mut s = session(); + let g = branded_pie(&mut s, csv); + sel(&mut s, &[g]); + let instance = id_of(&s.execute("symbol.new", &json!({"name": "Chart"})).unwrap()); + assert_eq!(label_in(&symbol_art(&s), "North"), Paint::solid(Color::BLACK), "black on the light wedge"); + copy(&mut s, &[instance]); + for (choice, north) in [("merge", Color::WHITE), ("add", Color::BLACK)] { + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap(); + s.execute("edit.paste", &json!({"swatchConflict": choice})).unwrap(); + assert_eq!(label_in(&symbol_art(&s), "North"), Paint::solid(north), "symbol {choice}"); + assert_eq!(label_in(&symbol_art(&s), "South"), Paint::solid(Color::BLACK), "symbol {choice}"); + // Pasting again uses the symbol the first paste added. + s.execute("edit.paste", &json!({"swatchConflict": choice})).unwrap(); + let names: Vec<&str> = doc(&s).symbols.iter().map(|x| x.name.as_str()).collect(); + assert_eq!(names, ["Chart"], "symbol {choice}"); + } + + let mut s = session(); + let g = branded_pie(&mut s, csv); + s.execute("object.pattern.make", &json!({"name": "Chart", "edit": false, "ids": [g.0]})).unwrap(); + assert_eq!(label_in(&pattern_art(&s), "North"), Paint::solid(Color::BLACK), "black on the light wedge"); + let r = rect(&mut s, 300.0, 300.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"ids": [r.0], "swatch": "Chart"})).unwrap(); + copy(&mut s, &[r]); + for (choice, north) in [("merge", Color::WHITE), ("add", Color::BLACK)] { + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap(); + s.execute("edit.paste", &json!({"swatchConflict": choice})).unwrap(); + assert_eq!(label_in(&pattern_art(&s), "North"), Paint::solid(north), "pattern {choice}"); + assert_eq!(label_in(&pattern_art(&s), "South"), Paint::solid(Color::BLACK), "pattern {choice}"); + // Pasting again uses the pattern the first paste added. + s.execute("edit.paste", &json!({"swatchConflict": choice})).unwrap(); + let names: Vec<&str> = doc(&s).patterns.iter().map(|x| x.name.as_str()).collect(); + assert_eq!(names, ["Chart"], "pattern {choice}"); + } +} + /// A two-line legend label in a narrow dark wedge, whose text sits off the wedge's middle line, stays white when its graph /// is pasted without formatting. #[test] diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index c5a480323b..e16542edb2 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -357,6 +357,48 @@ fn convert_to_oklch_answers_lightness_chroma_and_hue() { assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}"); } +/// `color.parse` reads each notation into an RGB color, its hex and the alpha as a percentage (null +/// when the text gives none), and answers an error for anything else. +#[test] +fn parse_reads_hex_with_alpha_and_css_colors() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let mut parse = |text: &str| s.execute("color.parse", &json!({ "text": text })); + for (text, opacity) in [ + ("#33669980", json!(50.2)), + ("33669980", json!(50.2)), + ("#3698", json!(53.33)), + ("#336699", Value::Null), + ("#369", Value::Null), + ("rgb(51 102 153 / 50%)", json!(50.0)), + ("rgba(51, 102, 153, 0.25)", json!(25.0)), + ("rgb(20% 40% 60%)", Value::Null), + ("hsl(210 50% 40%)", Value::Null), + ("hsla(210deg, 50%, 40%, 1)", json!(100.0)), + ] { + let r = parse(text).unwrap(); + assert_eq!(r["hex"], "#336699", "{text}: {r}"); + assert_eq!(r["opacity"], opacity, "{text}: {r}"); + let c: Color = serde_json::from_value(r["color"].clone()).unwrap(); + let Color::Rgb { r: red, g, b } = c else { panic!("{text}: {c:?}") }; + assert_eq!([red, g, b].map(|v| (v * 255.0).round() as u8), [0x33, 0x66, 0x99], "{text}"); + } + let red = parse("oklch(62.8% 0.2577 29.23 / 0.5)").unwrap(); + assert_eq!((&red["hex"], &red["opacity"]), (&json!("#ff0000"), &json!(50.0)), "{red}"); + let message = "`text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters"; + let long = format!("rgb(1 2 3{})", " ".repeat(40)); + for bad in ["", "#12345", "#gggggg", "rgb(1, 2%, 3)", "rgb(1 2)", "oklch(0.5, 0.1, 30)", "cmyk 0 100 100 0", "red", long.as_str()] { + let e = parse(bad).unwrap_err().to_string(); + assert!(e.ends_with(message), "{bad:?}: {e}"); + } + assert!(parse_err(&mut s, json!({})).ends_with("missing `text`")); + assert!(parse_err(&mut s, json!({"text": 5})).ends_with("`text` must be a string")); +} + +fn parse_err(s: &mut Session, p: Value) -> String { + s.execute("color.parse", &p).unwrap_err().to_string() +} + #[test] fn assign_profile_is_stored_and_undoable() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index a8e37ff812..34bfe7a7bc 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -56,7 +56,7 @@ fn single_file(plates: &[(&str, String)], extra: &str) -> Vec { } /// Cyan solid on the top row, PANTONE 185 C at 50% on the left column. -fn two_plates() -> Vec { +pub(crate) fn two_plates() -> Vec { single_file( &[("Cyan", plate_eps([0, 0, 255, 255])), ("PANTONE 185 C", plate_eps([127, 255, 127, 255]))], "%%DocumentCustomColors: (PANTONE 185 C)\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n", @@ -267,6 +267,33 @@ fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_cor assert_eq!(node(&s).image_corners().unwrap(), corners); } +/// Place with Replace of an image changed by Perspective Distort or Free Distort by a DCS file puts +/// the file's image between the corners and draws its clipping path through them. +#[test] +fn place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners() { + let dir = temp_dir("replace-distorted-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let png = crate::tests_links::png(4, 4, [255, 0, 0]); + let r = s.execute("file.place", &json!({ "name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100] })).unwrap(); + let old = NodeId(r["ids"][0].as_u64().unwrap()); + s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap(); + let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap(); + let r = s.execute("file.place", &json!({ "path": path, "replace": true })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = NodeId(r["image"].as_u64().unwrap()); + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(node.is_distorted_image()); + assert_eq!(node.image_corners().unwrap(), corners); + let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") }; + let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") }; + let anchors: Vec<_> = path.anchors().map(|(_, _, a)| a.p).collect(); + // The left half of the 2 × 2 pixels, where the corners put it. + let map = node.image_map().unwrap(); + let want = [(0.0, 0.0), (1.0, 0.0), (1.0, 2.0), (0.0, 2.0)].map(|(x, y)| map.apply(vectorcraft_geom::Point::new(x, y)).unwrap()); + assert!(anchors.len() == want.len() && want.iter().all(|w| anchors.iter().any(|a| a.distance(*w) < 1e-6)), "{anchors:?} vs {want:?}"); +} + #[test] fn update_link_clips_an_image_whose_file_gained_a_clipping_path() { let dir = temp_dir("update-gained-clip"); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 7fd3b2a70c..516e4fb3b0 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4045,6 +4045,24 @@ fn move_anchors_reshape_and_close_refuse_a_number_given_as_text() { assert!(after.subpaths[0].closed && moved == Some(before.subpaths[0].anchors[1].p.x + 10.0), "{after:?}"); } +/// Move Anchors by 0, with anchors or whole paths selected, changes nothing and records no undo +/// step; a move by 10 records one. +#[test] +fn move_anchors_by_zero_records_no_undo_step() { + let mut s = session(); + let id = curve(&mut s); + for select in [json!({"id": id.0, "anchors": [[0, 1]]}), json!({"id": id.0, "anchors": [[0, 0], [0, 1]]})] { + s.execute("select.anchors", &select).unwrap(); + let (before, undo) = (path(&s, id), s.doc().unwrap().history.undo.len()); + for p in [json!({}), json!({"dx": 0, "dy": 0}), json!({"dx": null, "dy": -0.0})] { + s.execute("path.moveAnchors", &p).unwrap(); + assert_eq!((path(&s, id), s.doc().unwrap().history.undo.len()), (before.clone(), undo), "{select} {p}"); + } + s.execute("path.moveAnchors", &json!({"dx": 10})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{select}"); + } +} + /// Close Path, Set Handle, Move Anchors and the Pencil, Curvature, Reshape Segment and Blob Brush /// commands refuse an on/off option given as text or as another value that is not true or false, /// naming the key, and change nothing; true, false and null still work. diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index b3ca69fbc7..0394fb18fa 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -748,3 +748,68 @@ fn deselecting_objects_one_at_a_time_looks_up_only_the_removed_objects() { assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times"); assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000"); } + +/// Taking a group of 10,000 squares out of a selection that keeps two squares reads the two +/// squares' paints again instead of taking the group's 10,000 out of them. +#[test] +fn deselecting_a_large_group_reads_the_objects_left() { + let mut s = session(3, |d, k| match k { + 0 => Node::group(d.alloc_id(), (0..10_000).map(|i| Arc::new(square(d, i + 2))).collect()), + _ => square(d, k - 1), + }); + let ids = layer(&s, 0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + assert!(selected(&s, &ids)); + let read = || crate::cmd::PAINTS_READ.with(std::cell::Cell::get); + let before = read(); + s.execute("select.toggle", &json!({"id": ids[0].0})).unwrap(); + assert!(selected(&s, &ids[1..])); + let fills = read() - before; + assert!(fills <= 100, "read or took out {fills} fills"); +} + +/// Taking a group of one square out of a selection that keeps a group of 10,000 squares takes the +/// one square out of the paints instead of reading the 10,000 again. +#[test] +fn deselecting_a_small_group_beside_a_large_one_takes_out_only_its_objects() { + let mut s = session(2, |d, k| match k { + 0 => Node::group(d.alloc_id(), vec![Arc::new(square(d, 0))]), + _ => Node::group(d.alloc_id(), (0..10_000).map(|i| Arc::new(square(d, i + 1))).collect()), + }); + let ids = layer(&s, 0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + assert!(selected(&s, &ids)); + let read = || crate::cmd::PAINTS_READ.with(std::cell::Cell::get); + let before = read(); + s.execute("select.toggle", &json!({"id": ids[0].0})).unwrap(); + assert!(selected(&s, &ids[1..])); + let fills = read() - before; + assert!(fills <= 100, "read or took out {fills} fills"); +} + +/// Taking a type object of 10,000 runs out of a selection that keeps two squares reads the two +/// squares' stroke weights again instead of taking the 10,000 run weights out of them. +#[test] +fn deselecting_type_of_many_runs_reads_the_objects_left() { + let mut s = session(3, |d, k| match k { + 0 => { + let style = vectorcraft_doc::CharStyle::default(); + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 40.0), "x", style.clone()); + t.runs = (0..10_000).map(|_| vectorcraft_doc::TextRun::new("x", style.clone())).collect(); + Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))) + } + _ => square(d, k), + }); + let ids = layer(&s, 0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + assert!(selected(&s, &ids)); + let read = || crate::cmd::WEIGHTS_READ.with(std::cell::Cell::get); + let before = read(); + s.execute("select.toggle", &json!({"id": ids[0].0})).unwrap(); + assert!(selected(&s, &ids[1..])); + let weights = read() - before; + assert!(weights <= 100, "read or took out {weights} stroke weights"); +} diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index 65fa7951cd..e2ea567acd 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -734,6 +734,34 @@ fn object_set_props_that_changes_nothing_deselects_what_it_leaves_hidden_or_lock } } +/// Layer Options that leave every row as it is change nothing and record no undo step; one that +/// changes a row records one. +#[test] +fn layer_options_that_change_nothing_record_no_undo_step() { + let mut s = session(); + let (layer, sub, a, ..) = tree(&mut s); + run(&mut s, "layer.setProps", json!({"id": sub.0, "name": "Sub", "color": "red"})); + let before = (s.doc().unwrap().doc.clone(), undos(&s)); + for p in [ + json!({}), + json!({"id": layer.0, "visible": true, "locked": false, "template": false, "printable": true, "preview": true, "dimImages": false}), + json!({"id": sub.0, "name": "Sub", "color": "red"}), + json!({"id": sub.0, "name": " "}), + json!({"ids": [a.0, sub.0], "visible": true}), + ] { + run(&mut s, "layer.setProps", p.clone()); + let after = (s.doc().unwrap().doc.clone(), undos(&s)); + assert!(after.0 == before.0 && after.1 == before.1, "{p} changes nothing"); + } + run(&mut s, "layer.setProps", json!({"id": sub.0, "locked": true})); + assert_eq!(undos(&s), before.1 + 1, "locking the sublayer is one undo step"); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let undo = undos(&s); + run(&mut s, "layer.setProps", json!({"id": sub.0, "locked": true})); + assert_eq!(undos(&s), undo, "locking it again records no undo step"); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the art of the locked sublayer is deselected"); +} + #[test] fn layer_options_validate_and_template_locks_and_dims() { let mut s = session(); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 6391c4f3db..405bb12a37 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -812,6 +812,47 @@ fn relink_embed_and_unembed_keep_a_distorted_images_corners() { assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); } +/// Place with Replace of a distorted image by an image file keeps its corners, in one undo step: +/// the new file's pixels fill them, the new image is linked to that file, and its transform is the +/// old image's scaled to the new pixel size. Undo brings the old image back between the same +/// corners. +#[test] +fn place_with_replace_keeps_a_distorted_images_corners() { + let dir = Folder::new("distorted-place-replace"); + let (photo, other) = (dir.file("photo.png"), dir.file("other.png")); + write(&photo, &png(20, 10, RED)); + write(&other, &png(60, 20, BLUE)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + // Around the artboard's center, where `centre_colour` looks. + s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap(); + let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).cloned(); + let before = node(&s, id).unwrap().image_corners().unwrap(); + let old_xf = image(&s, id).xf; + let undo_len = |s: &Session| s.doc().unwrap().history.undo.len(); + let undo = undo_len(&s); + + let r = s.execute("file.place", &json!({"path": other, "replace": true})).unwrap(); + let new = NodeId(r["ids"][0].as_u64().unwrap()); + assert_eq!(undo_len(&s), undo + 1); + assert!(node(&s, id).is_none(), "the old image is replaced"); + let n = node(&s, new).unwrap(); + assert!(n.is_distorted_image()); + assert_eq!(n.image_corners().unwrap(), before); + let im = image(&s, new); + assert_eq!((im.width, im.height), (60, 20)); + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str())); + let want = old_xf * vectorcraft_geom::Affine::scale_non_uniform(20.0 / 60.0, 10.0 / 20.0); + assert!(im.xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{:?} against {want:?}", im.xf); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); + + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, new).is_none()); + assert_eq!(node(&s, id).unwrap().image_corners().unwrap(), before); + assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); +} + /// Unembed into a folder keeps a distorted image's corners, in one undo step. #[test] fn unembed_to_a_folder_keeps_a_distorted_images_corners() { diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 4641467aa4..7f46a8edcd 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -6,8 +6,8 @@ use std::collections::BTreeSet; use serde_json::{Value, json}; use vectorcraft_doc::{AnchorRef, LiveCorners, LiveShape, NodeKind}; -use vectorcraft_geom::Affine; use vectorcraft_geom::shapes::CornerKind; +use vectorcraft_geom::{Affine, Point}; use crate::*; @@ -887,6 +887,164 @@ fn a_line_takes_its_length_and_angle() { assert_eq!(steps(&s), n); } +/// Each live shape edit that moves, turns or scales the shape (Rectangle, Ellipse and Polygon +/// Angle, Polygon Radius, Side Length, Make Sides Equal, Line Length and Line Angle) takes a linked +/// opacity mask and a placed gradient along, so they keep their place in the shape's own frame; a +/// new side count or pie leaves them where they are. Scale Strokes & Effects comes from `strokes`, +/// and the bounding box keeps its angle. +#[test] +fn shape_edits_take_a_linked_mask_and_placed_gradient_along() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let add = |s: &mut Session, cmd: &str, p: Value| NodeId(s.execute(cmd, &p).unwrap()["id"].as_u64().unwrap()); + // Each shape gets a placed linear gradient fill and a linked opacity mask off its center. + let dress = |s: &mut Session, id: NodeId, start: [f64; 2], end: [f64; 2], mask: [f64; 2]| { + s.execute("paint.setFill", &json!({"ids": [id.0], "gradient": {"kind": "linear"}})).unwrap(); + s.execute("paint.setGradientGeom", &json!({"ids": [id.0], "start": start, "end": end})).unwrap(); + let m = s.execute("shape.rectangle", &json!({"x": mask[0], "y": mask[1], "width": 20, "height": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [id.0, m]})).unwrap(); + }; + let rect = add(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 100, "height": 60})); + dress(&mut s, rect, [20.0, 30.0], [90.0, 50.0], [15.0, 40.0]); + let ellipse = add(&mut s, "shape.ellipse", json!({"x": 200, "y": 200, "width": 120, "height": 80})); + dress(&mut s, ellipse, [210.0, 240.0], [300.0, 220.0], [270.0, 205.0]); + let polygon = add(&mut s, "shape.polygon", json!({"cx": 200, "cy": 100, "radius": 50, "sides": 6})); + dress(&mut s, polygon, [170.0, 90.0], [230.0, 120.0], [205.0, 70.0]); + let line = add(&mut s, "shape.line", json!({"x1": 100, "y1": 300, "x2": 200, "y2": 300})); + dress(&mut s, line, [100.0, 300.0], [200.0, 300.0], [120.0, 290.0]); + // The shape's own frame: its untransformed unit box, a polygon's unit circle, or a line from 0 to 1 along x. + let frame = |l: &LiveShape| match l { + LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => *xf * Affine::scale_non_uniform(*w, *h), + LiveShape::Polygon { radius, xf, .. } => *xf * Affine::scale(*radius), + LiveShape::Line { a, b } => { + let d = *b - *a; + Affine::new([d.x, d.y, -d.y, d.x, a.x, a.y]) + } + l => panic!("{l:?}"), + }; + // The mask art's center and the gradient's start in the shape's frame, the gradient's value at the + // frame's origin and its two unit points (a linear gradient's isolines, which a shear keeps but + // its end point does not), and the mask art's center in the document. + let local = |s: &Session, id: NodeId| { + let n = s.doc().unwrap().doc.node(id).unwrap(); + let to_doc = frame(n.live_shape().unwrap()); + let to_local = to_doc.inverse(); + let mask = n.extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap().center(); + let vectorcraft_color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("a gradient fill") }; + let geom = g.geom.unwrap(); + let along = geom.end - geom.start; + let t = |x: f64, y: f64| (to_doc * Point::new(x, y) - geom.start).dot(along) / along.hypot2(); + ([to_local * mask, to_local * geom.start, Point::new(t(0.0, 0.0), t(1.0, 0.0)), Point::new(t(0.0, 1.0), 0.0)], mask) + }; + let edits = [ + (rect, json!({"rectangleAngle": 30})), + (ellipse, json!({"ellipseAngle": 50})), + (polygon, json!({"polygonAngle": 20})), + (polygon, json!({"polygonRadius": 80})), + (polygon, json!({"sideLength": 30})), + (polygon, json!({"makeSidesEqual": true})), + (line, json!({"lineLength": 50})), + (line, json!({"lineAngle": 90})), + (line, json!({"lineLength": 140, "lineAngle": 210})), + ]; + // Every edit is checked, and the ones that leave the mask or gradient behind are listed together. + let mut left_behind = Vec::new(); + for (id, edit) in edits { + if edit.get("makeSidesEqual").is_some() { + // Scaled unevenly and turned first, so Make Sides Equal has a shear and an uneven scale to drop. + s.execute("object.scale", &json!({"ids": [polygon.0], "sx": 200, "sy": 100})).unwrap(); + s.execute("object.rotate", &json!({"ids": [polygon.0], "angle": 30})).unwrap(); + s.execute("object.scale", &json!({"ids": [polygon.0], "sx": 100, "sy": 150})).unwrap(); + } + let angle = s.doc().unwrap().doc.node(id).unwrap().bbox_angle; + let (was, _) = local(&s, id); + let mut p = edit.clone(); + p["ids"] = json!([id.0]); + run(&mut s, p); + let now = local(&s, id).0; + if now.iter().zip(&was).any(|(now, then)| now.distance(*then) >= 1e-9) { + left_behind.push(format!("{edit}: {now:?} from {was:?}")); + } + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().bbox_angle, angle, "{edit}: the bounding box keeps its angle"); + } + assert!(left_behind.is_empty(), "moved off the shape:\n{}", left_behind.join("\n")); + // A new side count or pie keeps the shape's place, angle and size: the mask stays where it is. + for (id, edit) in [(polygon, json!({"sides": 8})), (ellipse, json!({"pieStart": 30, "pieEnd": 200}))] { + let (_, was) = local(&s, id); + let mut p = edit.clone(); + p["ids"] = json!([id.0]); + run(&mut s, p); + assert_eq!(local(&s, id).1, was, "{edit}"); + } + // With Scale Strokes & Effects off a new radius keeps the stroke's weight; on, the stroke scales with it. + let weight = |s: &Session| s.doc().unwrap().doc.node(polygon).unwrap().appearance.stroke_width(); + s.execute("stroke.set", &json!({"ids": [polygon.0], "weight": 4})).unwrap(); + run(&mut s, json!({"ids": [polygon.0], "polygonRadius": 160, "strokes": false})); + assert!((weight(&s) - 4.0).abs() < 1e-9, "{}", weight(&s)); + run(&mut s, json!({"ids": [polygon.0], "polygonRadius": 320, "strokes": true})); + assert!((weight(&s) - 8.0).abs() < 1e-9, "the stroke scaled with the shape: {}", weight(&s)); + for bad in [json!({"ids": [polygon.0], "polygonRadius": 50, "strokes": "yes"}), json!({"ids": [polygon.0], "polygonRadius": 50, "patterns": 1})] { + assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}"); + } + // An object named twice moves once, and a rounded rectangle in its mask keeps its corner radius + // with Scale Corners on, as the shape's own corners do. + let star = add(&mut s, "shape.polygon", json!({"cx": 300, "cy": 300, "radius": 40, "sides": 5})); + s.execute("paint.setFill", &json!({"ids": [star.0], "gradient": {"kind": "linear"}})).unwrap(); + s.execute("paint.setGradientGeom", &json!({"ids": [star.0], "start": [280, 300], "end": [320, 310]})).unwrap(); + let m = add(&mut s, "shape.rectangle", json!({"x": 290, "y": 280, "width": 30, "height": 20, "radius": 5})); + s.execute("transparency.makeOpacityMask", &json!({"ids": [star.0, m.0]})).unwrap(); + s.prefs.scale_corners = true; + let (was, _) = local(&s, star); + run(&mut s, json!({"ids": [star.0, star.0], "polygonRadius": 80})); + let (now, _) = local(&s, star); + assert!(now.iter().zip(&was).all(|(now, then)| now.distance(*then) < 1e-9), "moved once: {now:?} from {was:?}"); + let n = s.doc().unwrap().doc.node(star).unwrap(); + let art = &n.extras().mask.as_deref().unwrap().art; + let rect = match &art.kind { + NodeKind::Group { children, .. } => &children[0], + _ => art, + }; + let Some(LiveShape::Rectangle { radii, xf, w, .. }) = rect.live_shape() else { panic!("a live rectangle in the mask") }; + assert!((w * xf.as_coeffs()[0] - 60.0).abs() < 1e-9, "the mask doubled with the shape: {w}, {xf:?}"); + assert!((radii[0] * xf.as_coeffs()[0] - 5.0).abs() < 1e-9, "the corner keeps its radius: {radii:?}, {xf:?}"); +} + +/// A pixel-aligned line that a new angle carries off the pixel grid snaps back to it, and with +/// `patterns` on its pattern moves with the snap as well as with the turn; with `patterns` off the +/// pattern stays where it was. +#[test] +fn a_pixel_aligned_line_takes_its_pattern_through_the_snap() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let line = |s: &mut Session, aligned: bool| { + let id = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0.5, "x2": 100, "y2": 0.5})).unwrap()["id"].as_u64().unwrap()); + let n = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap(); + n.appearance.set_stroke(vectorcraft_color::Paint::Pattern { pattern: "P".into(), xf: Affine::default() }); + n.extras_mut().pixel_aligned = aligned; + id + }; + let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().clone(); + let pattern = |s: &Session, id: NodeId| match node(s, id).appearance.stroke_paint() { + vectorcraft_color::Paint::Pattern { xf, .. } => xf, + p => panic!("a pattern stroke: {p:?}"), + }; + let origin = |s: &Session, id: NodeId| node(s, id).geometric_bounds().unwrap().origin(); + for patterns in [true, false] { + let (aligned, free) = (line(&mut s, true), line(&mut s, false)); + run(&mut s, json!({"ids": [aligned.0, free.0], "lineAngle": 90, "patterns": patterns})); + let snapped = origin(&s, aligned) - origin(&s, free); + assert!(snapped.hypot() > 1e-6, "the aligned line snapped to the grid: {snapped:?}"); + if patterns { + let want = Affine::translate(snapped) * pattern(&s, free); + let got = pattern(&s, aligned); + let off = got.as_coeffs().iter().zip(want.as_coeffs()).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max); + assert!(off < 1e-9, "the pattern moved with the snap: {got:?}, want {want:?}"); + } else { + assert_eq!(pattern(&s, aligned), Affine::default(), "the pattern stays where it was"); + } + } +} + #[test] fn relative_corner_rounding_keeps_fraction_on_resize() { let (mut s, id) = session(); diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index 8caada9e72..fd88ff8e27 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -285,6 +285,89 @@ fn with_characters_selected_an_id_takes_the_opacity() { assert_eq!(node(&s, t), before, "the characters keep their paint"); } +/// While the Type tool has characters selected, a null `id` or `ids` names no object: the paint goes +/// to the selected characters only, as without the key. +#[test] +fn with_characters_selected_a_null_id_paints_the_characters() { + let runs = |key: Option<&str>| { + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Hello"})).unwrap(); + let t = NodeId(r["id"].as_u64().unwrap()); + select(&mut s, &[t]); + select_characters(&mut s, t); + let mut p = json!({"color": "#ff0000"}); + if let Some(key) = key { + p[key] = Value::Null; + } + s.execute("paint.setFill", &p).unwrap(); + match &node(&s, t).kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("not type"), + } + }; + let characters = runs(None); + assert!(characters.len() > 1, "only the selected characters take the paint"); + for key in ["id", "ids"] { + assert_eq!(runs(Some(key)), characters, "{key}: null"); + } +} + +/// An opacity for characters selected while the Type tool is typing is refused before the typing +/// session ends: the session goes on, and no undo step is recorded. +#[test] +fn an_opacity_for_characters_leaves_the_typing_session_running() { + let mut s = session(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 50.0, 250.0), v).unwrap(); + } + s.tool_text("Hello", v).unwrap(); + s.set_tool_option("select", &json!({"start": 0, "end": 2})); + assert!(crate::cmd::typing_in_progress(&s)); + let undo = undo_labels(&s).len(); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert!(crate::cmd::typing_in_progress(&s), "the typing session goes on"); + assert_eq!(undo_labels(&s).len(), undo, "no undo step"); +} + +/// With an opacity alone, the reply counts only the objects that took it: a selected object without +/// that fill item is left out, and one already at that opacity still counts. With a paint, every +/// target counts. +#[test] +fn an_opacity_alone_counts_the_objects_that_took_it() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a]); + s.execute("appearance.removeItem", &json!({"index": 0})).unwrap(); + assert!(node(&s, a).appearance.fill().is_none()); + select(&mut s, &[a, b]); + assert_eq!(s.execute("paint.setFill", &json!({"opacity": 40})).unwrap()["objects"], 1); + assert_eq!(s.execute("paint.setFill", &json!({"opacity": 40})).unwrap()["objects"], 1, "already at 40%"); + assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap()["objects"], 2); +} + +/// With a layer targeted, `paint.proxies` reads the art the command edits: a locked object's fill +/// row does not count, so the proxy answers null when the edit finds no fill to take the opacity. +#[test] +fn a_targeted_layers_proxy_leaves_out_locked_art() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[b]); + s.execute("appearance.removeItem", &json!({"index": 0})).unwrap(); + select(&mut s, &[a]); + s.execute("object.lock", &json!({})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("no target has that fill or stroke to take the opacity"), "{e}"); + s.execute("object.unlockAll", &json!({})).unwrap(); + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the unlocked fill counts"); +} + /// A type object whose characters take the paint is left alone beside a rectangle that takes the /// opacity, with no error; alone, it answers the characters error. #[test] @@ -373,6 +456,80 @@ fn an_object_in_a_symbol_instance_refuses_an_opacity() { assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); } +/// With an object selected in a dynamic symbol instance, a bad `target` is refused whether `id` and +/// `ids` are left out or given as null, and leaves the document alone; a good one with a null `id` +/// still paints the object. +#[test] +fn an_object_in_a_symbol_instance_refuses_a_bad_target() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let inst = s.execute("symbol.new", &json!({"name": "One", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].clone(); + s.execute("symbol.instance.selectPart", &json!({"id": inst, "path": []})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + for p in [ + json!({"color": "#ff0000", "target": "content"}), + json!({"color": "#ff0000", "target": "content", "id": null}), + json!({"color": "#ff0000", "target": "content", "ids": null}), + ] { + let e = s.execute("paint.setFill", &p).unwrap_err(); + assert!(e.to_string().contains("`target` must be"), "{p}: {e}"); + assert_eq!(*s.doc().unwrap().doc, *doc, "{p}"); + } + assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff0000", "target": "object", "id": null})).unwrap()["objects"], 1); + assert_ne!(*s.doc().unwrap().doc, *doc); +} + +/// A bad `target` is refused when `id` or `ids` names an object, and a bad `target` or `aligned` +/// while the Type tool has characters selected; each leaves the document alone. A good `target` +/// with an `id` still paints the object. +#[test] +fn a_bad_target_is_refused_with_an_id_or_selected_characters() { + let mut s = session(); + let r = rect(&mut s, 10.0); + select(&mut s, &[r]); + let doc = s.doc().unwrap().doc.clone(); + for cmd in ["paint.setFill", "paint.setStroke"] { + for p in [ + json!({"color": "#ff0000", "target": "content", "id": r.0}), + json!({"color": "#ff0000", "target": "content", "ids": [r.0]}), + json!({"opacity": 40, "target": "content", "id": r.0}), + json!({"opacity": 40, "target": "content", "ids": [r.0]}), + ] { + let e = s.execute(cmd, &p).unwrap_err(); + assert!(e.to_string().contains("`target` must be"), "{cmd} {p}: {e}"); + assert_eq!(*s.doc().unwrap().doc, *doc, "{cmd} {p}"); + } + } + assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff0000", "target": "object", "id": r.0})).unwrap()["objects"], 1); + assert_ne!(*s.doc().unwrap().doc, *doc); + let t = text(&mut s); + select(&mut s, &[t]); + select_characters(&mut s, t); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"color": "#ff0000", "target": "content"}), json!({"color": "#ff0000", "aligned": "yes"})] { + assert!(s.execute("paint.setFill", &p).is_err(), "{p}"); + assert_eq!(*s.doc().unwrap().doc, *doc, "{p}"); + } +} + +/// The other commands that name their appearance item the same way refuse a bad `target` with an +/// `id` or `ids` too, and leave the document alone; a good one still edits the object. +#[test] +fn a_stroke_edit_refuses_a_bad_target_with_an_id() { + let mut s = session(); + let r = rect(&mut s, 10.0); + select(&mut s, &[r]); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"weight": 9, "target": "content", "id": r.0}), json!({"weight": 9, "target": "content", "ids": [r.0]})] { + let e = s.execute("stroke.set", &p).unwrap_err(); + assert!(e.to_string().contains("`target` must be"), "{p}: {e}"); + assert_eq!(*s.doc().unwrap().doc, *doc, "{p}"); + } + s.execute("stroke.set", &json!({"weight": 9, "target": "object", "id": r.0})).unwrap(); + assert_ne!(*s.doc().unwrap().doc, *doc); +} + /// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows /// it; the object's fill item and the other points stay as they were. #[test] diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 4566ef2be4..cc04612a89 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -7269,6 +7269,27 @@ fn placed_plugin_commands_are_listed_in_their_menu() { assert!(listed(&s, &low(bee)).is_none()); } +/// `plugin.info`'s `manifest` gives each command's context menus in its `menu`, for a command +/// placed in another menu and for one listed only in context menus. +#[test] +fn plugin_info_gives_a_command_s_context_menus() { + let mut s = session(); + let id = "test.engine.place.context"; + let commands = json!([ + {"id": "low", "label": "Low", "menu": {"path": ["Select"], "context": [{"menu": "canvas", "when": "selection"}]}}, + {"id": "tidy", "label": "Tidy", "menu": {"context": [{"menu": "layers", "when": "layerRow"}]}}, + {"id": "keep", "label": "Keep"} + ]); + let manifest = format!(r#"{{"id":"{id}","name":"Ctx","api":2,"version":"1","kind":"filter","commands":{commands}}}"#); + install_wat(&mut s, &tpl::returning(&manifest, r#"{"objects":[]}"#)); + let info = run(&mut s, "plugin.info", json!({"id": id})); + let shown = &info["manifest"]["commands"]; + assert_eq!(shown[0]["menu"], json!({"path": ["Select"], "context": [{"menu": "canvas", "when": "selection"}]}), "{info}"); + assert_eq!(shown[1]["menu"], json!({"context": [{"menu": "layers", "when": "layerRow"}]}), "{info}"); + assert!(shown[2].get("menu").is_none(), "{info}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A command run is journaled like any other, so an action records it with its parameters and /// plays it back. #[test] diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index e2e2d3dae7..28f34e13ab 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -1266,6 +1266,22 @@ fn transform_pattern_tiles_is_the_transforms_default() { assert_eq!(tiles(&s), [0.5, 0.0, 0.0, 0.5, 5.0, 0.0]); } +/// A transform of an object whose pattern is only in its linked opacity mask notes Transform +/// Patterns in the journal too, so a replay moves the mask's tiles alike. +#[test] +fn transform_patterns_is_journaled_for_a_pattern_in_a_linked_mask() { + let mut s = new_doc(); + // The mask art is the patterned square above the polygon. + let id = NodeId(s.execute("shape.polygon", &json!({"cx": 125, "cy": 125, "radius": 40, "sides": 6})).unwrap()["id"].as_u64().unwrap()); + let art = patterned_square(&mut s); + s.execute("transparency.makeOpacityMask", &json!({"ids": [id.0, art.0]})).unwrap(); + set_pref(&mut s, "transformPatternTiles", json!(true)); + s.execute("object.move", &json!({"ids": [id.0], "dx": 10, "dy": 0})).unwrap(); + assert_eq!(s.journal.last().unwrap().1["patterns"], json!(true), "object.move"); + s.execute("object.setLiveShape", &json!({"ids": [id.0], "polygonAngle": 20})).unwrap(); + assert_eq!(s.journal.last().unwrap().1["patterns"], json!(true), "object.setLiveShape"); +} + /// A 50 pt square at (100, 100) with a 1 pt stroke, filled with a 20 pt pattern, selected. fn patterned_square(s: &mut Session) -> NodeId { let tile = square(s, 0.0, 0.0); diff --git a/crates/engine/src/tests/previewbounds.rs b/crates/engine/src/tests/previewbounds.rs index 53f344ceb8..a543adf276 100644 --- a/crates/engine/src/tests/previewbounds.rs +++ b/crates/engine/src/tests/previewbounds.rs @@ -975,6 +975,57 @@ fn set_bounds_gives_a_closed_path_with_beveled_or_mitered_corners_the_size_out_o assert!(wrong.is_empty(), "{wrong:?}"); } +#[test] +fn set_bounds_gives_a_group_whose_own_stroke_miters_a_slanted_corner_the_size_out_of_proportion() { + // The group's own beveled or mitered stroke paints along the unstroked triangle in it, so its + // margins at the tip follow the slanted segments' directions too. + let mut wrong = vec![]; + for (join, limit) in [("bevel", 10.0), ("miter", 2.0), ("miter", 10.0)] { + let mut s = session(); + let anchors = json!([{"x": 100, "y": 150}, {"x": 110, "y": 100}, {"x": 120, "y": 150}]); + let path = NodeId(run(&mut s, "path.create", json!({"anchors": anchors, "closed": true}))["id"].as_u64().unwrap()); + let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({"ids": [group.0]})); + run(&mut s, "stroke.set", json!({"weight": 2, "join": join, "miterLimit": limit})); + run(&mut s, "select.set", json!({"ids": [path.0]})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let doc = &s.doc().unwrap().doc; + let painted = |id: NodeId| doc.node(id).unwrap().appearance.painted_strokes().count(); + assert_eq!((painted(path), painted(group)), (0, 1), "only the group has a stroke"); + preview(&mut s, true); + run(&mut s, "select.set", json!({"ids": [group.0]})); + run(&mut s, "object.setBounds", json!({"width": 60, "height": 20, "reference": 0, "strokes": false})); + let v = s.transform_bounds(&[group]).unwrap(); + if (v.width() - 60.0).abs() > 1e-6 || (v.height() - 20.0).abs() > 1e-6 { + wrong.push(format!("{join} {limit}: {v:?}")); + } + } + assert!(wrong.is_empty(), "{wrong:?}"); +} + +#[test] +fn set_bounds_gives_a_stroked_group_with_a_hidden_subgroup_the_requested_width() { + // The hidden subgroup supplies the rightmost geometry, but the outer group's stroke paints + // only along the visible rectangle. Square corners keep the resize in the span solver. + let mut s = session(); + let shown = rect(&mut s, 100.0, 50.0, 0.0); + rect(&mut s, 200.0, 50.0, 0.0); + let hidden = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [shown.0, hidden.0]})); + let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({"ids": [group.0]})); + run(&mut s, "paint.setStroke", json!({"ids": [group.0], "item": 0, "color": "#000000"})); + run(&mut s, "stroke.set", json!({"weight": 10, "join": "miter"})); + run(&mut s, "object.hide", json!({"ids": [hidden.0]})); + preview(&mut s, true); + run(&mut s, "select.set", json!({"ids": [group.0]})); + let before = s.transform_bounds(&[group]).unwrap(); + assert!(close(before, Rect::new(95.0, 95.0, 250.0, 155.0)), "{before:?}"); + run(&mut s, "object.setBounds", json!({"width": 300, "reference": 0, "strokes": false})); + let after = s.transform_bounds(&[group]).unwrap(); + assert!((after.width() - 300.0).abs() < 1e-6, "{after:?}"); +} + #[test] fn set_bounds_gives_a_symbol_instance_of_a_diagonal_butt_line_the_size_out_of_proportion() { let mut s = session(); @@ -1034,19 +1085,21 @@ fn set_bounds_measures_the_members_of_groups_one_by_one() { wrong.push(format!("nested {nested}, plain {plain}, strokes {strokes}: {v:?}")); } } - // The group with a 1 pt stroke of its own, which reaches 5 pt at its miter limit of 10, around - // each member: the visual box runs from (-7, 90) to (110, 160). Set to 224 wide from its left - // edge, it is 224 wide and its left edge stays at -7, with strokes kept or scaling. + // The group with a 20 pt miter-joined stroke of its own, which paints 10 pt past each member's + // corners, not the 100 pt its miter limit of 10 could reach: the visual box runs from (-10, 90) + // to (110, 160). Set to 224 wide from its left edge, it is 224 wide and its left edge stays at + // -10, with strokes kept or scaling. for strokes in [false, true] { let (mut s, _) = thin_and_thick(); let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); run(&mut s, "appearance.addStroke", json!({"ids": [group.0]})); + run(&mut s, "stroke.set", json!({"weight": 20})); let ids = [group, rect(&mut s, 100.0, 10.0, 0.0)]; run(&mut s, "select.set", json!({"ids": [ids[0].0, ids[1].0]})); - assert!(close(s.transform_bounds(&ids).unwrap(), Rect::new(-7.0, 90.0, 110.0, 160.0)), "{:?}", s.transform_bounds(&ids)); + assert!(close(s.transform_bounds(&ids).unwrap(), Rect::new(-10.0, 90.0, 110.0, 160.0)), "{:?}", s.transform_bounds(&ids)); run(&mut s, "object.setBounds", json!({"width": 224, "reference": 0, "strokes": strokes})); let v = s.transform_bounds(&ids).unwrap(); - if !close(v, Rect::new(-7.0, 90.0, 217.0, 160.0)) { + if !close(v, Rect::new(-10.0, 90.0, 214.0, 160.0)) { wrong.push(format!("the group with a stroke, strokes {strokes}: {v:?}")); } } @@ -1258,6 +1311,13 @@ fn a_handle_drag_keeps_the_opposite_edge_of_the_offset_shape() { } } +/// Holds the fonts, the hyphenation exceptions and the plug-ins steady on other threads: the memo +/// also answers for them ([`vectorcraft_doc::hit::live_inputs`]), and a test that counts what it +/// measures or checks must not count a refresh that another test's change caused. +fn steady_live_inputs() -> (vectorcraft_text::test_fonts::SteadyFonts, vectorcraft_plugins::steady::SteadyPlugins) { + (vectorcraft_text::test_fonts::steady_fonts(vectorcraft_text::FontDb::global()), vectorcraft_plugins::steady::steady_plugins()) +} + #[test] fn a_hover_checks_the_memo_as_often_however_many_objects_are_selected() { let checks = |objects: u32| { @@ -1273,6 +1333,7 @@ fn a_hover_checks_the_memo_as_often_however_many_objects_are_selected() { s.pointer(&PointerEvent::new(PointerKind::Move, 350.0, 350.0), v).unwrap(); s.cursor(Point::new(350.0, 350.0), Mods::default(), v) }; + let _steady = steady_live_inputs(); hover(&mut s); let before = s.preview_memo.checks(); hover(&mut s); @@ -1297,6 +1358,7 @@ fn hovering_over_an_unchanged_document_measures_nothing_again() { s.cursor(Point::new(x, 150.0), Mods::default(), v) }; let xs = [210.0, 150.0, 151.0, 180.0, 250.0]; + let _steady = steady_live_inputs(); for x in xs { hover(&mut s, x); } diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs new file mode 100644 index 0000000000..1432b8671b --- /dev/null +++ b/crates/engine/src/tests/script_actions.rs @@ -0,0 +1,396 @@ +//! `app.doScript`: a script plays an action of `script.run`'s `actions`. + +use serde_json::{Value, json}; + +use crate::*; + +fn run_with(s: &mut Session, source: &str, actions: &Value) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions})) +} + +fn log_with(s: &mut Session, source: &str, actions: &Value) -> Vec { + let r = run_with(s, source, actions).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The error message a `try` around `call` logs, or `"ok"`. +fn caught(s: &mut Session, call: &str, actions: &Value) -> String { + let source = format!("try {{ {call}; vc.log('ok'); }} catch (e) {{ vc.log(e.name + ': ' + e.message); }}"); + log_with(s, &source, actions).first().and_then(Value::as_str).unwrap_or_default().to_string() +} + +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn objects(s: &Session) -> usize { + s.active().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +fn undo_labels(s: &Session) -> Vec { + s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect() +} + +fn rect(x: i64) -> Value { + json!({"command": "shape.rectangle", "params": {"x": x, "y": 10, "width": 20, "height": 20}}) +} + +/// One set, `Set`, with the actions given as (name, steps). +fn set(actions: &[(&str, Vec)]) -> Value { + Value::Array(actions.iter().map(|(name, steps)| json!({"set": "Set", "name": name, "steps": steps})).collect()) +} + +#[test] +fn do_script_plays_every_step_as_one_undo_step_with_the_script() { + let mut s = doc(); + let before = undo_labels(&s); + let actions = set(&[("Two", vec![rect(0), rect(50)])]); + let out = log_with(&mut s, "vc.run('shape.rectangle', {x: 100, y: 10, width: 5, height: 5}); vc.log(app.doScript('Two', 'Set'));", &actions); + assert_eq!(out, vec![Value::Null], "doScript returns undefined"); + assert_eq!(objects(&s), 3); + let after = undo_labels(&s); + assert_eq!(after.len(), before.len() + 1, "{after:?}"); + assert_eq!(after.last().map(String::as_str), Some(script::STEP_LABEL)); + // The steps of a recorded `command.batch` run one by one, each counted as a host call. + let batch = set(&[("Batch", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), rect(10), rect(20)]}})])]); + let r = run_with(&mut s, "app.doScript('Batch', 'Set', false);", &batch).unwrap(); + assert_eq!(objects(&s), 6); + let r0 = run_with(&mut s, "1;", &batch).unwrap(); + assert!(r["hostCalls"].as_u64().unwrap() >= r0["hostCalls"].as_u64().unwrap() + 4, "{r}"); +} + +#[test] +fn a_later_throw_puts_back_what_the_action_did() { + let mut s = doc(); + let before = (objects(&s), undo_labels(&s)); + let actions = set(&[("Two", vec![rect(0), rect(50)])]); + let e = run_with(&mut s, "app.doScript('Two', 'Set'); throw new Error('late');", &actions).unwrap_err().to_string(); + assert!(e.contains("late"), "{e}"); + assert_eq!((objects(&s), undo_labels(&s)), before); +} + +#[test] +fn a_failed_step_is_put_back_and_the_steps_before_it_stay() { + let mut s = doc(); + let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}}); + let actions = set(&[("Bad", vec![rect(0), bad, rect(50)])]); + let m = caught(&mut s, "app.doScript('Bad', 'Set')", &actions); + assert!(m.starts_with("Error: action step 2 of “Bad” (`object.move`) failed:"), "{m}"); + assert_eq!(objects(&s), 1, "the first step stays done and the third never runs"); +} + +#[test] +fn names_are_matched_exactly_and_must_be_one_action() { + let mut s = doc(); + let actions = json!([ + {"set": "Set", "name": "One", "steps": [rect(0)]}, + {"set": "Set", "name": "Twice", "steps": [rect(0)]}, + {"set": "Set", "name": "Twice", "steps": [rect(0)]}, + {"set": "Set", "name": "Empty", "steps": []}, + ]); + assert_eq!(caught(&mut s, "app.doScript('one', 'Set')", &actions), "Error: the set “Set” has no action “one”"); + assert_eq!(caught(&mut s, "app.doScript('One', 'set')", &actions), "Error: there is no action set “set”"); + assert_eq!(caught(&mut s, "app.doScript('Twice', 'Set')", &actions), "Error: the set “Set” has more than one action “Twice”"); + assert_eq!(caught(&mut s, "app.doScript('Empty', 'Set')", &actions), "Error: the action “Empty” has no included steps"); + assert_eq!(caught(&mut s, "app.doScript('One', 'Set')", &json!([])), "Error: there is no action set “Set”"); + assert_eq!(objects(&s), 0); + assert_eq!(caught(&mut s, "app.doScript('One', 'Set', true)", &actions), "ok"); + assert_eq!(objects(&s), 1); + assert_eq!(caught(&mut s, "app.loadAction(1)", &actions), "Error: Application.loadAction is not available yet"); + assert_eq!(caught(&mut s, "app.unloadAction('Set', '')", &actions), "Error: Application.unloadAction is not available yet"); +} + +#[test] +fn bad_arguments_throw_and_change_nothing() { + let mut s = doc(); + let actions = set(&[("One", vec![rect(0)])]); + for (call, want) in [ + ("app.doScript()", "TypeError"), + ("app.doScript(1, 'Set')", "TypeError"), + ("app.doScript('One', {})", "TypeError"), + ("app.doScript('One', 'Set', 'yes')", "TypeError"), + ("app.doScript('One', 'Set', 1)", "TypeError"), + ("app.doScript('One', 'Set', false, 4)", "TypeError"), + ("app.doScript('', 'Set')", "Error"), + ("app.doScript(new Array(2000).join('x'), 'Set')", "RangeError"), + ] { + let m = caught(&mut s, call, &actions); + assert!(m.starts_with(&format!("{want}:")), "{call}: {m}"); + } + assert_eq!(objects(&s), 0); +} + +#[test] +fn steps_a_script_may_not_run_stop_the_action_before_any_step() { + let mut s = doc(); + s.prefs.show_external_script_warning = true; + let steps = [ + (json!({"command": "script.run", "params": {"source": "1"}}), "runs `script.run`, which a script cannot run"), + (json!({"command": "prefs.set", "params": {"key": "showExternalScriptWarning", "value": false}}), "runs `prefs.set`"), + (json!({"command": "ui.action.play", "params": {"set": "Set", "action": "Loop"}}), "runs `ui.action.play`"), + (json!({"command": "ui.runScript", "params": {"source": "1"}}), "runs `ui.runScript`"), + (json!({"command": "view.zoomIn"}), "runs `view.zoomIn`"), + (json!({"command": "action.stop", "params": {"message": "wait"}}), "is a stop, which a script cannot wait at"), + ]; + for (bad, want) in steps { + let actions = set(&[("Loop", vec![rect(0), bad.clone()])]); + let m = caught(&mut s, "app.doScript('Loop', 'Set')", &actions); + assert!(m.starts_with("Error: step 2 of “Loop” ") && m.contains(want), "{bad}: {m}"); + assert_eq!(objects(&s), 0, "{bad}: no step ran"); + } + assert!(s.prefs.show_external_script_warning); + // A refused command inside a recorded batch is refused too. + let batch = set(&[("B", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), {"command": "script.run", "params": {}}]}})])]); + let m = caught(&mut s, "app.doScript('B', 'Set')", &batch); + assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}"); + assert_eq!(objects(&s), 0); + // So is one among the commands a Batch step plays on each file, before the steps ahead of it run. + let files = json!({"command": "action.batch", "params": {"commands": [{"command": "select.all"}, {"command": "prefs.set", "params": {}}]}}); + let batch = set(&[("F", vec![rect(0), files])]); + let m = caught(&mut s, "app.doScript('F', 'Set')", &batch); + assert!(m.starts_with("Error: step 2.2 of “F” runs `prefs.set`, which a script cannot run"), "{m}"); + assert_eq!(objects(&s), 0); +} + +#[test] +fn an_action_step_keeps_the_scripts_file_gate() { + let mut s = doc(); + let path = std::env::temp_dir().join(format!("vc-do-script-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let export = json!({"command": "document.export", "params": {"path": path.to_string_lossy(), "format": "svg"}}); + let actions = set(&[("Export", vec![export])]); + let m = caught(&mut s, "app.doScript('Export', 'Set')", &actions); + assert!(m.contains("Script file access denied"), "{m}"); + assert!(!path.exists()); +} + +#[test] +fn a_long_action_is_held_to_the_host_call_limit() { + let mut s = doc(); + // Each step counts as a host call of its own, and its result as another, as for `vc.run`, so the + // steps of one call cannot pass the limit. + let calls = |s: &mut Session, steps: usize| { + let actions = set(&[("One", vec![json!({"command": "select.none"}); steps])]); + run_with(s, "app.doScript('One', 'Set');", &actions).unwrap()["hostCalls"].as_u64().unwrap() + }; + let (one, many) = (calls(&mut s, 1), calls(&mut s, 1001)); + assert!(many >= one + 2000, "{one} {many}"); +} + +#[test] +fn bad_action_lists_are_refused_before_the_script_runs() { + let mut s = doc(); + let step = || json!({"command": "select.none"}); + let cases = [ + (json!({}), "`actions` must be a list"), + (json!([1]), "`actions[0]` must be an object"), + (json!([{"set": "S", "name": 1, "steps": []}]), "`actions[0]`.name must be a string"), + (json!([{"set": "S", "name": "A"}]), "`actions[0]`.steps must be a list"), + (json!([{"set": "S", "name": "A", "steps": [], "key": 1}]), "unknown key `key`"), + (json!([{"set": "S", "name": "A", "steps": [{"command": ""}]}]), "command must be a command id"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "params": []}]}]), "params must be an object"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "step": 0}]}]), "step must be a whole number"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {}}]}]), "params.commands must be a list"), + ( + json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {"commands": [{"command": "command.batch", "params": {"commands": []}}]}}]}]), + "a command.batch inside a command.batch", + ), + (json!([{"set": "S", "name": "x".repeat(2000), "steps": []}]), "longer than 1024 bytes"), + (Value::Array(vec![json!({"set": "S", "name": "A", "steps": []}); script::actions::MAX_ACTIONS + 1]), "more than 4096 actions"), + (json!([{"set": "S", "name": "A", "steps": vec![step(); script::actions::MAX_ACTION_STEPS + 1]}]), "more than 10000 steps"), + ]; + for (actions, want) in cases { + let e = run_with(&mut s, "vc.run('shape.rectangle', {x: 0, y: 0, width: 1, height: 1});", &actions).unwrap_err().to_string(); + assert!(e.contains(want), "{want}: {e}"); + } + let many: Vec = (0..11).map(|i| json!({"set": "S", "name": format!("A{i}"), "steps": vec![step(); 10_000]})).collect(); + let e = run_with(&mut s, "1;", &Value::Array(many)).unwrap_err().to_string(); + assert!(e.contains("more than 100000 steps in all"), "{e}"); + assert_eq!(objects(&s), 0, "no run started"); +} + +#[test] +fn a_kept_engine_plays_the_actions_of_the_run_that_calls_it() { + let mut s = doc(); + let first = set(&[("One", vec![rect(0)])]); + log_with(&mut s, "#targetengine keep\nvar play = function () { app.doScript('One', 'Set'); };", &first); + assert_eq!(objects(&s), 0); + // The next run has no actions: the function kept from the first run finds none. + let call = "#targetengine keep\ntry { play(); vc.log('ok'); } catch (e) { vc.log(e.message); }"; + assert_eq!(log_with(&mut s, call, &json!([])), vec![json!("there is no action set “Set”")]); + let two = set(&[("One", vec![rect(0), rect(30)])]); + assert_eq!(log_with(&mut s, call, &two), vec![json!("ok")]); + assert_eq!(objects(&s), 2); +} + +/// Makes artboard `index` of the active document the view's active one, as the app does before each +/// command. +fn make_active(s: &mut Session, index: usize) { + let id = s.active().unwrap().doc.artboards[index].id; + s.doc_mut().unwrap().active_artboard = Some(id); +} + +/// A step that acts on the active artboard, Align to Artboard in a recorded batch and Fit to Selected +/// Art, acts on the active artboard's index as the run started; after the script deletes that +/// artboard, the last one. A step that names its artboard keeps it. +#[test] +fn steps_act_on_the_artboard_active_as_they_run() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let was = boards(&s); + make_active(&mut s, 2); + let align = |to: Value| json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard", "artboard": to}}); + let mut first = align(json!(0)); + first["params"].as_object_mut().unwrap().remove("artboard"); + let actions = set(&[ + ("Align", vec![json!({"command": "command.batch", "params": {"commands": [first]}})]), + ("Align 1", vec![align(json!(0))]), + ("Fit", vec![json!({"command": "artboard.fitToSelection"})]), + ]); + let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; + log_with(&mut s, "vc.run('artboard.delete', {index: 2}); app.doScript('Align', 'Set'); app.doScript('Fit', 'Set');", &actions); + let art = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + assert_eq!(art.x0, was[1].x0, "aligned to the last artboard, where the deleted active one was"); + assert_eq!(boards(&s), [was[0], art], "Fit to Selected Art resizes that artboard and leaves the other"); + log_with(&mut s, "app.doScript('Align 1', 'Set');", &actions); + assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it"); +} + +/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none, +/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it. +#[test] +fn a_batch_steps_artboard_holds_for_its_steps_that_name_none() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + make_active(&mut s, 1); + let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}}); + let mut own = align.clone(); + own["params"]["artboard"] = json!(1); + let batch = |artboard: u64, step: &Value| json!({"command": "command.batch", "params": {"artboard": artboard, "commands": [step]}}); + let actions = set(&[("First", vec![batch(0, &align)]), ("Past", vec![batch(9, &align)]), ("Own", vec![batch(0, &own)])]); + let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; + log_with(&mut s, "app.doScript('First', 'Set');", &actions); + assert_eq!(left(&s), was[0].x0, "the batch's artboard 0"); + log_with(&mut s, "app.doScript('Past', 'Set');", &actions); + assert_eq!(left(&s), was[2].x0, "past the last artboard, the last one"); + log_with(&mut s, "app.doScript('Own', 'Set');", &actions); + assert_eq!(left(&s), was[1].x0, "a step that names artboard 1 keeps it"); +} + +/// The active artboard a step gets is the index it had as the run started: after a step deletes an +/// artboard before it, the artboard now at that index, as the view shows it. +#[test] +fn steps_keep_the_active_artboards_index() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + let uid = s.active().unwrap().uid; + let start = script::actions::Start { active: &[(uid, 1)], picks: None, batch: None }; + let add = |s: &Session| script::actions::on_active_artboard(s, &start, "object.align", &json!({})); + assert_eq!(add(&s), json!({"artboard": 1})); + s.execute("artboard.delete", &json!({"index": 0})).unwrap(); + assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1"); + s.execute("artboard.delete", &json!({"index": 1})).unwrap(); + assert_eq!(add(&s), json!({"artboard": 0}), "past the last artboard, the last one"); +} + +/// A Fit to Artwork Bounds step that names no artboard fits the active one; one that names its +/// `indices` fits those. +#[test] +fn a_fit_to_artwork_bounds_step_fits_the_active_artboard_or_its_own() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + make_active(&mut s, 1); + let actions = set(&[ + ("Fit", vec![json!({"command": "artboard.fitToArt"})]), + ("Fit first", vec![json!({"command": "artboard.fitToArt", "params": {"indices": [0]}})]), + ]); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); + assert_eq!(boards(&s), [was[0], art[1]], "the active artboard fits its art"); + log_with(&mut s, "app.doScript('Fit first', 'Set');", &actions); + assert_eq!(boards(&s), art, "the step's own indices"); +} + +/// While the Artboard tool has several artboards selected, a paste step gets no artboard, so that it +/// pastes on those, and a Fit to Artwork Bounds step gets those as its `indices`; the other steps +/// still get the active one. +#[test] +fn paste_and_fit_steps_keep_the_artboard_tools_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + make_active(&mut s, 1); + let start = script::actions::Start { active: &[], picks: None, batch: None }; + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({})); + assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1})); + assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] { + assert_eq!(add(&s, id), json!({}), "{id}"); + } + assert_eq!(add(&s, "artboard.fitToArt"), json!({"indices": [0, 2]})); + assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1})); + assert_eq!(add(&s, "object.align"), json!({"artboard": 1})); + assert_eq!(add(&s, "shape.rectangle"), json!({})); +} + +/// The Artboard tool's selection as `script.run` starts holds for the steps `app.doScript` plays, +/// though the run gives the tool fresh state: a paste step pastes on those artboards and a Fit to +/// Artwork Bounds step fits them. +#[test] +fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { + // Three artboards with a rectangle on each, artboard 1 active and the Artboard tool holding 0 and 2. + let setup = || { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + s.execute("edit.copy", &json!({})).unwrap(); + make_active(&mut s, 1); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + (s, was, art) + }; + let actions = set(&[("Paste", vec![json!({"command": "edit.pasteInPlace"})]), ("Fit", vec![json!({"command": "artboard.fitToArt"})])]); + let (mut s, ..) = setup(); + let before = objects(&s); + log_with(&mut s, "app.doScript('Paste', 'Set');", &actions); + assert_eq!(objects(&s), before + 2, "one copy on each selected artboard"); + let (mut s, was, art) = setup(); + log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art"); + // A kept artboard past the last one is left out; with fewer than two left, the active one applies. + let (mut s, ..) = setup(); + s.reset_tool(); + let uid = s.active().unwrap().uid; + let kept = (uid, vec![0, 2]); + let start = script::actions::Start { active: &[(uid, 1)], picks: Some(&kept), batch: None }; + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({})); + assert_eq!(add(&s, "edit.pasteInBack"), json!({"artboards": [0, 2]})); + assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1})); + s.execute("artboard.delete", &json!({"index": 2})).unwrap(); + assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 295ed12f90..94886530c1 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -193,6 +193,140 @@ fn ruler_origin_round_trips_without_moving_art() { assert!(failure(&mut s, "app.activeDocument.rulerOrigin = [1e12, 0];").contains("outside the canvas")); } +/// A window on the document of [`doc`] that shows 300 × 200 pt around (200, 150) at 200%. +fn window() -> WindowView { + WindowView { + center: vectorcraft_geom::Point::new(200.0, 150.0), + zoom: 2.0, + zoom_baseline: 1.0, + rotation: 0.0, + size: [600.0, 400.0], + screen_mode: 0, + } +} + +/// Shows the active document in the window `v`. +fn show(s: &mut Session, v: WindowView) { + let uid = s.active().unwrap().uid; + s.window_views = vec![((uid, 1), v)]; +} + +/// The window of the active document. +fn shown(s: &Session) -> Option { + let uid = s.active().unwrap().uid; + s.window_views.iter().find(|((u, _), _)| *u == uid).map(|(_, v)| *v) +} + +#[test] +fn the_view_shows_the_part_of_the_document_its_window_shows() { + let (mut s, ..) = doc(); + let none = "var v = app.activeDocument.views; vc.log(v.length); vc.log(v[0] === undefined); vc.log(0 in v); vc.log('a' in v);"; + assert_eq!(log(&mut s, none), vec![json!(0), json!(true), json!(false), json!(false)], "a document without a window has no view"); + show(&mut s, window()); + // A rectangle drawn over the visible part of the document has the view's bounds. + let r = window().visible(); + rect(&mut s, r.x0, r.y0, r.width(), r.height()); + let out = log( + &mut s, + "var d = app.activeDocument; var v = d.views[0]; vc.log(d.views.length); vc.log(v.typename);\ + vc.log(v.parent === d); vc.log(v.bounds); var r = d.pageItems[0];\ + vc.log(r.geometricBounds); vc.log(v.centerPoint); vc.log(r.position[0] + r.width / 2);\ + vc.log(r.position[1] - r.height / 2);", + ); + assert_eq!(out[..3], [json!(1), json!("View"), json!(true)]); + assert_eq!(out[3], out[4], "the view's bounds are the visible area"); + assert_eq!(out[5], json!([out[6], out[7]]), "the centre is the middle of the visible area"); + // Turning the view shows more of the document around the same centre. + show(&mut s, WindowView { rotation: 30.0, ..window() }); + let turned = log(&mut s, "vc.log(app.activeDocument.views[0].bounds);"); + let width = |b: &Value| b[2].as_f64().unwrap() - b[0].as_f64().unwrap(); + assert!(width(&turned[0]) > width(&out[3])); + let names = log(&mut s, "var d = app.activeDocument; vc.log(String(d.views) + String(d.views[0]));"); + assert_eq!(names, vec![json!("[Views][View]")]); + assert_eq!(log(&mut s, "var v = app.activeDocument.views; vc.log(0 in v); vc.log(1 in v);"), vec![json!(true), json!(false)]); + // A named engine keeps the views from an earlier run, but they are stale. + run(&mut s, "#targetengine keep\nvar vs = app.activeDocument.views, v = vs[0];").unwrap(); + for member in ["String(vs)", "String(v)"] { + let e = failure(&mut s, &format!("#targetengine keep\n{member};")); + assert!(e.contains("Stale document"), "{member}: {e}"); + } +} + +#[test] +fn setting_the_zoom_changes_the_view_without_an_undo_step() { + let (mut s, ..) = doc(); + show(&mut s, window()); + // Another document's window. + s.window_views.push(((u64::MAX, 1), window())); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var v = app.activeDocument.views[0]; var b = v.bounds; v.zoom = 4; vc.log(v.zoom);\ + vc.log(v.bounds[2] - v.bounds[0] < b[2] - b[0]); v.centerPoint = [100, 100]; vc.log(v.centerPoint);\ + v.screenMode = ScreenMode.FULLSCREEN; vc.log(v.screenMode);", + ); + assert_eq!(out, vec![json!(4), json!(true), json!([100, 100]), json!("ScreenMode.FULLSCREEN")]); + let now = shown(&s).unwrap(); + assert!(now.zoom > window().zoom); + assert!(now.center != window().center && now.screen_mode != window().screen_mode); + assert_eq!(s.window_views[1].1.screen_mode, now.screen_mode, "the screen mode is the same in every window"); + assert_eq!(s.window_views[1].1.zoom, window().zoom, "the zoom is each window's own"); + assert_eq!(undo_steps(&s), steps, "a view change is not undoable"); + // A bad value throws and leaves the view as it is. + let bad = [ + ("v.zoom = 0;", "RangeError"), + ("v.zoom = 1000;", "RangeError"), + ("v.zoom = '2';", "TypeError"), + ("v.centerPoint = [1];", "TypeError"), + ("v.centerPoint = [1e12, 0];", "RangeError"), + ("v.screenMode = 'FULLSCREEN';", "TypeError"), + ]; + for (bad, name) in bad { + let out = log(&mut s, &format!("var v = app.activeDocument.views[0]; try {{ {bad} vc.log('set'); }} catch (e) {{ vc.log(e.name); }}")); + assert_eq!(out, vec![json!(name)], "{bad}"); + assert_eq!(shown(&s), Some(now), "{bad}"); + } + // A run that fails after changing the view keeps the change. + failure(&mut s, "app.activeDocument.views[0].zoom = 1; throw new Error('stop');"); + assert_eq!(shown(&s).map(|v| v.zoom), Some(1.0)); +} + +#[test] +fn view_centers_stay_inside_the_canvas_after_coordinate_conversion() { + let (mut s, ..) = doc(); + let origin = vectorcraft_geom::Point::new(3.0e6, 3.0e6); + s.edit("Move Artboard", |d, _| { + d.artboards[0].rect = vectorcraft_geom::Rect::from_origin_size(origin, (400.0, 300.0)); + Ok(()) + }) + .unwrap(); + show(&mut s, window()); + let steps = undo_steps(&s); + for coordinates in ["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"] { + let script_point = |p: vectorcraft_geom::Point| { + let y = if coordinates == "ARTBOARDCOORDINATESYSTEM" { p.y - origin.y } else { origin.y + 300.0 - p.y }; + [p.x - origin.x, y] + }; + for bound in [-MAX_COORD, MAX_COORD] { + for horizontal in [false, true] { + let point = |n| if horizontal { vectorcraft_geom::Point::new(n, 0.0) } else { vectorcraft_geom::Point::new(0.0, n) }; + let before = shown(&s); + let [x, y] = script_point(point(bound + bound.signum())); + let source = format!( + "app.coordinateSystem = CoordinateSystem.{coordinates}; var v = app.activeDocument.views[0]; \ + try {{ v.centerPoint = [{x}, {y}]; vc.log('set'); }} catch (e) {{ vc.log(e.name); }}" + ); + assert_eq!(log(&mut s, &source), vec![json!("RangeError")], "{source}"); + assert_eq!(shown(&s), before, "a rejected center leaves the view unchanged"); + let [x, y] = script_point(point(bound)); + log(&mut s, &format!("app.coordinateSystem = CoordinateSystem.{coordinates}; app.activeDocument.views[0].centerPoint = [{x}, {y}];")); + assert_eq!(shown(&s).unwrap().center, point(bound), "the canvas boundary is allowed"); + } + } + } + assert_eq!(undo_steps(&s), steps); +} + #[test] fn page_item_properties_join_one_undo_step() { let (mut s, a, _) = doc(); @@ -260,6 +394,71 @@ fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { assert_eq!(kept(&s), None); } +/// A blend mode a graph mark or axis label already has still replaces the blend mode another object +/// of its series or kind left on the graph, and is refused in a hidden or locked layer. +#[test] +fn a_blend_mode_a_graph_mark_or_label_already_has_replaces_the_one_the_graph_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let r = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let spec = |s: &Session| s.active().unwrap().doc.node(id).unwrap().extras().graph.as_deref().unwrap().clone(); + let kept_mark = |s: &Session| spec(s).series_paints.first().and_then(|p| p.blend); + let kept_label = |s: &Session| spec(s).label_styles.values_rows.as_ref().and_then(|r| r.paint.blend); + let graph = s.active().unwrap().doc.node(id).unwrap().clone(); + let group = graph.children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + let marks: Vec = group.children().unwrap().iter().map(|m| m.id).collect(); + let axes = graph.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Axes")).unwrap().clone(); + // The value axis numbers come first among the Axes group's labels. + let labels: Vec = axes.children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Text(_))).map(|c| c.id).collect(); + s.execute("object.setProps", &json!({"id": marks[0].0, "blend": "Multiply"})).unwrap(); + s.execute("object.setProps", &json!({"id": labels[0].0, "blend": "Screen"})).unwrap(); + let both = (Some(vectorcraft_color::BlendMode::Multiply), Some(vectorcraft_color::BlendMode::Screen)); + assert_eq!((kept_mark(&s), kept_label(&s)), both); + s.execute("object.setProps", &json!({"id": marks[1].0, "name": "mark"})).unwrap(); + s.execute("object.setProps", &json!({"id": labels[1].0, "name": "label"})).unwrap(); + let layer = s.active().unwrap().doc.layers[0].id; + for (on, off) in [ + (json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})), + (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), + ] { + s.execute("object.setProps", &on).unwrap(); + for name in ["mark", "label"] { + let steps = undo_steps(&s); + let e = failure(&mut s, &format!("var m = app.activeDocument.pageItems.getByName('{name}'); m.blendingMode = m.blendingMode;")); + assert!(e.contains("Cannot edit"), "{on} {name}: {e}"); + assert_eq!((kept_mark(&s), kept_label(&s)), both, "{on} {name}"); + assert_eq!(undo_steps(&s), steps, "{on} {name}"); + } + s.execute("object.setProps", &off).unwrap(); + } + log( + &mut s, + "var p = app.activeDocument.pageItems; p.getByName('mark').blendingMode = BlendModes.NORMAL; p.getByName('label').blendingMode = BlendModes.NORMAL;", + ); + assert_eq!((kept_mark(&s), kept_label(&s)), (None, None)); +} + +/// `app.redraw()` returns `undefined` and leaves the art and the undo history as they were. +#[test] +fn redraw_returns_and_changes_nothing() { + let (mut s, _, top) = doc(); + let (art, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + assert_eq!(log(&mut s, "vc.log(typeof app.redraw()); vc.log(app.redraw(1, 'x') === undefined);"), vec![json!("undefined"), json!(true)]); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art); + assert_eq!(undo_steps(&s), steps); + // In a run in the app, edits before and after the calls still end as one undo step. + s.script_frames = true; + let source = "var i = app.activeDocument.pageItems[0]; i.opacity = 40; app.redraw(); i.opacity = 30; app.redraw();"; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap()["running"], true); + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap_or_else(|| panic!("the run did not end")); + ended.unwrap(); + // The edit after the first call landed too: the opacity is below the 40% set before it. + assert!(s.active().unwrap().doc.node(top).unwrap().opacity < 0.4); + assert_eq!(undo_steps(&s), steps + 1); +} + /// Assigning an item the opacity it reports, rounded to four decimals, changes nothing. #[test] fn assigning_the_reported_opacity_changes_nothing() { @@ -278,6 +477,51 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(undo_steps(&s), steps + 1); } +/// `blendingMode` reads and sets the object's own blend mode as a `BlendModes` value; the mode it +/// already has adds no undo step, and any other value throws and changes nothing. +#[test] +fn blending_mode_reads_and_sets_the_objects_blend_mode() { + let (mut s, a, b) = doc(); + let blend = |s: &Session, id: NodeId| s.active().unwrap().doc.node(id).unwrap().blend; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[1]; vc.log(i.blendingMode);\ + i.blendingMode = BlendModes.MULTIPLY; vc.log(i.blendingMode);\ + vc.log([i.hasOwnProperty('blendingMode'), BlendModes.SATURATIONBLEND, BlendModes.COLORBLEND]);", + ); + assert_eq!(out[..2], [json!("BlendModes.NORMAL"), json!("BlendModes.MULTIPLY")]); + assert_eq!(out[2], json!([true, "BlendModes.SATURATIONBLEND", "BlendModes.COLORBLEND"])); + assert_ne!(blend(&s, a), blend(&s, b), "only the assigned object changed"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + let (before, steps) = (blend(&s, a), undo_steps(&s)); + log(&mut s, "var i = app.activeDocument.pageItems[1]; i.blendingMode = BlendModes.MULTIPLY; i.blendingMode = i.blendingMode;"); + assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "the mode the object has adds no step"); + // Two modes the help page names with a suffix set the modes the Transparency panel calls Color + // and Saturation. + log(&mut s, "var p = app.activeDocument.pageItems; p[1].blendingMode = BlendModes.COLORBLEND; p[0].blendingMode = BlendModes.SATURATIONBLEND;"); + assert_eq!((blend(&s, a).label(), blend(&s, b).label()), ("Color", "Saturation")); + let (before, steps) = (blend(&s, a), undo_steps(&s)); + for value in + ["'BlendModes.SCREEN '", "'MULTIPLY'", "'Multiply'", "'BlendModes.multiply'", "'BlendModes.NOPE'", "5", "null", "ZOrderMethod.BRINGTOFRONT"] + { + // The error is caught in the script, so the run does not roll back and the mode read right + // after it is the one the setter left. + let out = log( + &mut s, + &format!( + "var i = app.activeDocument.pageItems[1], e = '';\ + try {{ i.blendingMode = {value}; }} catch (x) {{ e = String(x); }}\ + vc.log(e); vc.log(i.blendingMode);" + ), + ); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("blendingMode needs a BlendModes value"), "{value}: {e}"); + assert_eq!(out[1], json!("BlendModes.COLORBLEND"), "{value}"); + assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "{value}"); + } +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -985,13 +1229,13 @@ fn a_startup_preset_alone_gives_its_first_size() { fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] + ["app.activeDocument.pageItems[0].isIsolated;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); // A deleted item or an earlier run's document is stale first. - let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.blendingMode;"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.isIsolated;"); assert!(e.contains("Stale page item"), "{e}"); run(&mut s, "#targetengine keep\nvar d = app.activeDocument;").unwrap(); let e = failure(&mut s, "#targetengine keep\nd.layers;"); @@ -1523,6 +1767,23 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", t.0)), "{e}"); + assert!(s.active().unwrap().doc.node(t).is_some()); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn move_and_duplicate_refuse_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); @@ -1770,7 +2031,7 @@ fn unsupported_members_say_so() { /// A script that names each visible selected object after its place in `app.selection`, testing /// the members it uses with `hasOwnProperty` and `propertyIsEnumerable` first. A member that is not -/// available yet, such as `blendingMode`, is read only when `hasOwnProperty` reports it, so it is +/// available yet, such as `isIsolated`, is read only when `hasOwnProperty` reports it, so it is /// never read. const NAME_PICKED: &str = "\ var picked = app.selection, k = picked.length, named = 0;\ @@ -1778,7 +2039,7 @@ const NAME_PICKED: &str = "\ while (k--) {\ var obj = picked[k];\ var usable = obj.propertyIsEnumerable('name') && obj.hasOwnProperty('hidden') && !obj.hidden;\ - if (obj.hasOwnProperty('blendingMode') && obj.blendingMode) usable = false;\ + if (obj.hasOwnProperty('isIsolated') && obj.isIsolated) usable = false;\ if (usable) { obj.name = 'picked ' + k; named += 1; }\ }\ if (picked.length && named < picked.length) alert('Some objects were skipped.');"; @@ -1857,9 +2118,9 @@ fn page_items_report_their_available_members_as_their_own() { vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ app.hasOwnProperty('activeDocument')]);\ - vc.log([p.hasOwnProperty('blendingMode'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ + vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ - vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('blendingMode')]);", + vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);", ); assert_eq!(out[0], json!([true, true, true, true, true, true, true])); // Members that are not available yet, unknown names and inherited ones are not the object's own. @@ -1988,7 +2249,37 @@ fn a_collection_read_with_a_name_gives_the_named_object() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); } -/// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or +/// A collection read with a name that is the text of a number but not an array index, such as `-1` +/// or `1.5`, gives the object of that name, and `undefined` when nothing has it; array indices stay +/// positions, and `index` still takes a number as a position. +#[test] +fn a_collection_read_with_a_number_name_that_is_not_an_index_gives_the_named_object() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "NaN"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = [];\ + vc.log([p['-1'] === p.getByName('-1'), '-1' in p, p[-1] === p.getByName('-1'), p.NaN === p.getByName('NaN'), 'NaN' in p]);\ + vc.log([p['1.5'] === undefined, '1.5' in p, p[0].name, p['1'].name]);\ + try { p.index(-1); } catch (e) { m.push(e.message); }\ + var t = new DocumentPreset(); t.title = '1.5'; var d = app.documents.addDocument('Print', t);\ + var ds = app.documents; vc.log([ds['1.5'] === d, '1.5' in ds, ds[1.5] === d, ds['-1'] === undefined, '-1' in ds]);\ + try { ds.index(1.5); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!( + out, + vec![ + json!([true, true, true, true, true]), + json!([true, false, "NaN", "-1"]), + json!([true, true, true, true, false]), + json!(["Not found", "Not found"]), + ] + ); +} + +/// `opacity`, `blendingMode`, `hidden`, `locked` and the position and size setters on an object in a hidden or /// locked layer throw and the run changes nothing, while its name and note still change; an object /// that is hidden or locked itself takes them. #[test] @@ -2008,6 +2299,7 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { // `hidden` and `locked` are refused even when the value is the one the object has. for set in [ "opacity = 50", + "blendingMode = BlendModes.MULTIPLY", "hidden = true", "hidden = false", "locked = true", @@ -2029,9 +2321,9 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { let out = log( &mut s, "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; c.opacity = c.opacity;\ - vc.log([c.name, c.note, c.opacity]); c.name = 'closed'; c.note = '';", + c.blendingMode = c.blendingMode; vc.log([c.name, c.note, c.opacity, c.blendingMode]); c.name = 'closed'; c.note = '';", ); - assert_eq!(out, vec![json!(["renamed", "n", 100])], "{on}"); + assert_eq!(out, vec![json!(["renamed", "n", 100, "BlendModes.NORMAL"])], "{on}"); s.execute("object.setProps", &off).unwrap(); } s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); @@ -2039,9 +2331,11 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { let out = log( &mut s, "var p = app.activeDocument.pageItems; p.getByName('locked').opacity = 50; p.getByName('free').opacity = 40;\ - vc.log([p.getByName('locked').opacity, p.getByName('free').opacity]);", + p.getByName('locked').blendingMode = BlendModes.SCREEN; p.getByName('free').blendingMode = BlendModes.DARKEN;\ + vc.log([p.getByName('locked').opacity, p.getByName('free').opacity, p.getByName('locked').blendingMode,\ + p.getByName('free').blendingMode]);", ); - assert_eq!(out, vec![json!([50, 40])]); + assert_eq!(out, vec![json!([50, 40, "BlendModes.SCREEN", "BlendModes.DARKEN"])]); } /// `name` takes a number or a Boolean as the text `String` gives it, and nothing else. diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 7d8f06700e..dc9749fb6c 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() { fuel: script::DEFAULT_FUEL, locale: "en_US".into(), answers: Vec::new(), + actions: Vec::new(), }; s.script_start(request).unwrap(); assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1])); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 9489921682..184f43cc4a 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -165,7 +165,7 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)"); let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); - assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`")); + assert!(run(&mut s, "new BridgeTalk();").unwrap_err().to_string().contains("`vc`")); // The application's members need no `app.`, so naming one alone is not an error. assert_eq!(run(&mut s, "activeDocument;").unwrap()["ok"], true); assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _")); @@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), @@ -206,7 +206,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); } // The app's own reference error names the `vc` object; the same text a script threw does not. - run(&mut s, "new Window('dialog');").unwrap_err(); + run(&mut s, "new BridgeTalk();").unwrap_err(); assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); // An error in code `eval` compiled keeps where its message came from. @@ -454,6 +454,29 @@ fn every_script_reads_e4x_and_has_the_xml_objects() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_defines_classes_and_a_jsx_script_cannot() { + let dir = fresh_folder("es2015-classes"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let modern = "class Shape { constructor(n) { this.n = n; } sides() { return this.n; } }\n\ + class Square extends Shape { constructor() { super(4); } sides() { return super.sides() * 10; } }\n\ + vc.log(new Square().sides());\nvc.log(eval('class E {} typeof E'));\n"; + let r = s.execute("script.run", &path(&write("shapes.js", modern))).unwrap(); + assert_eq!(r["log"], json!([40, "function"]), "{r}"); + for (name, text) in [("legacy.jsx", "class A {}"), ("object.jsx", "var o = { m() {} };")] { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + assert!(run(&mut s, "var C = class {};").unwrap_err().to_string().contains("SyntaxError")); + let _ = std::fs::remove_dir_all(&dir); +} + /// A new empty folder for test `name`. fn fresh_folder(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs new file mode 100644 index 0000000000..23937fb683 --- /dev/null +++ b/crates/engine/src/tests/script_scriptui.rs @@ -0,0 +1,532 @@ +//! ScriptUI dialogs in a script: the description the engine checks and lays out, the `window` +//! answers a run with nobody to ask takes from `answers`, the wait in the app, Stop, and the +//! report's `dialogs`. + +use serde_json::{Value, json}; +use vectorcraft_js::{Data, HostError}; + +use crate::script::scriptui::{self, MAX_CONTROLS, MAX_DEPTH, MAX_EXTENT, MAX_TEXT_BYTES}; +use crate::script::{ScriptUiDialog, UiEvent, UiKind, UiValue}; +use crate::*; + +/// One open document with one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn art(s: &Session) -> (String, usize) { + let d = &s.documents()[0]; + (format!("{:?}", d.doc.layers), d.history.undo.len()) +} + +fn headless(s: &mut Session, source: &str, answers: Value) -> Result { + s.execute("script.run", &json!({"source": source, "name": "w.js", "answers": answers})) +} + +/// A run in the app of `source`, one slice in. +fn framed(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + assert!(s.script_pump().is_none()); +} + +/// Pumps the run in the app until it ends or waits at a ScriptUI dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_window().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +fn window(steps: Value) -> Value { + json!([{"kind": "window", "value": steps}]) +} + +const EDIT: &str = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + +/// A dialog with a field, a check box, a slider, a list and OK and Cancel. +const FORM: &str = "var w = new Window('dialog', 'Settings'); var g = w.add('group'); \ + g.add('statictext', undefined, 'Name:'); var name = g.add('edittext', undefined, 'first', {name: 'name'}); \ + var bold = w.add('checkbox', undefined, 'Bold'); var size = w.add('slider', undefined, 5, 0, 10); size.name = 'size'; \ + var pick = w.add('dropdownlist', undefined, ['a', 'b', 'c']); pick.name = 'pick'; \ + var ok = w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel');"; + +#[test] +fn a_run_with_nobody_to_ask_takes_the_steps_of_its_window_answer() { + let mut s = one_doc(); + let source = format!( + "{EDIT} {FORM} bold.onClick = function () {{ name.text = 'bolded'; }}; var r = w.show(); vc.log([r, name.text, bold.value, size.value, pick.selection.text]);" + ); + let steps = json!([ + {"control": "Bold", "event": "click"}, + {"control": "size", "event": "change", "value": 99}, + {"control": "pick", "event": "change", "value": 2}, + {"control": "OK", "event": "click"}, + ]); + let r = headless(&mut s, &source, window(steps)).unwrap(); + assert_eq!(r["log"], json!([[1, "bolded", true, 10, "c"]]), "the slider's value is clamped to its range: {r}"); + assert_eq!(r["dialogs"], json!([{"kind": "window", "title": "Settings", "controls": 8, "events": 4, "answer": 1}])); + let cancel = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"control": "Cancel", "event": "click"}]))).unwrap(); + assert_eq!(cancel["log"], json!([2])); + let closed = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"event": "close"}]))).unwrap(); + assert_eq!(closed["log"], json!([0])); +} + +#[test] +fn a_dialog_from_a_resource_specification_takes_the_steps_of_its_window_answer() { + let mut s = one_doc(); + let source = "var w = new Window(\"dialog { text: 'Settings', \ + g: Group { label: StaticText { text: 'Name:' }, field: EditText { text: 'first', properties: {name: 'field'} } }, \ + ok: Button { text: 'OK' } }\"); vc.log([w.show(), w.g.field.text]);"; + let steps = json!([{"control": "field", "event": "change", "value": "typed"}, {"control": "OK", "event": "click"}]); + let r = headless(&mut s, source, window(steps)).unwrap(); + assert_eq!(r["log"], json!([[1, "typed"]]), "{r}"); + assert_eq!(r["dialogs"][0]["title"], "Settings"); + assert_eq!(r["dialogs"][0]["controls"], 4); +} + +#[test] +fn a_dialog_a_handler_opens_is_listed_after_the_window_that_opened_it() { + let mut s = one_doc(); + let source = format!("{FORM} bold.onClick = function () {{ alert('Bolded'); }}; vc.log(w.show());"); + let answers = json!([ + {"kind": "window", "value": [{"control": "Bold", "event": "click"}, {"control": "OK", "event": "click"}]}, + {"kind": "alert", "value": "ok"}, + ]); + let r = headless(&mut s, &source, answers).unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["dialogCount"], 2); + assert_eq!(r["dialogs"][0], json!({"kind": "window", "title": "Settings", "controls": 8, "events": 2, "answer": 1}), "{r}"); + assert_eq!((&r["dialogs"][1]["kind"], &r["dialogs"][1]["message"]), (&json!("alert"), &json!("Bolded")), "{r}"); +} + +#[test] +fn a_missing_wrong_or_unused_step_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!("{EDIT} {FORM} try {{ w.show(); }} catch (e) {{ vc.log('caught'); }}"); + for (given, says) in [ + (json!([]), "`answers` has no answer left for this dialog"), + (json!([{"kind": "alert", "value": "ok"}]), "is for alert, not window"), + (window(json!([])), "has no step left"), + (window(json!([{"control": "Nothing", "event": "click"}])), "the dialog has no control named Nothing"), + (window(json!([{"control": "Name:", "event": "click"}])), "cannot be clicked"), + (window(json!([{"control": "pick", "event": "change", "value": 3}])), "has no item 3"), + (window(json!([{"control": "OK", "event": "click"}, {"event": "close"}])), "has 1 step the dialog did not use"), + ] { + let e = headless(&mut s, &source, given.clone()).unwrap_err().to_string(); + assert!(e.contains(says), "{given}: {e}"); + assert_eq!(art(&s), before, "{given}"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught: {report}"); + assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}"); + } +} + +#[test] +fn a_step_names_a_control_by_its_text_only_when_it_has_no_name() { + let mut s = one_doc(); + let source = "var w = new Window('dialog'); \ + var named = w.add('button', undefined, 'Apply', {name: 'apply'}); named.onClick = function () { vc.log('named'); }; \ + var plain = w.add('button', undefined, 'Apply'); plain.onClick = function () { vc.log('plain'); }; \ + w.add('button', undefined, 'OK'); w.show();"; + let steps = window(json!([{"control": "Apply", "event": "click"}, {"control": "apply", "event": "click"}, {"control": "OK", "event": "click"}])); + headless(&mut s, source, steps).unwrap(); + assert_eq!(s.script_report().unwrap()["log"], json!(["plain", "named"])); + let go = "var w = new Window('dialog'); w.add('button', undefined, 'Go', {name: 'go'}); w.show();"; + let e = headless(&mut s, go, window(json!([{"control": "Go", "event": "click"}]))).unwrap_err().to_string(); + assert!(e.contains("the dialog has no control named Go"), "{e}"); + let help = "var w = new Window('dialog'); w.add('button', undefined, 'Help').onClick = function () { vc.log('help'); }; w.show();"; + let e = headless(&mut s, help, window(json!([{"control": "", "event": "click"}]))).unwrap_err().to_string(); + assert!(e.contains("the dialog has no control named"), "an empty step names no control without a name: {e}"); + let blank = "var w = new Window('dialog'); w.add('button', undefined, 'Help').onClick = function () { vc.log('help'); }; \ + w.add('button', undefined, '').onClick = function () { vc.log('blank'); }; w.add('button', undefined, 'OK'); w.show();"; + headless(&mut s, blank, window(json!([{"control": "", "event": "click"}, {"control": "OK", "event": "click"}]))).unwrap(); + assert_eq!(s.script_report().unwrap()["log"], json!(["blank"]), "an empty step names the unnamed control whose text is empty"); +} + +#[test] +fn window_answers_that_do_not_parse_are_refused_before_the_run() { + let mut s = one_doc(); + let bad = |i: usize| format!("`answers[0]` has a step {i} that is not a valid click, change or close"); + for (steps, says) in [ + (json!("click"), "`answers[0]` is a window's answer, whose `value` must be a list of steps".to_string()), + (json!([1]), bad(0)), + (json!([{"event": "close"}, {"event": "tap", "control": "OK"}]), bad(1)), + (json!([{"event": "click"}]), bad(0)), + (json!([{"event": "click", "control": "OK", "value": 1}]), bad(0)), + (json!([{"event": "change", "control": "x"}]), bad(0)), + (json!([{"event": "change", "control": "x", "value": [1]}]), bad(0)), + (json!([{"event": "change", "control": "x".repeat(MAX_TEXT_BYTES + 1), "value": 1}]), bad(0)), + (json!([{"event": "close", "control": "x"}]), bad(0)), + (json!([{"event": "close", "extra": 1}]), bad(0)), + ] { + let e = headless(&mut s, "1", window(steps.clone())).unwrap_err().to_string(); + assert!(e.contains(&says), "{steps}: {e}"); + } +} + +#[test] +fn a_framed_run_waits_at_show_and_runs_each_handler_with_the_persons_events() { + let mut s = one_doc(); + let undo_before = art(&s).1; + framed( + &mut s, + &format!("{EDIT} {FORM} bold.onClick = function () {{ size.enabled = !bold.value; }}; var r = w.show(); vc.log([r, name.text, size.value]);"), + ); + let d = s.script_window().expect("show waits"); + assert_eq!(d.title(), "Settings"); + assert_eq!(d.nodes.len(), 9); + assert_eq!((d.nodes[3].kind, d.nodes[3].text.as_str()), (UiKind::EditText, "first")); + let bold = d.find("Bold").unwrap(); + let size = d.find("size").unwrap(); + assert!(s.script_window_answer(UiEvent::Click(d.find("Name:").unwrap())).is_err(), "static text takes no click"); + assert!(s.script_window_answer(UiEvent::Change(3, UiValue::Text("x".repeat(MAX_TEXT_BYTES + 1)))).is_err()); + assert!(s.script_window_answer(UiEvent::Click(99)).is_err()); + s.script_window_answer(UiEvent::Click(bold)).unwrap(); + assert!(s.script_window_answer(UiEvent::Close).is_err(), "nothing waits until the run goes on"); + assert!(pump(&mut s).is_none()); + let d = s.script_window().unwrap(); + assert!(d.nodes[bold].checked); + assert!(!d.nodes[size].enabled, "the handler disabled the slider"); + assert!(s.script_window_answer(UiEvent::Change(size, UiValue::Number(3.0))).is_err(), "a disabled control takes no events"); + s.script_window_answer(UiEvent::Change(3, UiValue::Text("Ann".into()))).unwrap(); + assert!(pump(&mut s).is_none()); + s.script_window_answer(UiEvent::Click(d.default_element.unwrap())).unwrap(); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[1, "Ann", 5]])); + assert_eq!(r["dialogs"][0]["events"], 3); + assert_eq!(art(&s).1, undo_before + 1, "a finished run is one undo step"); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script"); +} + +#[test] +fn an_unused_step_after_a_handler_threw_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!( + "{EDIT} var w = new Window('dialog'); var f = w.add('button', undefined, 'Fail'); f.onClick = function () {{ throw new Error('boom'); }}; \ + try {{ w.show(); }} catch (e) {{ vc.log('caught'); }}" + ); + let steps = window(json!([{"control": "Fail", "event": "click"}, {"event": "close"}])); + let e = headless(&mut s, &source, steps).unwrap_err().to_string(); + assert!(e.contains("has 1 step the dialog did not use"), "{e}"); + assert_eq!(art(&s), before, "the run is rolled back"); +} + +#[test] +fn a_list_index_written_as_a_whole_float_is_an_index_and_a_fraction_is_refused() { + let mut s = one_doc(); + let source = format!("{FORM} vc.log([w.show(), pick.selection.text]);"); + let r = headless(&mut s, &source, window(json!([{"control": "pick", "event": "change", "value": 1.0}, {"control": "OK", "event": "click"}]))) + .unwrap(); + assert_eq!(r["log"], json!([[1, "b"]])); + let e = headless(&mut s, &source, window(json!([{"control": "pick", "event": "change", "value": 1.5}]))).unwrap_err().to_string(); + assert!(e.contains("a list's `value` must be an item index or null"), "{e}"); +} + +#[test] +fn a_progress_bar_s_fraction_stays_finite_over_the_widest_range() { + let bar = |min: f64, max: f64, value: f64| { + let n = + with(with(with(node("progressbar", 0.0), "minvalue", Data::Number(min)), "maxvalue", Data::Number(max)), "value", Data::Number(value)); + scriptui::parse(&description(vec![node("dialog", -1.0), n])).unwrap().nodes[1].fraction() + }; + assert_eq!(bar(-1e308, 1e308, 1e308), 1.0); + assert_eq!(bar(-1e308, 1e308, -1e308), 0.0); + assert_eq!(bar(-1e308, 1e308, 0.0), 0.5); + assert_eq!(bar(0.0, 10.0, 3.0), 0.3); + assert_eq!(bar(5.0, 5.0, 5.0), 0.0, "an empty range shows nothing done"); +} + +#[test] +fn stop_while_show_waits_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + framed(&mut s, &format!("{EDIT} {FORM} w.show(); vc.log('after');")); + assert!(s.script_window().is_some()); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert_eq!(s.script_window(), None, "a run asked to stop no longer waits"); + assert!(s.script_window_answer(UiEvent::Close).is_err()); + assert!(s.script_pump().unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{report}"); + assert_eq!(report["dialogs"][0]["answer"], "stop"); + assert_eq!(art(&s), before); + framed(&mut s, &format!("{EDIT} {FORM} w.show();")); + assert!(s.script_abandon(), "quitting while a dialog waits abandons the run"); + assert_eq!(art(&s), before); +} + +#[test] +fn a_handler_that_loops_ends_the_run_at_its_fuel_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!("{EDIT} {FORM} bold.onClick = function () {{ for (;;) {{}} }}; w.show();"); + let e = headless(&mut s, &source, window(json!([{"control": "Bold", "event": "click"}]))).unwrap_err().to_string(); + assert!(e.contains("limit") || e.contains("fuel") || e.contains("instructions"), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "error"); +} + +#[test] +fn a_show_in_a_callback_throws_in_the_app() { + let mut s = one_doc(); + s.script_frames = true; + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var e = ''; try { [1].forEach(function () { w.show(); }); } catch (x) { e = x.message; } vc.log(e);"; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + let r = pump(&mut s).expect("show does not wait in a callback").unwrap(); + assert!(r["log"][0].as_str().unwrap().contains("cannot open inside a callback"), "{r}"); +} + +/// A handler that `notify` runs while no dialog is showing may show one in a run with nobody to +/// ask, which takes a window answer for it; in the app the same `show()` throws. +#[test] +fn a_show_in_a_handler_notify_runs_takes_a_window_answer_with_nobody_to_ask() { + let source = "var b = new Window('dialog').add('button', undefined, 'Go'); var r = ''; \ + b.onClick = function () { var d = new Window('dialog'); d.add('button', undefined, 'OK'); r = d.show(); }; \ + try { b.notify(); } catch (x) { r = x.message; } vc.log(r);"; + let mut s = one_doc(); + let r = headless(&mut s, source, window(json!([{"control": "OK", "event": "click"}]))).unwrap(); + assert_eq!(r["log"], json!([1]), "{r}"); + let mut s = one_doc(); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + let r = pump(&mut s).expect("show does not wait in a handler notify runs").unwrap(); + assert!(r["log"][0].as_str().unwrap().contains("cannot open inside a callback"), "{r}"); +} + +fn node(kind: &str, parent: f64) -> Data { + Data::Object(vec![ + ("kind".into(), Data::String(kind.into())), + ("parent".into(), Data::Number(parent)), + ("name".into(), Data::String(String::new())), + ("text".into(), Data::String("t".into())), + ("enabled".into(), Data::Bool(true)), + ("visible".into(), Data::Bool(true)), + ]) +} + +fn description(nodes: Vec) -> Data { + Data::Object(vec![ + ("nodes".into(), Data::Array(nodes)), + ("defaultElement".into(), Data::Number(-1.0)), + ("cancelElement".into(), Data::Number(-1.0)), + ]) +} + +fn with(n: Data, name: &str, value: Data) -> Data { + let Data::Object(mut fields) = n else { panic!("a node is an object") }; + fields.retain(|(k, _)| k != name); + fields.push((name.into(), value)); + Data::Object(fields) +} + +fn refused(d: &Data) -> String { + match scriptui::parse(d) { + Err(HostError::Type(m) | HostError::Range(m) | HostError::Error(m)) => m, + other => panic!("not refused: {other:?}"), + } +} + +#[test] +fn a_description_out_of_order_too_large_too_deep_or_too_long_is_refused() { + let dialog = node("dialog", -1.0); + assert!(refused(&description(vec![])).contains("has no dialog")); + assert!(refused(&description(vec![node("group", -1.0)])).contains("does not start with the dialog")); + assert!(refused(&description(vec![dialog.clone(), node("button", 2.0), node("group", 0.0)])).contains("before its container")); + assert!(refused(&description(vec![dialog.clone(), node("button", 1.0)])).contains("before its container"), "a control cannot hold itself"); + assert!(refused(&description(vec![dialog.clone(), node("button", 0.0), node("button", 1.0)])).contains("holds none")); + assert!(refused(&description(vec![dialog.clone(), node("dialog", 0.0)])).contains("before its container")); + let many: Vec = std::iter::once(dialog.clone()).chain((0..=MAX_CONTROLS).map(|_| node("button", 0.0))).collect(); + assert!(refused(&description(many)).contains(&format!("at most {MAX_CONTROLS} controls"))); + let deep: Vec = std::iter::once(dialog.clone()).chain((0..=MAX_DEPTH).map(|k| node("group", k as f64))).collect(); + assert!(refused(&description(deep)).contains(&format!("at most {MAX_DEPTH} deep"))); + let long = with(node("statictext", 0.0), "text", Data::String("x".repeat(MAX_TEXT_BYTES + 1))); + assert!(refused(&description(vec![dialog.clone(), long])).contains("longer than 16 KiB")); + let slider = with(with(node("slider", 0.0), "minvalue", Data::Number(5.0)), "maxvalue", Data::Number(1.0)); + assert!(refused(&description(vec![dialog.clone(), slider])).contains("minvalue is larger")); + let nan = with(node("button", 0.0), "bounds", Data::Array(vec![Data::Number(0.0), Data::Number(f64::NAN), Data::Number(1.0), Data::Number(1.0)])); + assert!(refused(&description(vec![dialog.clone(), nan])).contains("not a number")); + let orient = with(dialog.clone(), "orientation", Data::String("diagonal".into())); + assert!(refused(&description(vec![orient])).contains("row, column or stack")); + let align = with(node("button", 0.0), "alignment", Data::String("sideways".into())); + assert!(refused(&description(vec![dialog, align])).contains("no alignment sideways")); +} + +#[test] +fn sizes_and_places_are_clamped_and_the_layout_follows_the_containers() { + let dialog = with(with(node("dialog", -1.0), "orientation", Data::String("column".into())), "margins", Data::Array(vec![Data::Number(10.0); 4])); + let row = with(with(node("group", 0.0), "orientation", Data::String("row".into())), "spacing", Data::Number(5.0)); + let a = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(100.0), Data::Number(20.0)])); + let b = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(50.0), Data::Number(30.0)])); + let huge = + with(node("statictext", 0.0), "bounds", Data::Array(vec![Data::Number(-1e12), Data::Number(0.0), Data::Number(1e12), Data::Number(1e300)])); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog, row, a, b, huge])).unwrap(); + assert_eq!((d.nodes[1].rect.w, d.nodes[1].rect.h), (155.0, 30.0), "a row adds widths and spacing, and takes the tallest height"); + assert_eq!((d.nodes[2].rect.x, d.nodes[3].rect.x), (10.0, 115.0)); + assert_eq!(d.nodes[2].rect.y, 15.0, "a shorter control is centered in its row"); + for n in &d.nodes { + for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] { + assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect); + } + } + let (w, h) = d.size(); + assert!(w <= MAX_EXTENT && h <= MAX_EXTENT); +} + +#[test] +fn characters_reserve_the_width_of_an_edit_field_or_a_static_text() { + let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]); + let text = |kind: &str, t: &str| with(node(kind, 0.0), "text", Data::String(t.into())); + let field = with(text("edittext", "Sample"), "characters", Data::Number(35.0)); + let plain = text("edittext", "Sample"); + let label = with(text("statictext", "Hi"), "characters", Data::Number(10.0)); + let sized = with(with(text("edittext", "Sample"), "characters", Data::Number(35.0)), "size", pair(100.0, 20.0)); + let dialog = with(node("dialog", -1.0), "orientation", Data::String("row".into())); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog, field, plain, label, sized])).unwrap(); + assert_eq!(d.nodes[1].rect.w, 35.0 * 7.0 + 12.0, "35 characters of room"); + assert_eq!(d.nodes[2].rect.w, 80.0, "without characters, the text's own width and the 80 minimum"); + assert_eq!(d.nodes[3].rect.w, 10.0 * 7.0 + 4.0); + assert_eq!(d.nodes[4].rect.w, 100.0, "a size set takes the place of the characters' width"); +} + +#[test] +fn a_hidden_control_and_what_it_holds_take_no_room() { + let dialog = with(node("dialog", -1.0), "orientation", Data::String("row".into())); + let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]); + let a = with(node("button", 0.0), "size", pair(100.0, 20.0)); + let hidden = with(node("group", 0.0), "visible", Data::Bool(false)); + let inside = with(node("button", 2.0), "size", pair(400.0, 300.0)); + let b = with(node("button", 0.0), "size", pair(50.0, 20.0)); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog.clone(), a.clone(), hidden, inside, b.clone()])).unwrap(); + let shown: ScriptUiDialog = scriptui::parse(&description(vec![dialog, a, b])).unwrap(); + assert_eq!(d.size(), shown.size(), "the hidden group and the button in it leave the dialog's size as it is"); + assert_eq!(d.nodes[4].rect.x, shown.nodes[2].rect.x, "the next control takes the hidden group's place"); + assert!(!d.nodes[3].visible, "the button in the hidden group is hidden too"); +} + +#[test] +fn a_control_s_size_keeps_within_its_minimum_and_maximum() { + let dialog = node("dialog", -1.0); + let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]); + let wide = with(with(node("button", 0.0), "size", pair(300.0, -1.0)), "max", pair(120.0, -1.0)); + let tall = with(with(node("button", 0.0), "size", pair(-1.0, -1.0)), "min", pair(-1.0, 60.0)); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog.clone(), wide, tall])).unwrap(); + assert_eq!(d.nodes[1].rect.w, 120.0, "the maximum width holds over a larger size"); + assert_eq!(d.nodes[2].rect.h, 60.0, "the minimum height holds over the estimate"); + let plain: ScriptUiDialog = scriptui::parse(&description(vec![dialog, node("button", 0.0)])).unwrap(); + assert!(plain.nodes[1].rect.h < 60.0 && plain.nodes[1].rect.w > 0.0, "a size of -1 leaves the side to the estimate"); + let column = with(with(node("dialog", -1.0), "orientation", Data::String("column".into())), "size", pair(300.0, -1.0)); + let fill = |n: Data| with(n, "alignment", Data::String("fill".into())); + let capped = with(fill(node("button", 0.0)), "max", pair(90.0, -1.0)); + let d: ScriptUiDialog = scriptui::parse(&description(vec![column, capped, fill(node("button", 0.0))])).unwrap(); + assert!(d.nodes[2].rect.w > 90.0, "a control that fills its column takes the column's width"); + assert_eq!(d.nodes[1].rect.w, 90.0, "a control that fills its column stays within its maximum width"); +} + +#[test] +fn window_s_alert_confirm_and_prompt_open_the_script_dialogs() { + let mut s = one_doc(); + let answers = json!([{"kind": "alert", "value": "ok"}, {"kind": "confirm", "value": false}, {"kind": "prompt", "value": "typed"}]); + let r = headless(&mut s, "vc.log([typeof Window.alert('Hi'), Window.confirm('Go?'), Window.prompt('Name', 'x')]);", answers).unwrap(); + assert_eq!(r["log"], json!([["undefined", false, "typed"]]), "{r}"); + assert_eq!(r["dialogCount"], 3); +} + +/// A description of arbitrary kinds, containers in any order, numbers of any size (infinite and +/// not-a-number ones included) and texts of any length. +fn any_description() -> impl proptest::strategy::Strategy { + use proptest::prelude::*; + let kind = prop_oneof![ + Just("dialog"), + Just("group"), + Just("panel"), + Just("statictext"), + Just("edittext"), + Just("button"), + Just("checkbox"), + Just("radiobutton"), + Just("dropdownlist"), + Just("listbox"), + Just("slider"), + Just("progressbar"), + Just("wobble"), + ]; + let number = prop_oneof![1 => Just(f64::NAN), 1 => Just(f64::INFINITY), 1 => Just(-1e300), 1 => any::(), 6 => -50.0..400.0f64]; + let text = prop_oneof![2 => Just(String::new()), 8 => "[ -~]{0,40}", 1 => Just("x".repeat(MAX_TEXT_BYTES + 1))]; + let bounds = proptest::option::of(proptest::collection::vec(number.clone(), 4..=4)); + let size = proptest::option::of(proptest::collection::vec(number.clone(), 2..=2)); + // The container is a share of the controls before this one, or with a share past 1, one after it. + let fields = (kind, 0.0..1.1f64, text, bounds, size, 0..4usize, number); + proptest::collection::vec(fields, 0..40).prop_map(|nodes| { + let mut containers = vec![0usize]; + let mut out = Vec::new(); + for (i, (kind, share, text, bounds, size, items, value)) in nodes.into_iter().enumerate() { + let kind = if i == 0 { "dialog" } else { kind }; + let parent = match i { + 0 => -1.0, + _ if share >= 1.0 => (i + 1) as f64, + _ => containers[((share * containers.len() as f64) as usize).min(containers.len() - 1)] as f64, + }; + if matches!(kind, "group" | "panel") { + containers.push(i); + } + let numbers = |v: Option>| v.map_or(Data::Null, |v| Data::Array(v.into_iter().map(Data::Number).collect())); + let mut n = with(with(node(kind, parent), "text", Data::String(text)), "bounds", numbers(bounds)); + n = with(n, "size", numbers(size)); + n = with(n, "items", Data::Array((0..items).map(|k| Data::String(k.to_string())).collect())); + n = with(n, "selection", Data::Number(value)); + out.push(with(with(n, "minvalue", Data::Number(0.0)), "value", Data::Number(value))); + } + description(out) + }) +} + +proptest::proptest! { + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(256))] + + /// Any description is refused with an error or laid out with every place and size finite and + /// within the limit. + #[test] + fn any_description_is_refused_or_laid_out_within_its_limits(d in any_description()) { + if let Ok(dialog) = scriptui::parse(&d) { + for n in &dialog.nodes { + for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] { + proptest::prop_assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect); + } + proptest::prop_assert!(n.value.is_finite() && n.selection.is_none_or(|k| k < n.items.len())); + } + } + } +} + +#[test] +fn an_event_is_checked_against_the_dialog() { + let d = scriptui::parse(&description(vec![ + node("dialog", -1.0), + node("button", 0.0), + with(node("edittext", 0.0), "readonly", Data::Bool(true)), + with(with(with(node("slider", 0.0), "minvalue", Data::Number(0.0)), "maxvalue", Data::Number(10.0)), "value", Data::Number(4.0)), + with(node("listbox", 0.0), "items", Data::Array(vec![Data::String("a".into())])), + with(node("button", 0.0), "visible", Data::Bool(false)), + ])) + .unwrap(); + assert_eq!(scriptui::check_event(&d, UiEvent::Click(1)), Ok(UiEvent::Click(1))); + assert!(scriptui::check_event(&d, UiEvent::Click(0)).is_err(), "the dialog itself is no control"); + assert!(scriptui::check_event(&d, UiEvent::Change(2, UiValue::Text("x".into()))).is_err(), "a read-only field takes no text"); + assert_eq!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(-5.0))), Ok(UiEvent::Change(3, UiValue::Number(0.0)))); + assert!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(f64::NAN))).is_err()); + assert!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(Some(1)))).is_err()); + assert_eq!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(None))), Ok(UiEvent::Change(4, UiValue::Index(None)))); + assert!(scriptui::check_event(&d, UiEvent::Click(5)).is_err(), "a hidden control takes no events"); + assert_eq!(scriptui::check_event(&d, UiEvent::Close), Ok(UiEvent::Close)); +} diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs new file mode 100644 index 0000000000..df96906aec --- /dev/null +++ b/crates/engine/src/tests/script_styles.rs @@ -0,0 +1,434 @@ +//! Character and paragraph styles in the script object model. + +use serde_json::{Value, json}; +use vectorcraft_doc::{TextObject, TextStyleDef}; + +use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA}; +use crate::script::TEST_RESULT_BYTES; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A 400 × 300 pt document with point type holding `text`. +fn doc_with(text: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap(); + (s, NodeId(id)) +} + +fn text_of(s: &Session, id: NodeId) -> TextObject { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Each run's text, style name, size and underline. +fn runs(s: &Session, id: NodeId) -> Vec<(String, Option, f64, bool)> { + text_of(s, id).runs.iter().map(|r| (r.text.clone(), r.style.style_name.clone(), r.style.size, r.style.underline)).collect() +} + +fn char_names(s: &Session) -> Vec { + s.active().unwrap().doc.char_styles.iter().map(|d| d.name.clone()).collect() +} + +const DOC: &str = "var d = app.activeDocument, cs = d.characterStyles, ps = d.paragraphStyles, tf = d.textFrames[0];"; + +#[test] +fn style_collections_list_the_normal_style_first_and_add_find_and_remove() { + let (mut s, _) = doc_with("Hello"); + let before = undo_steps(&s); + let out = log( + &mut s, + &format!( + "{DOC} vc.log([cs.length, ps.length, cs[0].name, ps[0].name, cs.typename, cs[0].typename, ps[0].typename]);\ + var b = cs.add('Body'); var p = ps.add('Lead');\ + vc.log([cs.length, cs[1].name, cs.getByName('Body').name, cs.index(1).name, cs.index('Body').name, b.parent.typename]);\ + vc.log([ps.length, ps.getByName('Lead').name, cs[5] === undefined]);\ + cs.add('Other'); cs.removeAll(); ps.removeAll();\ + vc.log([cs.length, ps.length, cs[0].name]);" + ), + ); + assert_eq!(out[0], json!([1, 1, NORMAL_CHAR, NORMAL_PARA, "CharacterStyles", "CharacterStyle", "ParagraphStyle"])); + assert_eq!(out[1], json!([2, "Body", "Body", "Body", "Body", "Document"])); + assert_eq!(out[2], json!([2, "Lead", true])); + assert_eq!(out[3], json!([1, 1, NORMAL_CHAR])); + assert_eq!(undo_steps(&s), before + 1); + let undo = undo_steps(&s); + for (src, says) in [ + ("cs.getByName('Nope');", "Not found"), + ("cs.index(4);", "Not found"), + ("cs.add('Body'); cs.add('Body');", "already exists"), + ("cs[0].remove();", "cannot be removed"), + ("ps[0].name = 'Mine';", "cannot be renamed"), + ("cs.getByName(5);", "string"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!((undo_steps(&s), char_names(&s)), (undo, Vec::::new())); +} + +/// Names are trimmed; an empty name, one past 256 characters and one with a control character +/// are refused with nothing changed. +#[test] +fn style_names_are_trimmed_and_checked() { + let (mut s, _) = doc_with("Hello"); + let out = log(&mut s, &format!("{DOC} vc.log(cs.add(' Lead ').name); vc.log(cs.add('{}').name.length);", "x".repeat(256))); + assert_eq!(out, [json!("Lead"), json!(256)]); + let undo = undo_steps(&s); + let long = "x".repeat(257); + for (src, says) in [ + ("cs.add(' ');".to_string(), "empty"), + (format!("cs.add('{long}');"), "256 characters"), + ("cs.add('a\\u0007b');".to_string(), "control characters"), + ("ps.add('tab\\there');".to_string(), "control characters"), + ("cs.getByName('Lead').name = 'x\\ny';".to_string(), "control characters"), + ("cs.add(5);".to_string(), "string"), + (format!("cs.getByName('{}');", "y".repeat(5000)), "too long"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(undo_steps(&s), undo); + assert_eq!(char_names(&s).len(), 2); + // Path characters are kept as part of the name; a style name never names a file. + let out = log(&mut s, &format!("{DOC} vc.log(cs.add('../a/b\\\\c:*?').name);")); + assert_eq!(out, [json!("../a/b\\c:*?")]); + assert_eq!(char_names(&s).last().map(String::as_str), Some("../a/b\\c:*?")); +} + +/// A style attribute that is not a finite number in range is refused with nothing changed. +#[test] +fn style_attributes_refuse_values_that_are_not_finite_or_in_range() { + let (mut s, _) = doc_with("Hello"); + log(&mut s, &format!("{DOC} cs.add('X'); ps.add('P');")); + let undo = undo_steps(&s); + for (src, says) in [ + ("cs[1].characterAttributes.size = NaN;", "finite number"), + ("cs[1].characterAttributes.size = Infinity;", "finite number"), + ("cs[1].characterAttributes.size = 1e9;", "0.1 to 1296"), + ("cs[1].characterAttributes.leading = 1e300;", "0.1 to 5000"), + ("cs[1].characterAttributes.tracking = -1e9;", "tracking"), + ("ps[1].paragraphAttributes.leftIndent = NaN;", "finite"), + ("ps[1].paragraphAttributes.spaceBefore = 1e12;", "1296"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(undo_steps(&s), undo); + let attrs = |s: &Session| { + s.active().unwrap().doc.char_styles.iter().chain(s.active().unwrap().doc.para_styles.iter()).map(|d| d.attrs.len()).sum::() + }; + assert_eq!(attrs(&s), 0); +} + +/// A style object follows its style through a rename made with it; after the style is removed, +/// with the object or with a command, every member throws, and a new style of that name does not +/// bring it back. +#[test] +fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { + let (mut s, id) = doc_with("Hello"); + let out = log( + &mut s, + &format!( + "{DOC} var a = cs.add('A'); a.applyTo(tf.textRange); a.name = ' B '; vc.log([a.name, cs[1].name, a === cs.getByName('B')]);\ + a.name = 'B'; vc.log(cs.length);" + ), + ); + assert_eq!(out, [json!(["B", "B", true]), json!(2)]); + assert_eq!(runs(&s, id)[0].1.as_deref(), Some("B")); + for remove in ["a.remove();", "vc.run('charStyle.delete', {name: 'B'});", "cs.removeAll();"] { + let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); {remove} cs.add('B'); a.name;")); + assert!(e.contains("Stale style"), "{remove}: {e}"); + } + // A style removed and made again by commands is another style. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('charStyle.delete', {{name: 'B'}}); vc.run('charStyle.new', {{name: 'B', attrs: {{}}}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // So is a style removed and made again by the steps of one batch. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.delete', params: {{name: 'B'}}}}, \ + {{command: 'charStyle.new', params: {{name: 'B', attrs: {{}}}}}}]}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // And a style a batch renames and then names back. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.rename', params: {{name: 'B', to: 'C'}}}}, \ + {{command: 'charStyle.rename', params: {{name: 'C', to: 'B'}}}}]}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // The attributes object of a removed style throws for its typename too. + let e = + failure(&mut s, &format!("{DOC} var t = cs.getByName('B').characterAttributes; vc.log(t.typename); cs.getByName('B').remove(); t.typename;")); + assert!(e.contains("Stale style"), "{e}"); + // A style renamed by a command is stale too, and its text keeps its look after a removal. + let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;")); + assert!(e.contains("Stale style"), "{e}"); + let e = + failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.characterAttributes.size;")); + assert!(e.contains("Stale style"), "{e}"); + let size = runs(&s, id)[0].2; + log(&mut s, &format!("{DOC} var a = cs.getByName('B'); a.characterAttributes.size = 40; a.remove();")); + assert_eq!(runs(&s, id)[0].1, None); + assert_ne!(runs(&s, id)[0].2, size); + assert_eq!(runs(&s, id)[0].2, 40.0); +} + +/// The steps of one batch a script runs keep one copy of a document's style lists, however many of +/// them change the lists. +#[test] +fn the_steps_of_a_batch_keep_one_copy_of_the_style_lists() { + let (mut s, _) = doc_with("Hello"); + let commands: Vec = (0..20).map(|i| json!({"command": "charStyle.new", "params": {"name": format!("S{i}"), "attrs": {}}})).collect(); + s.script_in_run = true; + let r = s.execute("command.batch", &json!({"commands": commands})); + s.script_in_run = false; + r.unwrap(); + assert_eq!(char_names(&s).len(), 20); + assert_eq!(crate::script::retained_style_lists(&s), 1); +} + +/// A removal or rename whose result cannot cross to the script is put back, and the style's object +/// still names the style after it. +#[test] +fn a_style_change_that_is_put_back_keeps_the_style_object() { + let (mut s, _) = doc_with("Hello"); + s.execute("charStyle.new", &json!({"name": "B", "attrs": {}})).unwrap(); + TEST_RESULT_BYTES.with(|b| b.set(Some(1))); + let r = run( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B');\ + try {{ a.remove(); }} catch (e) {{ vc.log(e.name); }}\ + try {{ vc.run('charStyle.delete', {{name: 'B'}}); }} catch (e) {{ vc.log(e.name); }}\ + try {{ a.name = 'C'; }} catch (e) {{ vc.log(e.name); }}\ + vc.log([a.name, a === cs.getByName('B'), cs.length]);" + ), + ); + TEST_RESULT_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", ["B", true, 2]]), "{r}"); + assert!(char_names(&s).contains(&"B".to_string()), "{:?}", char_names(&s)); +} + +/// A character style styles exactly the range; without clearing overrides the range keeps its +/// own underline, and with them it goes back to the Normal style first. +#[test] +fn apply_to_styles_a_range_and_clearing_overrides_resets_it() { + let (mut s, id) = doc_with("Hello world"); + let before = undo_steps(&s); + log( + &mut s, + &format!("{DOC} var w = tf.words[0]; w.underline = true; var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo(w);"), + ); + assert_eq!(runs(&s, id), [("Hello".into(), Some("Big".into()), 30.0, true), (" world".into(), None, 12.0, false)]); + assert_eq!(undo_steps(&s), before + 1); + log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf.words[0], true);")); + assert_eq!(runs(&s, id)[0], ("Hello".into(), Some("Big".into()), 30.0, false)); + // A whole frame, and an empty range, which changes nothing. + log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf); cs[0].applyTo(tf.characters[0]);")); + assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]); +} + +/// A character style applied to an empty frame styles the text set in it later. +#[test] +fn a_character_style_applied_to_an_empty_frame_styles_text_set_later() { + for target in ["tf", "tf.textRange"] { + let (mut s, id) = doc_with(""); + log(&mut s, &format!("{DOC} var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo({target}); tf.contents = 'Hi';")); + assert_eq!(runs(&s, id), [("Hi".into(), Some("Big".into()), 30.0, false)], "{target}"); + } +} + +/// A paragraph style styles every paragraph the text touches, and only those. +#[test] +fn a_paragraph_style_styles_the_paragraphs_the_text_touches() { + let (mut s, id) = doc_with("one\ntwo\nthree"); + let out = log( + &mut s, + &format!( + "{DOC} var c = ps.add('Centered'); var a = c.paragraphAttributes;\ + vc.log([a.justification === undefined, a.spaceBefore === undefined, a.typename]);\ + a.justification = Justification.CENTER; a.spaceBefore = 6;\ + vc.log([a.justification, a.spaceBefore]); c.applyTo(tf.paragraphs[1]);\ + vc.log(tf.paragraphs[1].paragraphAttributes.justification);" + ), + ); + assert_eq!(out, [json!([true, true, "ParagraphAttributes"]), json!(["Justification.CENTER", 6]), json!("Justification.CENTER")]); + let t = text_of(&s, id); + let names: Vec<_> = (0..3).map(|i| t.para_at(i).style_name.clone()).collect(); + assert_eq!(names, [None, Some("Centered".to_string()), None]); + assert_eq!(t.para_at(1).space_before, 6.0); + assert_eq!(t.para_at(2).space_before, 0.0); + let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.justification = 'middle';")); + assert!(e.contains("Justification"), "{e}"); + let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.spaceAfter = 5000;")); + assert!(e.contains("1296"), "{e}"); +} + +/// A style's character attributes read `undefined` until set; setting one restyles the text in +/// the style but not a value the text changed itself. +#[test] +fn style_attributes_redefine_the_text_in_the_style() { + let (mut s, id) = doc_with("ab cd"); + let out = log( + &mut s, + &format!( + "{DOC} var x = cs.add('X'), a = x.characterAttributes;\ + vc.log([a.size === undefined, a.autoLeading === undefined, a.textFont === undefined, a.typename]);\ + a.size = 20; x.applyTo(tf.textRange); tf.words[1].size = 9; a.size = 24; a.autoLeading = true; a.underline = true;\ + vc.log([a.size, a.autoLeading, a.underline]);" + ), + ); + assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]); + assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]); + // Turning auto leading off keeps the leading auto leading gave the style's size. + let out = log( + &mut s, + &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);"), + ); + assert_eq!(out, [json!([false, 288])]); + let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;")); + assert!(e.contains("0.1 to 1296"), "{e}"); + let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.textFont = 'Arial';")); + assert!(e.contains("TextFont"), "{e}"); + let e = failure(&mut s, &format!("{DOC} ps.add('P').characterAttributes;")); + assert!(e.contains("not available yet"), "{e}"); +} + +/// A range lists each style its text uses once, in order, with the Normal style for unstyled +/// text, and its lists cannot add or remove styles. +#[test] +fn a_range_lists_the_styles_its_text_uses() { + let (mut s, _) = doc_with("aa bb cc\ndd"); + let out = log( + &mut s, + &format!( + "{DOC} var x = cs.add('X'), y = cs.add('Y'); y.applyTo(tf.words[2]); x.applyTo(tf.words[1]); x.applyTo(tf.words[3]);\ + ps.add('P').applyTo(tf.paragraphs[1]);\ + function names(l) {{ var o = []; for (var i = 0; i < l.length; i++) o.push(l[i].name); return o; }}\ + vc.log(names(tf.textRange.characterStyles)); vc.log(names(tf.words[1].characterStyles));\ + vc.log(names(tf.textRange.paragraphStyles)); vc.log(names(tf.paragraphs[0].paragraphStyles));\ + vc.log([tf.words[1].characterStyles[0] === x, tf.words[1].characterStyles.getByName('X').name,\ + tf.textRange.characterStyles.parent.typename]);" + ), + ); + assert_eq!(out[0], json!([NORMAL_CHAR, "X", "Y"])); + assert_eq!(out[1], json!(["X"])); + assert_eq!(out[2], json!([NORMAL_PARA, "P"])); + assert_eq!(out[3], json!([NORMAL_PARA])); + assert_eq!(out[4], json!([true, "X", "TextRange"])); + for src in ["tf.textRange.characterStyles.add('Z');", "tf.textRange.paragraphStyles.removeAll();"] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains("cannot be added or removed"), "{src}"); + } +} + +/// `applyTo` refuses what is not text, a `clearingOverrides` that is not a boolean, text of another +/// document, and a range whose text changed, with nothing changed. +#[test] +fn apply_to_refuses_bad_arguments_with_nothing_changed() { + let (mut s, id) = doc_with("Hello"); + log(&mut s, &format!("{DOC} cs.add('X');")); + let runs_before = runs(&s, id); + for (src, says) in [ + ("cs[1].applyTo(5);".to_string(), "TextRange"), + ("cs[1].applyTo(tf.textRange, 'yes');".to_string(), "clearingOverrides"), + ("cs[1].applyTo(cs);".to_string(), "TextRange"), + (format!("var r = tf.textRange; vc.run('text.setText', {{id: {}, text: 'Help'}}); cs[1].applyTo(r);", id.0), "Stale text range"), + ( + "var o = app.documents.add(); var t = o.textFrames.add(); t.contents = 'Other'; cs[1].applyTo(t.textRange);".to_string(), + "another document", + ), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(runs(&s, id), runs_before); +} + +/// A run names at most 4,096 styles; reading past that throws instead of growing without bound. +#[test] +fn style_objects_made_before_file_revert_go_stale_even_when_the_style_is_back() { + let (mut s, _) = doc_with("Hello"); + s.execute("charStyle.new", &json!({"name": "B", "attrs": {"size": 30}})).unwrap(); + let path = std::env::temp_dir().join(format!("vc-styles-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B');\ + vc.run('shape.rectangle', {{x: 1, y: 1, width: 5, height: 5}}); vc.run('file.revert', {{}});\ + var cs2 = app.activeDocument.characterStyles;\ + try {{ vc.log(a.name); }} catch (e) {{ vc.log(e.message); }}\ + vc.log(cs2.getByName('B').name); vc.log(cs2.getByName('B') === a);" + ), + ); + let _ = std::fs::remove_file(&path); + assert!(out[0].as_str().is_some_and(|m| m.contains("Stale style")), "{out:?}"); + assert_eq!(out[1], json!("B"), "a style object made after the revert names the reverted style"); + assert_eq!(out[2], json!(false)); +} + +#[test] +fn a_run_names_at_most_4096_styles() { + let (mut s, _) = doc_with("Hello"); + let mut d = (*s.active().unwrap().doc).clone(); + let defs: Vec = (0..4100).map(|i| TextStyleDef { name: format!("S{i}"), attrs: Default::default() }).collect(); + d.char_styles = defs.into(); + s.doc_mut().unwrap().doc = std::sync::Arc::new(d); + let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; vc.log(cs[0] === undefined); vc.log(cs.length);")); + assert_eq!(out, [json!(false), json!(4101)]); + let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;")); + assert!(e.contains("4096 styles"), "{e}"); + // `add` with every slot taken adds no style; with one slot left it adds the style. + let out = log( + &mut s, + &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; try {{ cs.add('New'); }} catch (e) {{ vc.log(e.message); }} vc.log(cs.length);"), + ); + assert_eq!(out, [json!("a script can name at most 4096 styles in one run"), json!(4101)]); + let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4095; i++) cs[i]; vc.log(cs.add('New').name); vc.log(cs.length);")); + assert_eq!(out, [json!("New"), json!(4102)]); +} + +/// A script loads styles from a file only where it may read files; a file outside that is refused. +#[test] +fn a_script_loads_styles_only_from_a_file_it_may_read() { + let (mut s, _) = doc_with("Hello"); + let dir = std::env::temp_dir().join(format!("vc-script-styles-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Other.vectorcraft"); + let mut other = Session::new(); + other.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + other.execute("charStyle.new", &json!({"name": "Loaded", "attrs": {"size": 30}})).unwrap(); + std::fs::write(&path, vectorcraft_format::save(&other.active().unwrap().doc, false)).unwrap(); + let p = path.to_string_lossy().replace('\\', "/"); + let e = failure(&mut s, &format!("vc.run('charStyle.load', {{path: '{p}'}});")); + std::fs::remove_dir_all(&dir).ok(); + assert!(e.contains("access denied"), "{e}"); + assert!(char_names(&s).is_empty()); +} diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs new file mode 100644 index 0000000000..0a71638c92 --- /dev/null +++ b/crates/engine/src/tests/script_text.rs @@ -0,0 +1,653 @@ +//! Type in the script object model: `textFrames`, text ranges, their attributes and `textFonts`. + +use serde_json::{Value, json}; +use vectorcraft_doc::Justify; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A 400 × 300 pt document with point type holding `text`. +fn doc_with(text: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap(); + (s, NodeId(id)) +} + +fn plain(s: &Session, id: NodeId) -> String { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } +} + +fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.size)).collect(), + _ => panic!("not text"), + } +} + +#[test] +fn text_frames_add_point_area_and_path_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 200, "height": 100})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + var area = d.textFrames.areaText(p[1]); area.contents = 'Area';\ + var path = d.textFrames.pathText(p[0]); path.contents = 'Path';\ + var pt = d.textFrames.add(); pt.contents = 'Point';\ + var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ + vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ + vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\ + vc.log([d.textFrames[0].contents, d.textFrames[3].contents]); vc.log(d.textFrames[9] === undefined);\ + vc.log(at.orientation); vc.log(d.textFrames.parent.typename);", + ); + assert_eq!(out[0], json!(4)); + assert_eq!(out[1], json!(["TextType.AREATEXT", "TextType.PATHTEXT", "TextType.POINTTEXT"])); + // Topmost first, as `pageItems` lists them: the newest type, then the area type on the rectangle. + assert_eq!( + out[2..], + [json!("TextFrame"), json!(true), json!(["At", "Area"]), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")] + ); + assert_eq!(undo_steps(&s), before + 1); + // A path of another kind, or no path, is refused. + assert!(failure(&mut s, "app.activeDocument.textFrames.areaText(app.activeDocument.textFrames[0]);").contains("PathItem")); + assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1]);").contains("anchor")); + assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1, 2], 'up');").contains("TextOrientation")); + assert_eq!(undo_steps(&s), before + 1); + // pathText takes its orientation fourth, after the start and end positions it does not take yet. + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 250}, {"x": 300, "y": 260}], "closed": false})).unwrap(); + let find = "var d = app.activeDocument, p = d.pageItems, q; for (var i = 0; i < p.length; i++) if (p[i].typename == 'PathItem') q = p[i];"; + assert!(failure(&mut s, &format!("{find} d.textFrames.pathText(q, 0.5);")).contains("not available yet")); + let out = log(&mut s, &format!("{find} vc.log(d.textFrames.pathText(q, undefined, undefined, TextOrientation.VERTICAL).orientation);")); + assert_eq!(out, vec![json!("TextOrientation.VERTICAL")]); +} + +#[test] +fn contents_reads_paragraph_breaks_as_r_and_accepts_every_break() { + let (mut s, id) = doc_with("x"); + let out = log(&mut s, "var t = app.activeDocument.textFrames[0]; t.contents = 'a\\rb\\r\\nc\\nd\\u0003e'; vc.log(t.contents);"); + assert_eq!(out, vec![json!("a\rb\rc\rd\u{3}e")]); + assert_eq!(plain(&s, id), "a\nb\nc\nd\u{2028}e"); + assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = true;").contains("contents must be a string or a number")); +} + +#[test] +fn contents_takes_a_number_as_its_text() { + let (mut s, id) = doc_with("x"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; t.contents = 7; vc.log(t.contents);\ + t.textRange.characters[0].contents = 2.5; vc.log(t.contents);", + ); + assert_eq!(out, vec![json!("7"), json!("2.5")]); + assert_eq!(plain(&s, id), "2.5"); +} + +#[test] +fn offsets_count_utf16_units_and_keep_surrogate_pairs_whole() { + let (mut s, _) = doc_with("a\u{1F600}b cd"); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, c = r.characters;\ + vc.log([r.length, r.start, r.end, c.length]);\ + vc.log([c[1].start, c[1].length, c[2].start, c[2].contents]);\ + vc.log([r.words.length, r.words[1].contents, r.words[0].characters.length]);\ + vc.log(app.activeDocument.textFrames[0].contents.length === r.length);", + ); + assert_eq!(out, vec![json!([7, 0, 7, 6]), json!([1, 2, 3, "b"]), json!([2, "cd", 3]), json!(true)]); +} + +#[test] +fn the_first_character_of_each_word_grows_in_one_undo_step() { + let (mut s, id) = doc_with("one two"); + let before = undo_steps(&s); + log( + &mut s, + "var text = app.activeDocument.textFrames[0].textRange;\ + for (var j = 0; j < text.words.length; j++) { var f = text.words[j].characters[0]; f.size = f.size * 1.5; }", + ); + assert_eq!(sizes(&s, id), vec![("o".into(), 18.0), ("ne ".into(), 12.0), ("t".into(), 18.0), ("wo".into(), 12.0)]); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn ranges_follow_model_edits_and_go_stale_after_other_edits() { + let (mut s, id) = doc_with("one two three"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], w = t.words, second = w[1], third = w[2];\ + w[0].contents = 'first'; vc.log([second.contents, second.start, third.contents]);\ + second.contents = ''; vc.log([second.length, third.contents, t.contents]);", + ); + assert_eq!(out, vec![json!(["two", 6, "three"]), json!([0, "three", "first three"])]); + let source = format!("var r = app.activeDocument.textFrames[0].words[0]; vc.run('text.setText', {{id: {}, text: 'other'}}); r.contents;", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{e}"); + let e = failure(&mut s, "var t = app.activeDocument.textFrames[0], r = t.textRange; t.remove(); r.contents;"); + assert!(e.contains("Stale text range"), "{e}"); + // A change reversed before the range is read leaves the text the range knew. + let (mut s, id) = doc_with("one two"); + let source = format!( + "var r = app.activeDocument.textFrames[0].words[1]; vc.run('text.setText', {{id: {0}, text: 'other'}});\ + vc.run('text.setText', {{id: {0}, text: 'one two'}}); vc.log([r.contents, r.start]);", + id.0 + ); + assert_eq!(log(&mut s, &source), vec![json!(["two", 4])]); +} + +#[test] +fn ranges_made_before_file_revert_go_stale_even_when_the_text_is_the_same() { + let (mut s, _) = doc_with("one two"); + let path = std::env::temp_dir().join(format!("vc-text-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.words[1];\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + var now = app.activeDocument.textFrames[0];\ + vc.log(now.contents); try { vc.log(r.contents); } catch (e) { vc.log(e.message); }\ + vc.log(now.words[1].contents);", + ); + let _ = std::fs::remove_file(&path); + assert_eq!(out[0], json!("one two"), "the reverted file holds the same text"); + assert!(out[1].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert_eq!(out[2], json!("two"), "a range made after the revert reads the reverted text"); +} + +#[test] +fn a_frame_and_its_ranges_held_across_file_revert_go_stale() { + let (mut s, _) = doc_with("one two"); + let path = std::env::temp_dir().join(format!("vc-text-revert-held-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange, w = t.words;\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + try { vc.log(t.contents); } catch (e) { vc.log(e.message); }\ + try { vc.log(r.contents); } catch (e) { vc.log(e.message); }\ + try { vc.log(w.length); } catch (e) { vc.log(e.message); }\ + var now = app.activeDocument.textFrames[0], r2 = now.textRange;\ + vc.log(r2.contents); r2.contents = 'three'; vc.log(now.contents);", + ); + let _ = std::fs::remove_file(&path); + assert!(out[0].as_str().is_some_and(|m| m.contains("Stale page item")), "{out:?}"); + assert!(out[1].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert_eq!(out[3], json!("one two"), "a range made after the revert reads the reverted text"); + assert_eq!(out[4], json!("three"), "a frame found after the revert can be edited"); +} + +#[test] +fn a_range_an_edit_covers_holds_the_edits_new_text() { + let (mut s, _) = doc_with("abc"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], first = t.characters[0], r = t.characters[1];\ + t.characters[2].contents = 'ZZ'; vc.log([first.contents, r.contents]);\ + t.contents = 'XY'; vc.log([r.contents, r.start, r.length, first.contents]);", + ); + // A range that ends where an edit starts keeps its end; one inside the edit takes the new text. + assert_eq!(out, vec![json!(["a", "b"]), json!(["XY", 0, 2, "XY"])]); +} + +#[test] +fn bad_attribute_values_are_refused_without_a_change() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + for (src, want) in [ + ("r.size = 0;", "size must be from 0.1"), + ("r.size = 'big';", "size must be a finite number"), + ("r.size = NaN;", "not a finite number"), + ("r.leading = 0;", "leading must be from 0.1"), + ("r.characterAttributes.tracking = 1e9;", "tracking"), + ("r.underline = 1;", "underline must be true or false"), + ("r.textFont = 'Arial';", "textFont must be a TextFont"), + ("r.paragraphAttributes.justification = 'LEFT';", "Justification value"), + ("r.paragraphAttributes.leftIndent = 5000;", "leftIndent"), + ("r.length = -1;", "length must be a whole number from 0 to 3"), + ("r.length = 1.5;", "length must be a whole number from 0 to 3"), + ("r.length = 4;", "length must be a whole number from 0 to 3"), + ("r.length = 'two';", "length must be a finite number"), + ] { + let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}")); + assert!(e.contains(want), "{src}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(sizes(&s, id), vec![("abc".into(), 12.0)]); +} + +#[test] +fn setting_the_value_a_range_has_records_no_undo_step() { + let (mut s, _) = doc_with("abc"); + let before = undo_steps(&s); + log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange; r.size = r.size; r.underline = false;\ + t.contents = t.contents; r.paragraphAttributes.leftIndent = 0; r.characters[0].characterAttributes.size = 12;", + ); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = r.leading; vc.log([r.autoLeading, r.leading]);"); + assert_eq!(out, vec![json!([false, 14.4])]); + assert_eq!(undo_steps(&s), before + 1); + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - 14.4).abs() < 1e-9)), "{:?}", t.runs), + _ => panic!("not text"), + } + // A fixed leading set to its own value is still no change. + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = 14.4; vc.log(r.autoLeading);"); + assert_eq!(out, vec![json!(false)]); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn paragraph_attributes_set_the_paragraphs_a_range_touches() { + let (mut s, _) = doc_with("first\nsecond"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], p = t.paragraphs;\ + vc.log([p.length, p[0].contents, p[1].contents]);\ + p[1].paragraphAttributes.justification = Justification.CENTER; p[1].paragraphAttributes.leftIndent = 9;\ + vc.log([p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].paragraphAttributes.leftIndent, p[1].paragraphAttributes.leftIndent, p[1].getParagraphLength()]);", + ); + assert_eq!(out[0], json!([2, "first\r", "second"])); + assert_eq!(out[1], json!(["Justification.LEFT", "Justification.CENTER"])); + assert_eq!(out[2], json!([0, 9, 6])); + // A paragraph whose range ends after its break sets only itself. + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; p[0].paragraphAttributes.justification = Justification.RIGHT;\ + p[0].paragraphAttributes.spaceAfter = 4;\ + vc.log([p[0].justification, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].paragraphAttributes.spaceAfter, p[1].paragraphAttributes.spaceAfter]);", + ); + assert_eq!(out, vec![json!(["Justification.RIGHT", "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]); + // The empty paragraph after a final break belongs only to an empty range at the end. + let (mut s, id) = doc_with("a\n"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], p = t.paragraphs; p[0].paragraphAttributes.spaceAfter = 4;\ + vc.log([p.length, p[0].paragraphs.length, p[0].paragraphAttributes.spaceAfter]);", + ); + assert_eq!(out, vec![json!([1, 1, 4])]); + let after: Vec = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (0..2).map(|i| t.para_at(i).space_after).collect(), + _ => panic!("not text"), + }; + assert_eq!(after, vec![4.0, 0.0]); +} + +#[test] +fn auto_leading_reads_the_paragraph_of_the_range_inside_one_run() { + let (mut s, id) = doc_with("first\nsecond"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 6, "end": 6, "autoLeading": 200})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; vc.log([p[0].leading, p[1].leading, p[1].characters[0].leading]);\ + p[1].autoLeading = false; vc.log([p[0].autoLeading, p[1].autoLeading, p[1].leading]);", + ); + assert_eq!(out, vec![json!([14.4, 24, 24]), json!([true, false, 24])]); + let leadings: Vec<(String, Option)> = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading)).collect(), + _ => panic!("not text"), + }; + assert_eq!(leadings, vec![("first\n".into(), None), ("second".into(), Some(24.0))]); +} + +#[test] +fn a_font_that_missing_glyph_protection_keeps_off_some_characters_throws() { + let (from, to, c) = ("Source Sans 3", "JetBrains Mono", '\u{180}'); + let db = vectorcraft_text::FontDb::global(); + let covers = |f: &str| db.face(f, "Regular").is_some_and(|face| face.covers(c)); + if !covers(from) || covers(to) { + return; // Installed fonts of these names cover other characters. + } + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "a\u{180}c", "font": from})).unwrap(); + let pick = format!("var r = app.activeDocument.textFrames[0].textRange, f = app.textFonts.getByName('{to} Regular');"); + let e = failure(&mut s, &format!("{pick} r.textFont = f;")); + assert!(e.contains("textFont: the font has no glyph for 1 character, which keeps its font"), "{e}"); + // Characters the font can draw take it without an error. + let out = log(&mut s, &format!("{pick} r.characters[0].textFont = f; vc.log(r.characters[0].textFont.family);")); + assert_eq!(out, vec![json!(to)]); +} + +#[test] +fn turning_auto_leading_off_keeps_each_characters_leading() { + let (mut s, id) = doc_with("ab\ncd"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 200})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "size": 24})).unwrap(); + let before = undo_steps(&s); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.autoLeading = false; vc.log(r.autoLeading);"); + assert_eq!(out, vec![json!(false)]); + assert_eq!(undo_steps(&s), before + 1); + let leadings: Vec<(String, Option)> = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading.map(|l| (l * 1000.0).round() as i64))).collect(), + _ => panic!("not text"), + }; + let want = [("a", 14_400), ("b", 28_800), ("\n", 14_400), ("cd", 24_000)]; + assert_eq!(leadings, want.iter().map(|(t, l)| (t.to_string(), Some(*l))).collect::>()); + // Paragraphs and runs with the same leading take one command. + let (mut s, _) = doc_with("one\ntwo\nthree"); + let r = run(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;").unwrap(); + let calls: Vec<(Value, Value)> = r["slowestCommands"].as_array().unwrap().iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect(); + assert_eq!(calls, vec![(json!("text.setRangeStyle"), json!(1))]); + // Auto leading that a fixed leading cannot hold is refused before anything changes. + let (mut s, id) = doc_with("ab\ncd"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 0})).unwrap(); + let before = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;"); + assert!(e.contains("autoLeading cannot be turned off"), "{e}"); + assert_eq!(undo_steps(&s), before); + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_none())), + _ => panic!("not text"), + } +} + +#[test] +fn an_explicit_alignment_replaces_auto_alignment() { + let justify = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.para_at(0).justify, + _ => panic!("not text"), + }; + for (text, reads) in [("abc", "Justification.LEFT"), ("\u{5e9}\u{5dc}\u{5d5}\u{5dd}", "Justification.RIGHT")] { + let (mut s, id) = doc_with(text); + assert_eq!(justify(&s, id), Justify::Auto); + let before = undo_steps(&s); + let out = log( + &mut s, + "var a = app.activeDocument.textFrames[0].textRange.paragraphAttributes; vc.log(a.justification);\ + a.justification = Justification.LEFT; vc.log(a.justification);", + ); + assert_eq!(out, vec![json!(reads), json!("Justification.LEFT")], "{text}"); + assert_eq!(justify(&s, id), Justify::Left, "{text}"); + assert_eq!(undo_steps(&s), before + 1, "{text}"); + } + // Each paragraph on Auto reads by its own text. + let (mut s, _) = doc_with("abc\n\u{5e9}\u{5dc}\u{5d5}\u{5dd}\nd"); + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; var j = function (i) { return p[i].paragraphAttributes.justification; }; vc.log([j(0), j(1), j(2)]);", + ); + assert_eq!(out, vec![json!(["Justification.LEFT", "Justification.RIGHT", "Justification.LEFT"])]); +} + +#[test] +fn a_stale_range_has_no_parent() { + let (mut s, id) = doc_with("abc"); + let source = format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'x'}}); r.parent;", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{e}"); +} + +#[test] +fn a_stale_range_and_its_collections_have_no_typename() { + let (mut s, id) = doc_with("abc"); + let source = format!( + "var r = app.activeDocument.textFrames[0].textRange, all = [r, r.characters, r.words, r.paragraphs, r.characterAttributes, r.paragraphAttributes];\ + var names = []; for (var i = 0; i < all.length; i++) names.push(all[i].typename); vc.log(names);\ + vc.run('text.setText', {{id: {}, text: 'other'}}); var m = [];\ + for (var i = 0; i < all.length; i++) {{ try {{ m.push(all[i].typename); }} catch (e) {{ m.push(e.message); }} }} vc.log(m);", + id.0 + ); + let out = log(&mut s, &source); + assert_eq!(out[0], json!(["TextRange", "Characters", "Words", "Paragraphs", "CharacterAttributes", "ParagraphAttributes"])); + assert_eq!(out[1], json!(vec!["Stale text range"; 6])); +} + +#[test] +fn members_not_built_yet_throw_after_the_stale_check() { + let (mut s, id) = doc_with("abc"); + let e = failure(&mut s, "app.activeDocument.textFrames[0].lines;"); + assert!(e.contains("TextFrame.lines is not available yet"), "{e}"); + let e = failure(&mut s, "var t = app.activeDocument.textFrames[0]; t.remove(); t.lines;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.lines;"); + assert!(e.contains("TextRange.lines is not available yet"), "{e}"); + for member in ["r.lines", "r.start = 1"] { + let source = + format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'other'}}); {member};", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{member}: {e}"); + } +} + +#[test] +fn text_fonts_list_and_assign_fonts_by_name() { + // The last font in the menu that draws "abc", so Missing Glyph Protection keeps no character. + let db = vectorcraft_text::FontDb::global(); + let listed: Vec<(String, String)> = db.menu_family_list().iter().flat_map(|f| db.styles(f).into_iter().map(move |st| (f.clone(), st))).collect(); + let covers = |(f, st): &&(String, String)| db.face(f, st).is_some_and(|face| "abc".chars().all(|c| face.covers(c))); + let Some((pos, (family, style))) = listed.iter().enumerate().rev().find(|(_, fs)| covers(fs)) else { + return; // No installed font draws "abc". + }; + let (mut s, id) = doc_with("abc"); + let out = log( + &mut s, + &format!( + "var f = app.textFonts, m = '';\ + try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\ + vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ + vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);" + ), + ); + assert_eq!(out, vec![json!("Not found"), json!("Not found"), json!(true), json!([family, style]), json!(true), json!(true), json!(true)]); + let set = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (t.runs[0].style.font_family.clone(), t.runs[0].style.font_style.clone()), + _ => panic!("not text"), + }; + assert_eq!(&set, &(family.clone(), style.clone())); +} + +#[test] +fn setting_a_ranges_length_moves_its_end_and_leaves_the_text() { + let (mut s, id) = doc_with("hello world"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange, w = t.words[1]; r.length = 2;\ + vc.log([r.length, r.contents, r.start, r.end, t.textRange.length]);\ + w.length = 3; vc.log([w.contents, w.start]); r.length = 0; vc.log([r.length, r.contents]);\ + t.characters[0].contents = 'J'; r.length = 5; vc.log(r.contents);", + ); + assert_eq!(out, vec![json!([2, "he", 0, 2, 11]), json!(["wor", 6]), json!([0, ""]), json!("Jello")]); + assert_eq!(plain(&s, id), "Jello world"); + assert_eq!(undo_steps(&s), before + 1); +} + +/// A length that ends inside a surrogate pair moves the range's end out to the end of the character. +#[test] +fn a_length_ending_inside_a_surrogate_pair_keeps_the_character_whole() { + let (mut s, _) = doc_with("a\u{1F600}b"); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.length = 2; vc.log([r.length, r.end, r.contents]);"); + assert_eq!(out, vec![json!([3, 3, "a\u{1F600}"])]); +} + +/// `textFrames.removeAll()` deletes nothing when type is on a locked artboard. +#[test] +fn remove_all_type_refuses_type_on_a_locked_artboard() { + let (mut s, id) = doc_with("kept"); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", id.0)), "{e}"); + assert!(s.active().unwrap().doc.node(id).is_some()); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn collections_of_text_add_words_characters_and_paragraphs() { + let cases = [ + ("t.words.add('x')", "hello world", "hello world x", "x"), + ("t.words.addBefore('x')", "hello world", "x hello world", "x"), + ("t.words[0].words.add('x')", "hello world", "hello x world", "x"), + ("t.words.add('x', t.words[0], ElementPlacement.PLACEBEFORE)", "hello world", "x hello world", "x"), + ("t.words.add('x', t.words[1], ElementPlacement.PLACEATBEGINNING)", "hello world", "hello x world", "x"), + ("t.words.add('x', t, ElementPlacement.PLACEATEND)", "hello world", "hello world x", "x"), + ("t.words.add('x')", "hello world ", "hello world x ", "x"), + ("t.words.add('x')", "", "x", "x"), + ("t.words.add(7)", "a", "a 7", "7"), + ("t.characters.add('!')", "hi", "hi!", "!"), + ("t.characters[0].characters.add('x')", "hi", "hxi", "x"), + ("t.paragraphs.add('end')", "one\ntwo", "one\ntwo\nend", "end"), + ("t.paragraphs[0].paragraphs.add('mid')", "one\ntwo", "one\nmid\ntwo", "mid"), + ("t.paragraphs.addBefore('top')", "one", "top\none", "top"), + ]; + for (call, text, after, added) in cases { + let (mut s, id) = doc_with(text); + let before = undo_steps(&s); + let out = log(&mut s, &format!("var t = app.activeDocument.textFrames[0], n = {call}; vc.log([n.typename, n.contents]);")); + assert_eq!(out, vec![json!(["TextRange", added])], "{call} on {text:?}"); + assert_eq!(plain(&s, id), after, "{call} on {text:?}"); + assert_eq!(undo_steps(&s), before + 1, "{call} on {text:?}"); + } + // Empty contents add nothing; bad arguments throw before anything changes. + let (mut s, id) = doc_with("ab"); + s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); + let before = undo_steps(&s); + // `textFrames` lists the topmost first, so the newer "other" is [0]. + let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); + assert_eq!(out, vec![json!([0, 5])]); + for (call, want) in [ + ("t.words.add(null)", "contents must be a string or a number"), + ("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"), + ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), + ("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"), + ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), + ] { + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};")); + assert!(e.contains(want), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(plain(&s, id), "ab"); +} + +#[test] +fn text_fonts_find_a_bundled_face_by_its_postscript_name() { + let Some(face) = vectorcraft_text::FontDb::global().loaded_faces().into_iter().find(|f| f.family == "Source Sans 3") else { + return; // Built without the bundled fonts. + }; + let ps = face.postscript_name(); + let (mut s, _) = doc_with("abc"); + let out = log(&mut s, &format!("var f = app.textFonts.getByName('{ps}'); vc.log([f.family, f.style, f.name]);")); + assert_eq!(out, vec![json!([face.family, face.style, ps])]); +} + +#[test] +fn a_text_range_sets_the_paragraph_attributes_of_the_paragraphs_it_touches() { + let (mut s, id) = doc_with("first\nsecond\nthird"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange; r.justification = Justification.CENTER;\ + vc.log([r.justification, t.paragraphs[2].paragraphAttributes.justification]);\ + t.characters[7].leftIndent = 9; vc.log([t.paragraphs[0].leftIndent, t.paragraphs[1].leftIndent, t.paragraphs[2].leftIndent]);", + ); + assert_eq!(out, vec![json!(["Justification.CENTER", "Justification.CENTER"]), json!([0, 9, 0])]); + let justify: Vec = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (0..3).map(|i| t.para_at(i).justify).collect(), + _ => panic!("not text"), + }; + assert_eq!(justify, vec![Justify::Center; 3]); + assert_eq!(undo_steps(&s), before + 1); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.justification = 'CENTER';"); + assert!(e.contains("Justification value"), "{e}"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn create_outline_and_conversions_return_the_new_objects() { + let (mut s, id) = doc_with("Hi"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], m = '';\ + try { t.convertAreaObjectToPointObject(); } catch (e) { m = e.message; } vc.log(m);\ + var a = t.convertPointObjectToAreaObject(); vc.log(a.kind);\ + var p = a.convertAreaObjectToPointObject(); vc.log(p.kind); vc.log(p.contents);\ + var g = p.createOutline(); vc.log(g.typename); vc.log(app.activeDocument.textFrames.length);", + ); + assert_eq!(out[0], json!("the text frame is not area type")); + assert_eq!(out[1..], [json!("TextType.AREATEXT"), json!("TextType.POINTTEXT"), json!("Hi"), json!("GroupItem"), json!(0)]); + assert!(s.active().unwrap().doc.node(id).is_none()); +} + +#[test] +fn outlining_type_with_nothing_to_outline_gives_null() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = + log(&mut s, "var d = app.activeDocument, t = d.textFrames.add(); var g = t.createOutline(); vc.log([g === null, d.textFrames.length]);"); + assert_eq!(out, vec![json!([true, 0])]); +} + +#[test] +fn type_made_with_a_large_id_is_the_new_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The second frame's id, 2^53 + 1, is not exact as a number. + let big = 1u64 << 53; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log( + &mut s, + "var d = app.activeDocument, a = d.textFrames.add(), b = d.textFrames.pointText([5, 5]); b.contents = 'second';\ + vc.log([a === b, a.contents, b.createOutline().typename]);", + ); + assert_eq!(out, vec![json!([false, "", "GroupItem"])]); + assert_eq!(plain(&s, NodeId(big)), ""); +} + +#[test] +fn text_members_refuse_objects_of_other_classes() { + let (mut s, _) = doc_with("abc"); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);"); + assert!(e.contains("this is not a TextFrame"), "{e}"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); + assert!(e.contains("this is not a TextRange"), "{e}"); + let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['TextFont', 0, 0]; app.activeDocument.textFrames[0].textRange.textFont = f;"); + assert!(e.contains("not plain data"), "{e}"); + // A font from an earlier run of a named engine is stale. + run(&mut s, "#targetengine keepfont\nvar held = app.textFonts[0];").unwrap(); + for member in ["held.family", "held.parent"] { + let e = failure(&mut s, &format!("#targetengine keepfont\n{member};")); + assert!(e.contains("Stale text font"), "{member}: {e}"); + } +} diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs new file mode 100644 index 0000000000..81987f52d9 --- /dev/null +++ b/crates/engine/src/tests/script_threads.rs @@ -0,0 +1,639 @@ +//! Threaded type in the script object model: `nextFrame`, `previousFrame`, `story`, +//! `document.stories`, and the text of a story of several frames. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn new_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +/// Area type `width` × `height` at `x` holding `text`. +fn area(s: &mut Session, x: f64, width: f64, height: f64, text: &str) -> NodeId { + let r = s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "size": 12, "area": {"width": width, "height": height}})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn plain(s: &Session, id: NodeId) -> String { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } +} + +fn threads(s: &Session) -> Vec> { + s.active().unwrap().doc.text_threads.clone() +} + +/// The text of every frame of the document's threads, in thread order. +fn story(s: &Session, frames: &[NodeId]) -> String { + frames.iter().map(|f| plain(s, *f)).collect() +} + +/// Two area frames threaded into one story whose text starts in the first, one line high, and +/// flows on into the second. +fn threaded(text: &str) -> (Session, NodeId, NodeId) { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 90.0, 18.0, text); + let b = area(&mut s, 150.0, 200.0, 200.0, ""); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(threads(&s), vec![vec![a, b]]); + (s, a, b) +} + +const STORY: &str = "alpha beta gamma\ndelta \u{1F600}"; + +#[test] +fn stories_list_one_story_for_each_thread_and_each_frame_in_none() { + let (mut s, _, _) = threaded(STORY); + area(&mut s, 400.0, 120.0, 40.0, "Alone"); + let out = log( + &mut s, + "var d = app.activeDocument, st = d.stories[1];\ + vc.log(d.stories.length); vc.log(st.typename); vc.log(st.textFrames.length);\ + vc.log(st.textFrames[0].nextFrame.previousFrame.contents === st.textFrames[0].contents);\ + vc.log(st.textFrames[1].nextFrame === null && st.textFrames[0].previousFrame === null);\ + vc.log(d.stories[0].textFrames[0].contents); vc.log(d.stories[0].textFrames.length);\ + d.textFrames.add(); vc.log(d.stories.length);\ + vc.log(d.stories.parent.typename); vc.log(st.parent.typename); vc.log(d.stories.typename);\ + vc.log(d.textFrames[1].story.textFrames[0].contents);", + ); + assert_eq!( + out, + vec![ + json!(2), + json!("Story"), + json!(2), + json!(true), + json!(true), + json!("Alone"), + json!(1), + json!(3), + json!("Document"), + json!("Document"), + json!("Stories"), + json!("Alone") + ] + ); +} + +#[test] +fn a_story_range_counts_utf16_units_across_its_frames() { + let (mut s, a, b) = threaded(STORY); + let (first, second) = (plain(&s, a), plain(&s, b)); + assert!(!first.is_empty() && !second.is_empty(), "the story flows through both frames: {first:?} {second:?}"); + assert_eq!(first.clone() + &second, STORY); + let out = log( + &mut s, + "var st = app.activeDocument.textFrames[0].story, r = st.textRange;\ + vc.log(st.length); vc.log(r.length); vc.log(r.contents); vc.log(r.typename);\ + vc.log(st.characters.length); vc.log(st.words.length); vc.log(st.paragraphs.length);\ + vc.log(st.paragraphs[0].contents); vc.log(st.words[4].contents); vc.log(st.words[4].start);\ + vc.log(r.paragraphs[1].getParagraphLength()); vc.log(r.story.length);\ + vc.log(app.activeDocument.textFrames[0].textRange.length < r.length);", + ); + assert_eq!( + out, + vec![ + json!(25), + json!(25), + json!("alpha beta gamma\rdelta \u{1F600}"), + json!("TextRange"), + json!(24), + json!(5), + json!(2), + json!("alpha beta gamma\r"), + json!("\u{1F600}"), + json!(23), + json!(8), + json!(25), + json!(true) + ] + ); +} + +/// The members a long story's range does not have yet throw that they are not available, and +/// first that a range that went stale is stale. +#[test] +fn a_story_range_names_the_members_it_does_not_have_yet() { + let (mut s, _, b) = threaded(STORY); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].story.textRange;\ + try { r.characterAttributes; } catch (e) { vc.log(String(e.message)); }\ + try { r.size = 20; } catch (e) { vc.log(String(e.message)); }\ + try { app.activeDocument.textFrames[0].story.lines; } catch (e) { vc.log(String(e.message)); }", + ); + assert_eq!( + out, + vec![ + json!("TextRange.characterAttributes is not available yet"), + json!("TextRange.size is not available yet"), + json!("Story.lines is not available yet") + ] + ); + let message = failure( + &mut s, + &format!( + "var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.characterAttributes;", + b.0 + ), + ); + assert!(message.contains("Stale text range"), "{message}"); + let message = failure( + &mut s, + &format!( + "var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.typename;", + b.0 + ), + ); + assert!(message.contains("Stale text range"), "{message}"); +} + +/// Ranges of one story read from different frames keep their places through each other's edits. +#[test] +fn story_ranges_read_from_different_frames_follow_each_others_edits() { + let (mut s, _, _) = threaded(STORY); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames, x = t[0].story.words[0], y = t[1].story.words[1];\ + x.contents = 'Q'; vc.log(y.contents); vc.log(y.start); y.contents = 'B'; vc.log(x.contents);\ + vc.log(t[1].story.textRange.contents);", + ); + assert_eq!(out, vec![json!("beta"), json!(2), json!("Q"), json!("Q B gamma\rdelta \u{1F600}")]); +} + +/// A story range that an edit covers holds the edit's new text, as a frame's range does. +#[test] +fn a_story_range_an_edit_covers_holds_the_new_text() { + let (mut s, _, _) = threaded(STORY); + let out = log( + &mut s, + "var st = app.activeDocument.textFrames[0].story, w = st.words[1], p = st.paragraphs[1];\ + st.textRange.contents = 'Z'; vc.log(w.contents); vc.log(p.contents); vc.log(w.typename); vc.log(st.words.typename);", + ); + assert_eq!(out, vec![json!("Z"), json!("Z"), json!("TextRange"), json!("Words")]); +} + +#[test] +fn a_story_edit_across_frames_reflows_in_one_undo_step() { + let (mut s, a, b) = threaded(STORY); + let before = undo_steps(&s); + let out = log( + &mut s, + "var st = app.activeDocument.textFrames[0].story, frame = app.activeDocument.textFrames[1].textRange;\ + var p = st.paragraphs[0], tail = st.paragraphs[1];\ + p.contents = 'X\\r'; vc.log(st.textRange.contents); vc.log(tail.contents); vc.log(tail.start);\ + try { frame.contents; } catch (e) { vc.log(String(e.message)); }\ + st.words[2].remove(); vc.log(st.textRange.contents);", + ); + assert_eq!(out, vec![json!("X\rdelta \u{1F600}"), json!("delta \u{1F600}"), json!(2), json!("Stale text range"), json!("X\rdelta ")]); + assert_eq!(story(&s, &[a, b]), "X\ndelta "); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(story(&s, &[a, b]), STORY); +} + +#[test] +fn a_story_range_is_stale_after_another_change_to_the_story() { + let (mut s, _, b) = threaded(STORY); + let message = failure( + &mut s, + &format!( + "var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.contents;", + b.0 + ), + ); + assert!(message.contains("Stale text range"), "{message}"); +} + +#[test] +fn a_story_range_made_before_file_revert_is_stale_even_when_the_text_is_the_same() { + let (mut s, _, _) = threaded(STORY); + let path = std::env::temp_dir().join(format!("vc-story-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].story.words[1];\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + var st = app.activeDocument.textFrames[0].story;\ + vc.log(st.textFrames.length); vc.log(st.textRange.contents);\ + try { vc.log(r.contents); } catch (e) { vc.log(String(e.message)); }\ + vc.log(st.words[1].contents);", + ); + let _ = std::fs::remove_file(&path); + assert_eq!(out[0], json!(2), "the reverted file keeps the thread"); + assert_eq!(out[1], json!("alpha beta gamma\rdelta \u{1F600}"), "the reverted file holds the same text"); + assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert_eq!(out[3], json!("beta"), "a range made after the revert reads the reverted text"); +} + +#[test] +fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "First story."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Second."); + let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [p.0]})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];\ + vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[2].story.textRange.contents);\ + t[2].nextFrame = t[1];", + ); + assert_eq!(out, vec![json!(2), json!("First story.Second."), json!("First story.Second.")]); + assert_eq!(threads(&s), vec![vec![a, b]]); + assert_eq!(story(&s, &[a, b]), "First story.Second."); + assert_eq!(undo_steps(&s), before + 1); + assert_eq!(s.active().unwrap().selection.objects.to_vec(), vec![p]); + // previousFrame links the other way. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(threads(&s).is_empty()); + assert_eq!((plain(&s, a), plain(&s, b)), ("First story.".into(), "Second.".into())); + log(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[1];"); + assert_eq!(threads(&s), vec![vec![b, a]]); + assert_eq!(story(&s, &[b, a]), "Second.First story."); +} + +#[test] +fn null_breaks_the_link_and_each_frame_keeps_its_text() { + let (mut s, a, b) = threaded(STORY); + let (first, second) = (plain(&s, a), plain(&s, b)); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames, st = t[0].story; t[0].previousFrame = null;\ + vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[1].nextFrame);\ + t[1].nextFrame = null;", + ); + assert_eq!(out, vec![json!(2), json!(1), json!(null)]); + assert!(threads(&s).is_empty()); + assert_eq!((plain(&s, a), plain(&s, b)), (first, second)); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(threads(&s), vec![vec![a, b]]); +} + +#[test] +fn area_and_path_text_thread_the_new_frame_to_a_base_frame() { + let mut s = new_doc(); + let base = area(&mut s, 10.0, 120.0, 40.0, "Base text that is long enough to flow on into the frames made after it."); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 350, "y": 10, "width": 120, "height": 60})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 300}, {"x": 400, "y": 320}], "closed": false})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, base = d.textFrames[0];\ + var after = d.textFrames.areaText(p[2], undefined, base);\ + var first = d.textFrames.areaText(p[1], TextOrientation.HORIZONTAL, base, false);\ + var last = d.textFrames.pathText(p[0], undefined, undefined, undefined, after, true);\ + vc.log(base.story.textFrames.length); vc.log(base.previousFrame.kind); vc.log(after.nextFrame.kind); vc.log(d.stories.length);", + ); + assert_eq!(out, vec![json!(4), json!("TextType.AREATEXT"), json!("TextType.PATHTEXT"), json!(1)]); + let t = threads(&s); + assert_eq!(t.len(), 1); + assert_eq!(t[0][1], base, "the frame made with postFix false comes before the base frame: {t:?}"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn a_bad_base_frame_is_refused_before_a_frame_is_made() { + let mut s = new_doc(); + s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap(); + let count = |s: &Session| s.active().unwrap().doc.node_count(); + let (n, before) = (count(&s), undo_steps(&s)); + let d = "var d = app.activeDocument, p = d.pageItems;"; + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0]);")).contains("only area type")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, p[0]);")).contains("baseFrame must be a TextFrame")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0], 'yes');")).contains("postFix")); + assert_eq!((count(&s), undo_steps(&s)), (n, before)); +} + +/// A base frame given with a path inside a compound path is refused before the path is turned +/// into type, so a script that catches the error finds the path as it was. +#[test] +fn a_base_frame_for_a_path_in_a_compound_path_leaves_the_path() { + let mut s = new_doc(); + area(&mut s, 10.0, 120.0, 60.0, "Base."); + let r1 = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap(); + let r2 = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [r1, r2]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, p = null;\ + for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') { p = d.pageItems[i]; break; } }\ + try { d.textFrames.areaText(p, undefined, d.textFrames[0]); } catch (e) { vc.log(String(e.message)); }\ + vc.log(p.typename); vc.log(d.textFrames.length);", + ); + assert_eq!(out, vec![json!("baseFrame: type made from a path inside a compound path cannot be threaded"), json!("PathItem"), json!(1)]); + assert_eq!(undo_steps(&s), before); +} + +/// A thread of `a` and `b`, a third area frame `c`, and point type `p`; what the document holds +/// now, to check that a refused change left it alone. +fn three() -> (Session, [NodeId; 4]) { + let (mut s, a, b) = threaded(STORY); + let c = area(&mut s, 400.0, 120.0, 40.0, "Third"); + let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap()); + (s, [a, b, c, p]) +} + +fn unchanged(s: &Session, ids: &[NodeId], before: &(Vec>, Vec, usize)) { + assert_eq!((threads(s), ids.iter().map(|i| plain(s, *i)).collect::>(), undo_steps(s)), *before); +} + +fn state(s: &Session, ids: &[NodeId]) -> (Vec>, Vec, usize) { + (threads(s), ids.iter().map(|i| plain(s, *i)).collect(), undo_steps(s)) +} + +#[test] +fn a_link_to_the_frame_itself_is_refused() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[2];"); + assert!(m.contains("nextFrame") && m.contains("itself"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_link_that_makes_a_loop_is_refused() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];"); + assert!(m.contains("loop"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];"); + assert!(m.contains("loop"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_link_into_the_middle_of_a_story_is_refused() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];"); + assert!(m.contains("already has a previous frame"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].previousFrame = t[3];"); + assert!(m.contains("already has a next frame"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn point_type_and_other_values_cannot_be_linked() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];"); + assert!(m.contains("only area type"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); + assert!(m.contains("only area type"), "{m}"); + let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = 5;"); + assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}"); + let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = undefined;"); + assert!(m.contains("TextFrame or null"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_hidden_or_locked_frame_in_either_story_stops_a_link() { + let (mut s, ids) = three(); + log(&mut s, "app.activeDocument.textFrames[2].locked = true;"); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];"); + assert!(m.contains("hidden or locked"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].nextFrame = null;"); + assert!(m.contains("hidden or locked"), "{m}"); + // A script that catches the error goes on, and the links stay as they were. + let out = log( + &mut s, + "var t = app.activeDocument.textFrames; try { t[2].nextFrame = t[1]; } catch (e) { vc.log([e.name, /hidden or locked/.test(e.message)]); }\ + vc.log(t[2].nextFrame === null);", + ); + assert_eq!(out, vec![json!(["Error", true]), json!(true)]); + unchanged(&s, &ids, &before); +} + +/// Reading a story whose text is larger than what one run may pass to and from the host stops +/// the run when the story's text is joined. +#[test] +fn joining_a_storys_text_counts_toward_the_runs_data_limit() { + let text = "word ".repeat(40_000); + let (mut s, _, _) = threaded(&text); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(100_000))); + let r = run(&mut s, "vc.log(app.activeDocument.stories[0].length);"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = r.map(|r| panic!("the run read a 200 KB story within a 100 KB limit: {r}")).unwrap_err().to_string(); + assert!(e.contains("more data to and from commands"), "{e}"); +} + +#[test] +fn a_frame_of_another_document_cannot_be_linked() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + area(&mut s, 10.0, 100.0, 40.0, "Elsewhere"); + s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 80, "height": 60})).unwrap(); + let m = failure(&mut s, "app.documents[1].textFrames[1].nextFrame = app.documents[0].textFrames[0];"); + assert!(m.contains("different documents"), "{m}"); + let out = log( + &mut s, + "var d = app.documents[0], p = d.pageItems[0];\ + try { d.textFrames.areaText(p, undefined, app.documents[1].textFrames[1]); } catch (e) { vc.log(String(e.message)); }\ + vc.log(p.typename); vc.log(d.textFrames.length);", + ); + assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_deleted_frame_makes_its_story_and_links_stale() { + let (mut s, _, _) = threaded(STORY); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.length;"); + assert!(m.contains("Stale story"), "{m}"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.lines;"); + assert!(m.contains("Stale story"), "{m}"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], g = app.activeDocument.textFrames[0]; g.remove(); f.nextFrame = g;"); + assert!(m.contains("Stale page item"), "{m}"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], r = f.story.textRange; f.remove(); r.contents;"); + assert!(m.contains("Stale text range"), "{m}"); + // A story read from a frame that stays follows it when its link is broken. + let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[0].story; t[1].nextFrame = null; vc.log(st.textFrames.length);"); + assert_eq!(out, vec![json!(1)]); +} + +#[test] +fn stories_refuse_bad_keys_and_huge_numbers() { + let (mut s, _, _) = threaded(STORY); + let out = log( + &mut s, + "var st = app.activeDocument.stories; vc.log(st[1e300] === undefined); vc.log(st[-1] === undefined); vc.log(st[0.5] === undefined);", + ); + assert_eq!(out, vec![json!(true), json!(true), json!(true)]); + assert!(failure(&mut s, "app.activeDocument.stories.index(1e20);").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.stories.index('nobody');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.stories.index({});").contains("TypeError")); + log(&mut s, "app.activeDocument.textFrames[1].name = 'Lead';"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.stories.index('Lead').textFrames.length);"), vec![json!(2)]); +} + +#[test] +fn a_long_story_walks_to_its_end_and_refuses_a_loop() { + let mut s = new_doc(); + let ids: Vec = (0..120).map(|i| area(&mut s, f64::from(i % 12) * 45.0, 40.0, 20.0, if i == 0 { STORY } else { "" })).collect(); + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(threads(&s), vec![ids.clone()]); + let out = log( + &mut s, + "var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame) { f = f.nextFrame; n++; } \ + vc.log(n); vc.log(f.story.textFrames.length); vc.log(d.stories.length);", + ); + assert_eq!(out, vec![json!(120), json!(120), json!(1)]); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[t.length - 1].nextFrame = t[0];"); + assert!(m.contains("loop"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[0].previousFrame = t[t.length - 1];"); + assert!(m.contains("loop"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[60].nextFrame = t[30];"); + assert!(m.contains("loop"), "{m}"); + unchanged(&s, &ids, &before); +} + +/// A stored thread that lists a frame twice, as a file can, is a story that visits each frame +/// once, so a walk along `nextFrame` ends. +#[test] +fn a_thread_listing_a_frame_twice_is_walked_once() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b, a]]; + let out = log( + &mut s, + "var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame && n < 10) { f = f.nextFrame; n++; } \ + vc.log(n); vc.log(d.stories[0].textFrames.length); vc.log(d.stories.length);", + ); + assert_eq!(out, vec![json!(2), json!(2), json!(1)]); + let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": null})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]})); + assert!(threads(&s).is_empty()); +} + +/// When a frame is listed in two threads, a story read from a frame of the second thread reads +/// that thread's text, not the text of the story read before it from a shared frame. +#[test] +fn stories_of_threads_that_share_a_frame_keep_their_own_text() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + let c = area(&mut s, 300.0, 120.0, 60.0, "Three!"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b], vec![b, c]]; + let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[0].story.length);"); + let (ab, bc) = (story(&s, &[a, b]).encode_utf16().count(), story(&s, &[b, c]).encode_utf16().count()); + assert_ne!(ab, bc); + assert_eq!(out, vec![json!(ab), json!(bc)]); +} + +/// A story and its range keep the exact id of the frame they were read from, also past 2^53. +#[test] +fn a_story_read_from_a_frame_with_a_large_id_stays_with_that_frame() { + let mut s = new_doc(); + // The second frame's id, 2^53 + 1, is not exact as a number. + let big = 1u64 << 53; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + assert_eq!((a.0, b.0), (big, big + 1)); + s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap(); + let out = log( + &mut s, + "var st = app.activeDocument.stories[0].textFrames[1].story, r = st.textRange; vc.log(r.contents);\ + st.textFrames[0].nextFrame = null; vc.log(st.textFrames.length); vc.log(st.textFrames[0].contents); vc.log(st.typename);", + ); + // The whole story flows into the first frame, so the second is empty once the link is broken. + assert_eq!(out, vec![json!("One.Two."), json!(1), json!(""), json!("Story")]); +} + +#[test] +fn set_neighbor_links_and_breaks_frames_by_id_without_a_selection() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + s.execute("select.none", &json!({})).unwrap(); + let before = undo_steps(&s); + let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[a.0, b.0]]})); + let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": a.0})).unwrap(); + assert_eq!(r["changed"], json!(false)); + assert_eq!(undo_steps(&s), before + 1); + assert!(s.active().unwrap().selection.objects.is_empty()); + let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]})); + let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap(); + assert_eq!(r["changed"], json!(false)); + assert_eq!(undo_steps(&s), before + 2); + for bad in [ + json!({"id": a.0, "side": "up", "neighbor": b.0}), + json!({"id": a.0, "side": "next"}), + json!({"id": a.0, "side": "next", "neighbor": 999_999}), + ] { + assert!(s.execute("text.thread.setNeighbor", &bad).is_err(), "{bad}"); + } + assert_eq!(undo_steps(&s), before + 2); +} + +/// Breaking a link where a paragraph starts makes the frames after it a story whose numbered +/// paragraphs count from 1, also when that story keeps two frames. +#[test] +fn a_break_at_a_paragraph_start_numbers_the_later_story_from_one() { + let mut s = new_doc(); + let items = (1..=12).map(|i| format!("Item {i}")).collect::>().join("\n"); + let ids = [area(&mut s, 10.0, 150.0, 60.0, &items), area(&mut s, 200.0, 150.0, 60.0, ""), area(&mut s, 400.0, 150.0, 200.0, "")]; + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "list": "number"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let numbers = |s: &Session, id: NodeId| { + let Some(NodeKind::Text(t)) = s.active().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("text") }; + assert!(!t.first_para_continues, "every frame starts a paragraph"); + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::>() + }; + let first = numbers(&s, ids[0]); + assert!(!first.is_empty() && !numbers(&s, ids[1]).is_empty(), "the first two frames hold items"); + assert_ne!(numbers(&s, ids[1]).first().map(String::as_str), Some("1.")); + let r = s.execute("text.thread.setNeighbor", &json!({"id": ids[0].0, "side": "next", "neighbor": null})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[ids[0].0], [ids[1].0, ids[2].0]]})); + let later = [numbers(&s, ids[1]), numbers(&s, ids[2])].concat(); + let expected: Vec = (1..=later.len()).map(|n| format!("{n}.")).collect(); + assert_eq!(later, expected, "the later story counts from 1"); + assert_eq!(numbers(&s, ids[0]), first); +} diff --git a/crates/engine/src/tests/strokegeom.rs b/crates/engine/src/tests/strokegeom.rs index 524dabef3e..af3eb52936 100644 --- a/crates/engine/src/tests/strokegeom.rs +++ b/crates/engine/src/tests/strokegeom.rs @@ -2,7 +2,7 @@ //! the width-profile presets. use serde_json::json; -use vectorcraft_doc::{ArrowAlign, StrokeLayer, WidthProfile}; +use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer, WidthProfile}; use crate::*; @@ -58,6 +58,19 @@ fn profiles_come_from_the_preset_catalogue() { } } +#[test] +fn the_notched_arrow_survives_the_native_format() { + let (mut s, id) = session_with_line(); + s.execute("stroke.set", &json!({"startArrow": "NotchedArrow", "endArrow": "NotchedArrow"})).unwrap(); + let st = stroke(&s, id); + assert_eq!((st.start_arrow, st.end_arrow), (Some(Arrowhead::NotchedArrow), Some(Arrowhead::NotchedArrow))); + let doc = &s.doc().unwrap().doc; + let text = String::from_utf8(vectorcraft_format::save(doc, true)).unwrap(); + assert_eq!(text.matches("\"NotchedArrow\"").count(), 2, "saved by name"); + let back = vectorcraft_format::load(text.as_bytes()).unwrap(); + assert_eq!(back.node(id).unwrap().appearance.stroke().unwrap(), &stroke(&s, id)); +} + #[test] fn arrow_align_and_profiles_survive_the_native_format() { let (mut s, id) = session_with_line(); diff --git a/crates/engine/src/tests/symbolbounds.rs b/crates/engine/src/tests/symbolbounds.rs index 50adeededb..a6abff8193 100644 --- a/crates/engine/src/tests/symbolbounds.rs +++ b/crates/engine/src/tests/symbolbounds.rs @@ -185,8 +185,9 @@ fn set_bounds_measures_the_objects_in_an_instances_art_one_by_one() { // A symbol whose art is a group of a rectangle from x 0 to 10 with a 2 pt stroke and one from // x 3 to 10 with a 10 pt stroke, both 50 pt high, and an instance of it 100 pt down, in a group // when `grouped`, selected with an unstroked rectangle from x 100 to 110 when `plain`. The - // instance's visual box runs from (-2, 95) to (15, 155). With `own`, the art's group and the - // instance each have a 1 pt stroke of their own, which reaches 5 pt at its miter limit of 10. + // instance's visual box runs from (-2, 95) to (15, 155). With `own`, the art's group has a 20 pt + // miter-joined stroke of its own, which paints 10 pt past each rectangle's corners, and the + // instance a 1 pt stroke, which grows its box by the 5 pt it can reach at its miter limit of 10. let selection = |grouped: bool, plain: bool, own: bool| { let mut d = Document::new(400.0, 400.0); let stroked = |d: &mut Document, x0: f64, weight: f64| { @@ -199,7 +200,7 @@ fn set_bounds_measures_the_objects_in_an_instances_art_one_by_one() { let mut art = Node::group(d.alloc_id(), vec![Arc::new(stroked(&mut d, 0.0, 2.0)), Arc::new(stroked(&mut d, 3.0, 10.0))]); let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mixed".into(), xf: Affine::translate((0.0, 100.0)) }); if own { - *art.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + *art.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 20.0); *instance.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); } d.symbols.push(Symbol { dynamic: false, name: "Mixed".into(), art: Arc::new(art) }); @@ -221,8 +222,8 @@ fn set_bounds_measures_the_objects_in_an_instances_art_one_by_one() { // With the unstroked rectangle, the visual box runs from (-2, 95) to (110, 155). Set to 224 wide // from its left edge, it is 224 wide and its left edge stays at -2, with strokes kept or // scaling, and with the instance in a group. The instance alone set to 37 wide is 37 wide. With - // the strokes of their own, which paint around each rectangle, the visual box runs from - // (-12, 85) to (110, 165): set to 224 wide, it is 224 wide and its left edge stays at -12. + // the strokes of their own, the visual box runs from (-15, 85) to (110, 165): set to 224 wide, + // it is 224 wide and its left edge stays at -15. let mut wrong = vec![]; for (grouped, plain, own, width, strokes) in [ (false, true, false, 224.0, false), @@ -233,7 +234,7 @@ fn set_bounds_measures_the_objects_in_an_instances_art_one_by_one() { (false, true, true, 224.0, true), ] { let (mut s, ids) = selection(grouped, plain, own); - let (left, top, bottom) = if own { (-12.0, 85.0, 165.0) } else { (-2.0, 95.0, 155.0) }; + let (left, top, bottom) = if own { (-15.0, 85.0, 165.0) } else { (-2.0, 95.0, 155.0) }; let before = s.transform_bounds(&ids); if !close(before, Rect::new(left, top, if plain { 110.0 } else { 15.0 }, bottom)) { wrong.push(format!("grouped {grouped}, plain {plain}, own {own}, before: {before:?}")); diff --git a/crates/engine/src/tests/three_point_arc.rs b/crates/engine/src/tests/three_point_arc.rs index ebd755dda7..fb34e0da6e 100644 --- a/crates/engine/src/tests/three_point_arc.rs +++ b/crates/engine/src/tests/three_point_arc.rs @@ -217,4 +217,178 @@ fn set_option_sets_the_direction_and_refuses_bad_values() { assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}"); } assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false)); + // `join` starts off and `tangentSnap` on; both take only true or false. + assert_eq!( + (s.tool_options_of("threePointArc")["join"].clone(), s.tool_options_of("threePointArc")["tangentSnap"].clone()), + (json!(false), json!(true)) + ); + let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"join": true, "tangentSnap": false}})).unwrap(); + assert_eq!((set["join"].clone(), set["tangentSnap"].clone()), (json!(true), json!(false))); + for key in ["join", "tangentSnap"] { + let e = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "key": key, "value": 1})).unwrap_err(); + assert_eq!(e, format!("tool `threePointArc`: `{key}` must be true or false")); + } +} + +/// An open path drawn from SVG path data, selected. +fn open_path(s: &mut Session, d: &str) -> NodeId { + id_of(&s.execute("path.create", &json!({ "d": d })).unwrap()) +} + +/// The anchors of the first subpath of `id`, and whether it is closed. +fn anchors(s: &Session, id: NodeId) -> (Vec, bool) { + let n = node(s, id); + let sp = &n.path_data().unwrap().subpaths[0]; + (sp.anchors.iter().map(|a| a.p).collect(), sp.closed) +} + +/// With `join`, an arc starting on the last anchor of an open path is added to that path: the path +/// keeps its id and direction and now ends where the arc ends, the anchor where they meet is not +/// doubled, and it is one undo step. An arc ending on a path's first anchor is added before it. +#[test] +fn join_adds_the_arc_to_the_open_path_it_starts_on() { + let mut s = session(); + let id = open_path(&mut s, "M0 100 L100 100"); + let (undo, count) = (undo_len(&s), object_count(&s)); + let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap(); + assert_eq!((id_of(&out), out["joined"].clone(), out["radius"].as_f64()), (id, json!(true), Some(40.0)), "{out}"); + assert_eq!((undo_len(&s), object_count(&s)), (undo + 1, count)); + let (pts, closed) = anchors(&s, id); + assert!(!closed); + assert_eq!((pts.first().copied(), pts.last().copied()), (Some(Point::new(0.0, 100.0)), Some(Point::new(180.0, 100.0))), "{pts:?}"); + assert_eq!(pts.iter().filter(|p| **p == Point::new(100.0, 100.0)).count(), 1, "{pts:?}"); + assert!(farthest_from_path(&s, id, &[Point::new(140.0, 60.0), Point::new(50.0, 100.0)]) < 1e-9); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(anchors(&s, id).0, [Point::new(0.0, 100.0), Point::new(100.0, 100.0)]); + // The arc ends on the first anchor of a path running right: the path still runs right, from + // the arc's start. + let id = open_path(&mut s, "M300 100 L400 100"); + let out = s.execute(C, &json!({"start": [220, 100], "end": [300, 100], "toward": [220, 60], "join": true})).unwrap(); + assert_eq!(id_of(&out), id); + let (pts, _) = anchors(&s, id); + assert_eq!((pts.first().copied(), pts.last().copied()), (Some(Point::new(220.0, 100.0)), Some(Point::new(400.0, 100.0))), "{pts:?}"); + assert!(farthest_from_path(&s, id, &[Point::new(260.0, 60.0)]) < 1e-9); +} + +/// With both ends on ends of two open paths, the arc joins them into one path in one undo step; +/// with both ends on the two ends of one open path, the path closes. +#[test] +fn join_with_both_ends_on_open_paths_makes_one_path() { + let mut s = session(); + let a = open_path(&mut s, "M0 100 L100 100"); + let b = open_path(&mut s, "M180 100 L280 100"); + let (undo, count) = (undo_len(&s), object_count(&s)); + let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap(); + assert_eq!(id_of(&out), a); + assert_eq!((undo_len(&s), object_count(&s)), (undo + 1, count - 1)); + assert!(s.doc().unwrap().doc.node(b).is_none()); + let (pts, closed) = anchors(&s, a); + assert!(!closed); + let ends = (pts.first().copied(), pts.last().copied()); + assert!( + ends == (Some(Point::new(0.0, 100.0)), Some(Point::new(280.0, 100.0))) + || ends == (Some(Point::new(280.0, 100.0)), Some(Point::new(0.0, 100.0))), + "{pts:?}" + ); + for p in [Point::new(100.0, 100.0), Point::new(180.0, 100.0)] { + assert_eq!(pts.iter().filter(|q| **q == p).count(), 1, "{pts:?}"); + } + assert!(farthest_from_path(&s, a, &[Point::new(140.0, 60.0), Point::new(230.0, 100.0)]) < 1e-9); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((object_count(&s), anchors(&s, b).0.len()), (count, 2)); + // One path's two ends: it closes. + let id = open_path(&mut s, "M100 300 L180 300"); + let out = s.execute(C, &json!({"start": [180, 300], "end": [100, 300], "through": [140, 340], "join": true})).unwrap(); + assert_eq!(id_of(&out), id); + let (pts, closed) = anchors(&s, id); + assert!(closed, "{pts:?}"); + assert_eq!(pts.iter().filter(|q| **q == Point::new(100.0, 300.0)).count(), 1, "{pts:?}"); + assert!(farthest_from_path(&s, id, &[Point::new(140.0, 340.0), Point::new(140.0, 300.0)]) < 1e-9); +} + +/// Of two open path ends at the arc's start, `join` takes the one in the selection, and with +/// neither selected the one in front. +#[test] +fn join_prefers_the_selected_path_then_the_front_one() { + let mut s = session(); + let back = open_path(&mut s, "M0 100 L100 100"); + let front = open_path(&mut s, "M100 200 L100 100"); + for (selected, want) in [(Some(back), back), (None, front)] { + let ids: Vec = selected.iter().map(|id| id.0).collect(); + s.execute("select.set", &json!({ "ids": ids })).unwrap(); + let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap(); + assert_eq!(id_of(&out), want, "{selected:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + // In isolation mode, a path outside the isolated group is left alone. + s.execute("select.set", &json!({ "ids": [back.0] })).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({ "id": group })).unwrap(); + s.execute("select.set", &json!({ "ids": [] })).unwrap(); + let out = s.execute(C, &json!({"start": [100, 100], "end": [100, 20], "through": [60, 60], "join": true})).unwrap(); + assert_eq!(id_of(&out), back, "{out}"); + s.execute("edit.undo", &json!({})).unwrap(); + let out = s.execute(C, &json!({"start": [100, 200], "end": [180, 200], "through": [140, 160], "join": true})).unwrap(); + assert!(out.get("joined").is_none(), "{out}"); + assert_eq!(anchors(&s, front).0.len(), 2); +} + +/// Without `join`, away from open path ends, on a locked path, or on a closed path's anchor, the +/// arc is a new path; a `join` that is not true or false is an error and draws nothing. +#[test] +fn join_leaves_paths_it_cannot_join_alone() { + let mut s = session(); + let line = open_path(&mut s, "M0 100 L100 100"); + let rect = open_path(&mut s, "M200 200 L300 200 L300 300 Z"); + let arc = |s: &mut Session, start: [f64; 2], end: [f64; 2], via: [f64; 2], join: Value| { + s.execute(C, &json!({"start": start, "end": end, "through": via, "join": join})) + }; + for (start, end, via, join) in [ + ([100.0, 100.0], [180.0, 100.0], [140.0, 60.0], json!(false)), + ([100.0, 120.0], [180.0, 120.0], [140.0, 80.0], json!(true)), + ([200.0, 200.0], [120.0, 200.0], [160.0, 160.0], json!(true)), + ] { + let count = object_count(&s); + let out = arc(&mut s, start, end, via, join.clone()).unwrap(); + assert!(out.get("joined").is_none() && id_of(&out) != line && id_of(&out) != rect, "{join}: {out}"); + assert_eq!(object_count(&s), count + 1); + } + assert_eq!(anchors(&s, line).0.len(), 2); + s.execute("select.set", &json!({"ids": [line.0]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + // On the line's other end, where none of the arcs above ends. + let out = arc(&mut s, [0.0, 100.0], [0.0, 180.0], [40.0, 140.0], json!(true)).unwrap(); + assert!(out.get("joined").is_none(), "{out}"); + assert_eq!(anchors(&s, line).0.len(), 2); + let count = object_count(&s); + let e = arc(&mut s, [100.0, 300.0], [180.0, 300.0], [140.0, 260.0], json!("yes")).unwrap_err().to_string(); + assert!(e.contains("`join` must be true or false"), "{e}"); + assert_eq!(object_count(&s), count); +} + +/// With the tool's `join` option on, clicks near an open path's end place the arc's end on it and +/// the arc joins the path; with it off the arc is a path of its own, and J while the ends are +/// placed switches it on. +#[test] +fn the_tool_joins_the_arc_to_the_path_end_it_starts_near() { + let mut s = session(); + let id = open_path(&mut s, "M0 100 L100 100"); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.select_tool("threePointArc", view()).unwrap(); + let count = object_count(&s); + for p in [(100.0, 100.0), (180.0, 100.0), (140.0, 60.0)] { + click(&mut s, p.0, p.1); + } + assert_eq!((object_count(&s), anchors(&s, id).0.len()), (count + 1, 2), "off: a path of its own"); + s.execute("edit.undo", &json!({})).unwrap(); + // J after the first click, near the path's end, switches `join` on. + click(&mut s, 99.0, 100.5); + s.tool_key(ToolKey::Letter('j'), Mods::default(), view()).unwrap(); + click(&mut s, 180.0, 100.0); + click(&mut s, 140.0, 60.0); + assert_eq!(object_count(&s), count); + let (pts, _) = anchors(&s, id); + assert_eq!((pts.len() > 2, pts.last().copied()), (true, Some(Point::new(180.0, 100.0))), "{pts:?}"); + assert_eq!(s.tool_options_of("threePointArc")["join"], json!(true), "J keeps the option switched"); } diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 3c9a7a84cc..d455f6ad2f 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -1043,11 +1043,11 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() { for (cmd, params) in [ ("object.cropImage", json!({})), ("imageTrace.make", json!({})), - ("object.createObjectMosaic", json!({})), ("object.mesh.create", json!({})), + // Vector art has no pixels to put between the corners. ( "file.place", - json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}), + json!({"replace": true, "name": "b.svg", "dataBase64": vectorcraft_format::base64_encode(b"")}), ), ] { let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); @@ -1235,6 +1235,166 @@ fn distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_recor assert_eq!(undo_len(&s), undo); } +/// A type object or (`symbol`) a symbol instance made of a 100 × 60 rectangle, selected alone. +fn type_or_instance(s: &mut Session, symbol: bool) -> NodeId { + let r = if symbol { + rect(s, 20.0, 30.0, 100.0, 60.0); + s.execute("symbol.new", &json!({"name": "Box"})).unwrap() + } else { + s.execute("text.create", &json!({"x": 20, "y": 80, "text": "Distort", "size": 40})).unwrap() + }; + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + id +} + +/// Where the corners of `id`'s box are drawn (top left, top right, bottom right, bottom left). +fn drawn_corners(s: &Session, id: NodeId) -> [Point; 4] { + let doc = &s.doc().unwrap().doc; + doc.node(id).unwrap().drawn_corners(&doc.symbol_boxes()).unwrap() +} + +fn assert_near_corners(got: [Point; 4], want: [Point; 4]) { + for (g, w) in got.iter().zip(want) { + assert!(g.distance(w) < 1e-6, "{got:?} against {want:?}"); + } +} + +/// Perspective Distort and Free Distort put the corners of a type object's box and of a symbol +/// instance's box exactly on the handles, in one undo step: the object stays type or an instance, +/// drawn through the warp, it is bounded by those corners, a move takes them along, and undo gives +/// back the flat object. +#[test] +fn distort_puts_the_corners_of_type_and_symbol_instances_on_the_handles() { + // Perspective Distort, then Free Distort, as fractions of the box. + let quads = [[(0.4, 0.0), (0.6, 0.0), (1.0, 1.0), (0.0, 1.0)], [(0.1, 0.05), (0.9, 0.0), (1.2, 1.1), (0.0, 1.0)]]; + for symbol in [false, true] { + for quad in quads { + let mut s = session(); + let id = type_or_instance(&mut s, symbol); + let b = bounds(&s, id); + let flat = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y)); + assert_near_corners(drawn_corners(&s, id), flat); + let want = quad.map(|(u, v)| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height())); + let undo = undo_len(&s); + s.execute("object.distort", &json!({ "corners": want.map(|p| [p.x, p.y]) })).unwrap(); + assert_eq!(undo_len(&s), undo + 1); + assert_near_corners(drawn_corners(&s, id), want); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Text(_) | vectorcraft_doc::NodeKind::SymbolInstance { .. }), "{:?}", n.kind); + assert!(n.projection().is_some()); + let got = bounds(&s, id); + let (xs, ys) = (want.map(|p| p.x), want.map(|p| p.y)); + let near = |a: f64, b: f64| (a - b).abs() < 1e-6; + assert!( + near(got.x0, xs.iter().copied().fold(f64::MAX, f64::min)) && near(got.x1, xs.iter().copied().fold(f64::MIN, f64::max)), + "{got:?}" + ); + assert!( + near(got.y0, ys.iter().copied().fold(f64::MAX, f64::min)) && near(got.y1, ys.iter().copied().fold(f64::MIN, f64::max)), + "{got:?}" + ); + s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap(); + assert_near_corners(drawn_corners(&s, id), want.map(|p| p + Vec2::new(10.0, 20.0))); + // Distorted type opens flat in Edit Text. + assert_eq!(s.execute("perspective.editText", &json!({"id": id.0})).is_ok(), !symbol); + if !symbol { + assert!(s.doc().unwrap().doc.node(id).unwrap().projection().is_none()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert_near_corners(drawn_corners(&s, id), want.map(|p| p + Vec2::new(10.0, 20.0))); + } + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + if !symbol { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(s.doc().unwrap().doc.node(id).unwrap().projection().is_none()); + assert_near_corners(drawn_corners(&s, id), flat); + } + } +} + +/// Distorted together with paths, the corners of a type object's box and of a symbol instance's +/// box follow the same warp as the anchors of a path drawn on that box. +#[test] +fn distort_moves_type_and_symbol_instances_with_a_path_as_one() { + for symbol in [false, true] { + let mut s = session(); + let id = type_or_instance(&mut s, symbol); + let b = bounds(&s, id); + // A path on the object's box, and one beside it so that the box is not the selection's. + let frame = rect(&mut s, b.x0, b.y0, b.width(), b.height()); + let side = rect(&mut s, b.x1 + 50.0, b.y0 - 40.0, 80.0, 80.0); + s.execute("select.set", &json!({"ids": [id.0, frame.0, side.0]})).unwrap(); + let all = s.doc().unwrap().doc.bounds_of(&[id, frame, side], false).unwrap(); + let corners = [[all.x0 + 30.0, all.y0], [all.x1 - 10.0, all.y0 + 20.0], [all.x1 + 40.0, all.y1], [all.x0, all.y1 - 5.0]]; + s.execute("object.distort", &json!({ "corners": corners })).unwrap(); + let anchors = match &s.doc().unwrap().doc.node(frame).unwrap().kind { + vectorcraft_doc::NodeKind::Path { path, .. } => path.subpaths[0].anchors.iter().map(|a| a.p).collect::>(), + k => panic!("not a path: {k:?}"), + }; + let got = drawn_corners(&s, id); + // The rectangle's first anchor may be any of its corners: each drawn corner is one of them. + for c in got { + assert!(anchors.iter().any(|p| p.distance(c) < 1e-6), "{got:?} against {anchors:?}"); + } + } +} + +/// Corners that would carry a type object's or a symbol instance's box past the warp's horizon, +/// or fold it over, are refused, and nothing changes. +#[test] +fn distort_refuses_corners_type_and_symbol_instances_cannot_follow() { + for symbol in [false, true] { + let mut s = session(); + let id = type_or_instance(&mut s, symbol); + let noun = if symbol { "symbol instance" } else { "type object" }; + let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + // The box (0, 0)-(10, 10) widens toward its bottom so fast that the warp's horizon lies at + // y = 15, across the object. + let e = + s.execute("object.distort", &json!({"from": [0, 0, 10, 10], "corners": [[0, 0], [10, 0], [20, 10], [-10, 10]]})).unwrap_err().to_string(); + assert!(e.contains(&format!("{noun} {}", id.0)) && e.contains("horizon"), "{e}"); + let b = bounds(&s, id); + let folded = [[b.x0, b.y0], [b.x1, b.y1], [b.x1, b.y0], [b.x0, b.y1]]; + let e = s.execute("object.distort", &json!({ "corners": folded })).unwrap_err().to_string(); + assert!(e.contains(&format!("{noun} {}", id.0)) && e.contains("convex"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(undo_len(&s), undo); + // Near the edge of the canvas, the corners still reach the handles. + s.execute("object.move", &json!({"dx": 0, "dy": 3.9e6})).unwrap(); + let b = bounds(&s, id); + let want = [(0.4, 0.0), (0.6, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height())); + s.execute("object.distort", &json!({ "corners": want.map(|p| [p.x, p.y]) })).unwrap(); + let got = drawn_corners(&s, id); + assert!(got.iter().zip(want).all(|(g, w)| g.distance(w) < 1e-3), "{got:?} against {want:?}"); + } +} + +/// Projective distort refuses type being edited flat without changing the document or history; +/// the same warp works after Edit Text ends. +#[test] +fn distort_refuses_type_being_edited_flat() { + let mut s = session(); + let id = type_or_instance(&mut s, false); + let b = bounds(&s, id); + let corners = [(0.2, 0.0), (0.8, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| [b.x0 + u * b.width(), b.y0 + v * b.height()]); + let p = json!({"ids": [id.0], "from": [b.x0, b.y0, b.x1, b.y1], "corners": corners}); + s.execute("object.distort", &p).unwrap(); + s.execute("perspective.editText", &json!({"id": id.0})).unwrap(); + let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + let e = s.execute("object.distort", &p).unwrap_err().to_string(); + assert!(e.contains("object.distort") && e.contains(&format!("type object {}", id.0)) && e.contains("being edited flat in Edit Text"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(undo_len(&s), undo); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let before = drawn_corners(&s, id); + let undo = undo_len(&s); + s.execute("object.distort", &p).unwrap(); + assert_ne!(drawn_corners(&s, id), before); + assert_eq!(undo_len(&s), undo + 1); +} + /// Image info gives a distorted image's resolution at its middle, not the resolution it had /// before the distort. #[test] diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 51f6f2a41d..c7e0e4ec5a 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1233,6 +1233,23 @@ fn color_management_policies_are_checked_and_kept() { assert_eq!(cms::active_settings(), cms::ColorSettings::default()); } +/// `color.parse` takes `oklch()` only while the working RGB space is sRGB; a hex color still gives +/// its numbers as the document's RGB numbers in another working space. +#[test] +fn color_parse_takes_oklch_only_in_an_srgb_working_space() { + let _g = settings(); + let old = cms::active_settings(); + let mut s = session(); + s.execute("edit.colorSettings", &json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap(); + let oklch = s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).map_err(|e| e.to_string()); + let hex = s.execute("color.parse", &json!({"text": "#33669980"})).map_err(|e| e.to_string()); + cms::set_active(&old).unwrap(); + assert!(oklch.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{oklch:?}"); + let hex = hex.unwrap(); + assert_eq!((&hex["hex"], &hex["opacity"]), (&json!("#336699"), &json!(50.2))); + assert!(s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).is_ok(), "sRGB again"); +} + /// The Ask boxes of Edit › Color Settings are checked, come back in the reply and are kept in /// `Color Settings.json`. #[test] diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 6664828398..462641b953 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -857,6 +857,11 @@ fn structured_junk() { ("node.move", json!({"id": 1, "parent": null, "index": 1000})), ("layer.setProps", json!({"id": 1, "color": 1000})), ("layer.newSublayer", json!({"parent": 2})), + ("color.parse", json!({"text": "rgb(1e308 -1e308 1e-400 / 1e308)"})), + ("color.parse", json!({"text": "hsl(1e308turn 1e308% -1e308%)"})), + ("color.parse", json!({"text": "oklch(1e308 1e308 -1e308rad / -1)"})), + ("color.parse", json!({"text": "#\u{1F600}\u{0}\u{FFFF}"})), + ("color.parse", json!({"text": "rgb(((((((((((("})), ("text.create", json!({"x": 0, "y": 0, "text": "\u{0}\u{FFFF}\u{1F600}", "size": -1})), ("text.create", json!({"x": 0, "y": 0, "text": "a", "size": 1e308, "area": {"width": -1, "height": 0}})), ("text.setStyle", json!({"size": 0, "leading": -1, "tracking": 1e308})), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 636c19fb36..9ff294a878 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -6,10 +6,12 @@ //! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files, //! opcodes with random contents) opened or placed, nor EPS and PostScript files //! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of -//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents +//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a +//! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents //! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor //! `.cdr` drawings (mutated and cut short, plain, compressed and packaged, opened and placed), //! nor `.cmx` files (mutated, cut short and garbage after the header, opened and placed), +//! nor layered raster `.pcraft` documents (mutated and cut short archives and manifests, opened and placed), //! nor the font files a folder search reads (damaged fonts, collections whose headers give any count of //! faces), nor scripts written for the reference app checked without running them (garbage, //! generated script text and mutated scripts). @@ -480,6 +482,93 @@ proptest! { } } +// ---------- layered raster .pcraft documents ---------- + +/// A `.pcraft` manifest of a 40 × 30 canvas with two visible raster layers, one under a layer mask, +/// that can be combined, and a hidden one. +fn pcraft_manifest() -> String { + let surface = |mode: &str, pixel: &str| { + let alpha = mode == "Rgb"; + format!(r#"{{"format":{{"mode":"{mode}","sample":"U8","alpha":{alpha}}},"default":"{pixel}","tiles":[]}}"#) + }; + let layer = |visible: bool, pixel: &str, mask: &str| { + format!( + r#"{{"id":1,"name":"L","visible":{visible},"locks":{{}},"blend":"Normal","opacity":0.5,"fill_opacity":1.0,"clipped":false,"mask":{mask}, + "effects":{{"enabled":false,"items":[],"psd_raw":null}},"label":"None","content":{{"kind":"raster","surface":{}}}, + "psd_blocks":[],"psd_id":null,"fill_cache":null}}"#, + surface("Rgb", pixel) + ) + }; + let mask = format!(r#"{{"surface":{},"enabled":true,"linked":true,"density":0.75,"feather":0.0}}"#, surface("Grayscale", "40")); + format!( + r#"{{"format_version":1,"generator":"test 0.1.0","document":{{"id":1,"name":"U","size":{{"width":40,"height":30}},"resolution_dpi":72.0, + "mode":"Rgb","depth":"U8","icc_profile":null,"layers":[{},{},{}],"channels":[],"guides":{{}},"selection":null,"metadata":{{}}, + "global_light":{{}}}},"thumbnail":null,"composite":"composite/preview.png"}}"#, + layer(true, "ff000080", "null"), + layer(true, "0000ffff", &mask), + layer(false, "00ff00ff", "null"), + ) +} + +/// A `.pcraft` bundle of `manifest` with a 4 × 3 preview. +fn pcraft_bundle(manifest: &[u8]) -> Vec { + let mut preview = vec![]; + image::RgbaImage::new(4, 3).write_to(&mut std::io::Cursor::new(&mut preview), image::ImageFormat::Png).unwrap(); + vectorcraft_engine::cmd::fileio::zip::store(&[("manifest.json", manifest), ("composite/preview.png", &preview)]).unwrap() +} + +/// Open and place `.pcraft` file `bytes`: neither may panic. +fn pcraft_survives(what: &str, bytes: &[u8]) -> Result<(), TestCaseError> { + survive(what, || vectorcraft_engine::cmd::fileio::load("x.pcraft", bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.pcraft", "dataBase64":vectorcraft_format::base64_encode(bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "{what}: placement panicked: {:?}", r.err()); + Ok(()) +} + +#[test] +fn the_pcraft_sample_combines_its_layers() { + let l = vectorcraft_engine::cmd::fileio::load("x.pcraft", &pcraft_bundle(pcraft_manifest().as_bytes())).unwrap(); + assert!(l.warnings.is_empty(), "{:?}", l.warnings); + assert_eq!(l.doc.artboards[0].rect.width(), 40.0, "the canvas, not the preview"); +} + +proptest! { + #![proptest_config(config())] + + #[test] + fn pcraft_mutated_bundles_open_and_place( + cut in prop::option::of(4usize..4096), + edits in prop::collection::vec((0usize..8192, any::()), 0..24), + ) { + let mut bytes = pcraft_bundle(pcraft_manifest().as_bytes()); + let n = bytes.len(); + for (at, b) in edits { bytes[at % n] = b; } + if let Some(cut) = cut { + bytes.truncate(cut); + } + pcraft_survives(".pcraft bundle", &bytes)?; + } + + #[test] + fn pcraft_mutated_manifests_open_and_place( + cut in prop::option::of(1usize..2048), + edits in prop::collection::vec((0usize..4096, any::()), 1..16), + ) { + let mut manifest = pcraft_manifest().into_bytes(); + let n = manifest.len(); + for (at, b) in edits { manifest[at % n] = b; } + if let Some(cut) = cut { + manifest.truncate(cut); + } + pcraft_survives(".pcraft manifest", &pcraft_bundle(&manifest))?; + } +} + // ---------- Affinity documents with every feature the reader maps ---------- #[path = "support/affinity_docs.rs"] @@ -1083,6 +1172,58 @@ proptest! { } } +/// A font dictionary whose widths are hostile, for [`vectorcraft_pdf::Opened::page_widths`]: any +/// subtype, encoding and first code, widths that are huge, negative or not numbers, a composite +/// font's `W` of any shape, and the `ToUnicode` map of object 5. +fn arb_width_font() -> impl Strategy { + ( + prop::sample::select(vec!["/TrueType", "/Type1", "/Type0", "/Type3", "/MMType1", "7"]), + prop::sample::select(vec!["/WinAnsiEncoding", "/Identity-H", "/Identity-V", "/MacRomanEncoding", "<< /Differences [65 /A] >>", "null"]), + prop::sample::select(vec!["0", "65", "-5", "255", "256", "4294967295", "1e30", "/X"]), + prop::collection::vec(prop::sample::select(vec!["500", "0", "-1", "1e40", "NaN", "null", "[1 2]", "/W"]), 0..12), + prop::collection::vec(prop::sample::select(vec!["1", "[500 600]", "65", "4294967295", "300", "-1", "[]", "1e9", "0 65535 7"]), 0..10), + prop::sample::select(vec!["/ABCDEF+Fuzz", "/Fuzz", "/ABCDEF+", "/+", "()", "/Fuzz-Identity-H"]), + any::(), + ) + .prop_map(|(subtype, encoding, first, widths, w, name, mapped)| { + let map = if mapped { "/ToUnicode 5 0 R" } else { "" }; + format!( + "<< /Type /Font /Subtype {subtype} /BaseFont {name} /Encoding {encoding} /FirstChar {first} /Widths [{}] {map} \ + /DescendantFonts [<< /Subtype /CIDFontType2 /BaseFont {name} /W [{}] >>] >>", + widths.join(" "), + w.join(" ") + ) + }) +} + +proptest! { + #![proptest_config(config())] + + /// The widths a page's fonts give their characters (read for a `.ai`'s text document) are read + /// without a panic from hostile font dictionaries, `ToUnicode` maps of any text, and forms that + /// draw themselves. + #[test] + fn pdf_font_widths_never_panic( + fonts in prop::collection::vec(arb_width_font(), 1..4), + cmap in prop::collection::vec(prop::sample::select(vec![ + "begincmap", "1 begincodespacerange", "<0000> ", "<00> ", "endcodespacerange", "2 beginbfchar", "<0001> <0041>", + "<0002> ", "<41> ", "1 beginbfrange", "<0000> <0000>", " <0000> <0041>", "<0001> <0003> [<0041> <0042>]", + "endbfrange", "endbfchar", "endcmap", "/Identity-H usecmap", "99999999999 beginbfchar", + ]), 0..12), + ) { + let list: Vec = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect(); + let map = cmap.join("\n"); + let form = format!( + "<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /Font << /F0 {} >> /XObject << /X0 6 0 R >> >> /Length 0 >>\nstream\n\nendstream", + fonts[0] + ); + let more = [format!("<< /Length {} >>\nstream\n{map}\nendstream", map.len() + 1).into_bytes(), form.into_bytes()]; + let pdf = handmade_pdf_with("", &format!("<< /Font << {} >> /XObject << /X0 6 0 R >> >>", list.join(" ")), "[0 0 100 100]", &more); + let read = catch_quiet(|| vectorcraft_pdf::open_pdf(&pdf, None).ok().map(|o| o.page_widths())); + prop_assert!(read.is_ok(), "{fonts:?} {cmap:?}: {read:?}"); + } +} + /// A dictionary value: one the reader reads, or one it skips over but can't parse (a name with a /// broken `#` escape, a number with a stray `-`). fn arb_dict_value() -> impl Strategy { @@ -2970,6 +3111,95 @@ proptest! { } } +// ---------- generated art objects' saved fields ---------- + +/// A native document holding one generated art object (a square drawn by plug-in +/// `org.example.gen`), as pretty JSON text. +fn generated_sample() -> Value { + use std::sync::Arc; + use vectorcraft_doc::generated::GeneratedArt; + use vectorcraft_doc::{Node, NodeId}; + let mut d = Document::new(200.0, 200.0); + let layer = d.layers.first().map(|l| l.id); + let square = + Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(10.0, 10.0, 60.0, 60.0)), Default::default()); + let mut g = Node::group(NodeId(0), vec![Arc::new(square)]); + g.id = d.alloc_id(); + let mut params = serde_json::Map::new(); + params.insert("size".into(), json!(50)); + g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", params))); + d.insert(layer, usize::MAX, g).unwrap(); + serde_json::from_slice(&vectorcraft_format::save(&d, true)).unwrap() +} + +/// The object of `v` (a native file's JSON) that holds a `generated` field. +fn generated_node(v: &mut Value) -> Option<&mut Value> { + match v { + Value::Object(o) if o.contains_key("generated") => Some(v), + Value::Object(o) => o.values_mut().find_map(generated_node), + Value::Array(a) => a.iter_mut().find_map(generated_node), + _ => None, + } +} + +/// Any JSON a damaged or hand-made file may hold in a saved field: strings (empty, long, with NUL, +/// control, bidi and path characters), numbers, booleans, null, lists and objects. +fn arb_saved_value() -> impl Strategy { + let leaf = prop_oneof![ + Just(Value::Null), + any::().prop_map(Value::from), + any::().prop_map(Value::from), + any::().prop_map(|f| serde_json::Number::from_f64(f).map_or(Value::Null, Value::Number)), + ".{0,80}".prop_map(Value::from), + prop::sample::select(vec!["org.example.gen", "org.example.gen ", "../x", "a\u{0}b", "\u{202e}gen", "", "x.y-z_1"]).prop_map(Value::from), + (0usize..200_000).prop_map(|n| Value::from("p".repeat(n))), + ]; + leaf.prop_recursive(3, 24, 6, |inner| { + prop_oneof![ + prop::collection::vec(inner.clone(), 0..6).prop_map(Value::from), + prop::collection::btree_map("[a-z_]{0,8}", inner, 0..6).prop_map(|m| Value::Object(m.into_iter().collect())), + ] + }) +} + +proptest! { + #![proptest_config(config())] + + /// A generated art object's saved plug-in id, name, parameters, transforms, scales and hash + /// replaced by anything, and the whole field too: the file opens without running a plug-in and + /// keeps the art, or is refused; an id is kept only when it is a plug-in id. It then renders, + /// exports and saves. + #[test] + fn generated_art_saved_fields_never_panic_and_keep_the_art(field in 0usize..9, value in arb_saved_value()) { + let mut v = generated_sample(); + let node = generated_node(&mut v).unwrap(); + let art = node["kind"].clone(); + let id = vectorcraft_doc::NodeId(node["id"].as_u64().unwrap()); + match ["plugin", "name", "params", "transform", "strokeScale", "effectScale", "patternTransform", "hash"].get(field) { + Some(key) => node["generated"][*key] = value, + None => node["generated"] = value, + } + let bytes = serde_json::to_vec(&v).unwrap(); + let loaded = vectorcraft_engine::cmd::fileio::load("x.vectorcraft", &bytes); + if let Ok(l) = &loaded { + // The group keeps its art whatever was read of its generated art fields. + let group = l.doc.node(id); + prop_assert!(group.is_some(), "the group is gone"); + prop_assert_eq!(group.map(|n| serde_json::to_value(&n.kind).unwrap()), Some(art)); + let mut plugins = vec![]; + l.doc.walk(|n| { + if let Some(g) = n.extras().generated.as_deref() { + plugins.push(g.plugin.clone()); + } + }); + for plugin in &plugins { + prop_assert!(plugin.is_empty() || vectorcraft_doc::generated::valid_id(plugin), "{plugin:?}"); + } + } + survive("generated art fields", || loaded.ok().map(|l| l.doc))?; + } +} + /// A native file whose area type has 2^60 rows, 2^60 columns, or 2^32 of each (their product /// overflows) opens with 100 in place of each count over 100, and renders and exports. #[test] @@ -4825,6 +5055,53 @@ proptest! { prop_assert!(!opened); } + /// A `.ai` whose private data is cut into streams anywhere, each deflated or not and some + /// damaged, opens or is refused without a panic, and its streams read one after the other give + /// what joining them gives. + #[test] + fn ai_private_data_cut_into_streams_anywhere_never_panics( + sizes in prop::collection::vec(1usize..400, 1..6), + damage in prop::collection::vec((0usize..4_000, any::()), 0..4), + deflate in any::(), + ) { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&editing_text())].concat(); + let mut parts: Vec> = vec![]; + let mut rest = private.as_slice(); + for size in sizes.iter().cycle() { + if rest.is_empty() { + break; + } + let (part, after) = rest.split_at((*size).min(rest.len())); + parts.push(if deflate { deflated(part) } else { part.to_vec() }); + rest = after; + } + let total: usize = parts.iter().map(Vec::len).sum(); + for (at, b) in damage { + let mut at = at % total.max(1); + for part in &mut parts { + if let Some(x) = part.get_mut(at) { + *x = b; + break; + } + at -= part.len(); + } + } + let parts: Vec<&[u8]> = parts.iter().map(Vec::as_slice).collect(); + let filter = if deflate { "/Filter /FlateDecode " } else { "" }; + let bytes = vectorcraft_testkit::ai::ai_with_parts(&parts, vectorcraft_testkit::ai::page_pdf(), "", filter); + let read_all = |r: &mut dyn std::io::Read| { + let mut data = vec![]; + r.read_to_end(&mut data).map(|_| data).map_err(|e| e.to_string()) + }; + let (joined, streamed) = catch_quiet(|| { + let opened = vectorcraft_pdf::open_pdf(&bytes, None).ok(); + (opened.as_ref().and_then(|o| o.illustrator_data()), opened.as_ref().and_then(|o| o.read_illustrator_data(read_all))) + }) + .expect("the private data read panicked"); + prop_assert_eq!(streamed, joined.map(Ok)); + survive("a .ai whose private data is cut into streams", || vectorcraft_engine::cmd::fileio::load("x.ai", &bytes).ok().map(|l| l.doc))?; + } + /// A `.ai` whose strokes have any width (0, which draws a hairline, negative, huge, not a number) on a /// path, on a gradient-filled path that `1 BB` strokes and on type in any rendering mode, /// damaged or hostile. diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index e1832f3d17..bad590987d 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -542,6 +542,120 @@ fn a_dimension_of_a_whole_path_measures_its_overall_width_and_height() { assert!((value(&s, id) - across).abs() < 0.1, "{} against {across}", text(&s, id)); } +/// A dimension of a whole path placed with Use Preview Bounds on (`"preview": true`) measures the +/// outside of the stroke, the width or height W and H show, and follows a new stroke weight with +/// its line as far outside the stroke as before. Without the flag the dimension measures between +/// the outermost points. The flag survives a native file, and a value other than true or false is +/// an error. +#[test] +fn a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke() { + use vectorcraft_engine::doc::dimension::DimensionSource; + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "stroke.set", json!({"weight": 10.0})); + let create = |s: &mut Session, preview: bool, orientation: &str| { + let source = json!({"kind":"extent","node":rect,"preview":preview}); + run(s, "dimension.create", json!({"source":source,"orientation":orientation,"offset":-30}))["id"].as_u64().unwrap() + }; + let (wide, tall, plain) = (create(&mut s, true, "horizontal"), create(&mut s, true, "vertical"), create(&mut s, false, "horizontal")); + let texts = |s: &Session| [wide, tall, plain].map(|id| text(s, id)); + assert_eq!(texts(&s), ["110.00 pt", "70.00 pt", "100.00 pt"]); + // 30 pt above the first point, the top left anchor: 25 pt above the stroke. + assert!((recipe(&s, wide).line_ends().0.y - 70.0).abs() < 1e-9, "{:?}", recipe(&s, wide).line_ends()); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "stroke.set", json!({"weight": 20.0})); + assert_eq!(texts(&s), ["120.00 pt", "80.00 pt", "100.00 pt"]); + assert!((recipe(&s, wide).line_ends().0.y - 65.0).abs() < 1e-9, "{:?}", recipe(&s, wide).line_ends()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(texts(&s), ["110.00 pt", "70.00 pt", "100.00 pt"]); + + let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false); + let mut reopened = Session::new(); + reopened.add_document(vectorcraft_format::load(&saved).unwrap(), None); + assert_eq!(recipe(&reopened, wide).source, Some(DimensionSource::Extent { node: NodeId(rect), preview: true })); + assert_eq!(recipe(&reopened, plain).source, Some(DimensionSource::Extent { node: NodeId(rect), preview: false })); + run(&mut reopened, "select.set", json!({"ids":[rect]})); + run(&mut reopened, "stroke.set", json!({"weight": 2.0})); + assert_eq!(texts(&reopened), ["102.00 pt", "62.00 pt", "100.00 pt"]); + + let bad = json!({"source":{"kind":"extent","node":rect,"preview":"yes"},"orientation":"horizontal"}); + assert!(s.execute("dimension.create", &bad).is_err()); +} + +/// A path made into a guide paints no strokes, so a dimension of the whole guide with Use Preview +/// Bounds measures between its outermost points, as one without the flag does. A dimension placed +/// before the path became a guide measures the same, and the stroke again once it is released. +#[test] +fn a_preview_bounds_dimension_of_a_guide_does_not_measure_its_stroke() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "stroke.set", json!({"weight": 10.0})); + let create = |s: &mut Session, orientation: &str| { + let source = json!({"kind":"extent","node":rect,"preview":true}); + run(s, "dimension.create", json!({"source":source,"orientation":orientation,"offset":-30}))["id"].as_u64().unwrap() + }; + let (before_wide, before_tall) = (create(&mut s, "horizontal"), create(&mut s, "vertical")); + assert_eq!([text(&s, before_wide), text(&s, before_tall)], ["110.00 pt", "70.00 pt"]); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "view.guides.make", json!({})); + assert!(s.doc().unwrap().doc.node(NodeId(rect)).unwrap().is_guide()); + let (wide, tall) = (create(&mut s, "horizontal"), create(&mut s, "vertical")); + assert_eq!([text(&s, wide), text(&s, tall)], ["100.00 pt", "60.00 pt"]); + // Dimensions placed before follow the path into a guide and back out of it. + assert_eq!([text(&s, before_wide), text(&s, before_tall)], ["100.00 pt", "60.00 pt"]); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "view.guides.release", json!({})); + assert!(!s.doc().unwrap().doc.node(NodeId(rect)).unwrap().is_guide()); + assert_eq!([text(&s, before_wide), text(&s, wide)], ["110.00 pt", "110.00 pt"]); +} + +/// With Use Preview Bounds, a dimension of a member of a compound path measures only the +/// arrowheads the compound path draws on that member: the start head on the first member's line +/// and the end head on the last one's. A member in the middle measures as the same line without +/// arrowheads does. +#[test] +fn a_preview_bounds_dimension_of_a_compound_member_measures_only_its_own_arrowheads() { + let mut s = session(); + let line = |s: &mut Session, y: f64| run(s, "shape.line", json!({"x1":100,"y1":y,"x2":200,"y2":y}))["id"].as_u64().unwrap(); + let (first, middle, last) = (line(&mut s, 100.0), line(&mut s, 200.0), line(&mut s, 300.0)); + run(&mut s, "select.set", json!({"ids":[first, middle, last]})); + run(&mut s, "object.compoundPath.make", json!({})); + run(&mut s, "stroke.set", json!({"weight": 4.0, "startArrow": "Triangle", "endArrow": "Triangle"})); + let alone = line(&mut s, 400.0); + run(&mut s, "select.set", json!({"ids":[alone]})); + run(&mut s, "stroke.set", json!({"weight": 4.0})); + let ends = |s: &mut Session, node: u64, orientation: &str| { + let source = json!({"kind":"extent","node":node,"preview":true}); + let id = run(s, "dimension.create", json!({"source":source,"orientation":orientation,"offset":-30}))["id"].as_u64().unwrap(); + let (a, b) = (recipe(s, id).a, recipe(s, id).b); + if orientation == "horizontal" { (a.x, b.x) } else { (a.y, b.y) } + }; + let (bare, mid) = (ends(&mut s, alone, "horizontal"), ends(&mut s, middle, "horizontal")); + assert!((mid.0 - bare.0).abs() < 1e-9 && (mid.1 - bare.1).abs() < 1e-9, "{mid:?} against {bare:?}"); + // Across the lines: the stroke weight alone, or wider where a head is drawn. + let across = |s: &mut Session, node: u64| { + let (a, b) = ends(s, node, "vertical"); + b - a + }; + let bare = across(&mut s, alone); + assert!((bare - 4.0).abs() < 1e-9, "{bare}"); + assert!((across(&mut s, middle) - bare).abs() < 1e-9, "{}", across(&mut s, middle)); + assert!(across(&mut s, first) > bare + 1.0, "start head on the first member: {}", across(&mut s, first)); + assert!(across(&mut s, last) > bare + 1.0, "end head on the last member: {}", across(&mut s, last)); + + // Released, the middle line draws both heads itself, and its dimension measures them. + let source = json!({"kind":"extent","node":middle,"preview":true}); + let kept = run(&mut s, "dimension.create", json!({"source":source,"orientation":"vertical","offset":-30}))["id"].as_u64().unwrap(); + let span = |s: &Session| recipe(s, kept).b.y - recipe(s, kept).a.y; + assert!((span(&s) - bare).abs() < 1e-9, "{}", span(&s)); + let compound = s.doc().unwrap().doc.parent_of(NodeId(middle)).unwrap(); + run(&mut s, "select.set", json!({"ids":[compound.0]})); + run(&mut s, "object.compoundPath.release", json!({})); + assert!(span(&s) > bare + 1.0, "{}", span(&s)); +} + /// A dimension of a whole path measures the segments the path draws: an anchor that starts no /// segment does not widen it. Its line stays clear of the whole path when only parts other than /// its measured points move, also when it is aligned or is scaled together with the path, when the diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 334dc9c1c1..ff4a5c22ab 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -35,6 +35,7 @@ mod ruler_guide_perf; mod ruler_origin; mod script_host_vs_scriptcheck; mod selection_commands; +mod several_handles; mod stroke_visibility; mod text_stroke_scale; mod three_d_light_color; diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index c54d8676c0..d7f60e5b2c 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -42,11 +42,13 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ]; /// The names the host adds that stay inside the document and the run, by the object that has them. -/// Reading a file or a folder, a file dialog and a message to the person do not change anything -/// outside it. The document model (`app`, its classes and the enumerations) acts on the open -/// documents; `Document.saveAs` and `close` throw "not available yet". +/// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not +/// change anything outside it. The document model (`app`, its classes and the enumerations) acts on +/// the open documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ - ("", "$ File Folder UnitValue alert confirm localize prompt toSource"), + ("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"), + ("Window.", "alert confirm length prompt prototype"), + ("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show"), ("Object.prototype.", "reflect toSource"), ("UnitValue.", "baseUnit baseUnit= length prototype"), ("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="), @@ -79,15 +81,17 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ + "activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ - Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= Tag Tags ZOrderMethod", + Documents ElementPlacement Layer PageItem PageItems RulerUnits ScreenMode selection selection= Tag Tags View Views \ + ZOrderMethod", ), ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \ - getIsFileOpen selection selection= toString typename", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \ + executeMenuCommand getIsFileOpen loadAction loadAction= redraw selection selection= textFonts toString typename \ + unloadAction unloadAction=", ), ("DocumentPreset.", "prototype"), ( @@ -102,11 +106,15 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames textFrames= toString \ - typename views views= width", + "activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \ + documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \ + pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \ + symbols symbols= tags textFrames toString typename views width", ), + ("Views.", "prototype"), + ("Views.prototype.", "constructor index length parent toString typename"), + ("View.", "prototype"), + ("View.prototype.", "bounds centerPoint centerPoint= constructor parent screenMode screenMode= toString typename zoom zoom="), ("Layer.", "prototype"), ("Layer.prototype.", "constructor name toString typename"), ("PageItems.", "prototype"), @@ -125,6 +133,11 @@ const INSIDE: &[(&str, &str)] = &[ ("Tags.prototype.", "add constructor getByName index length parent removeAll typename"), ("Tag.", "prototype"), ("Tag.prototype.", "constructor name name= parent remove typename value value="), + ( + "BlendModes.", + "COLORBLEND COLORBURN COLORDODGE DARKEN DIFFERENCE EXCLUSION HARDLIGHT HUE LIGHTEN LUMINOSITY MULTIPLY NORMAL \ + OVERLAY SATURATIONBLEND SCREEN SOFTLIGHT", + ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), @@ -138,7 +151,118 @@ const INSIDE: &[(&str, &str)] = &[ ), ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), + ("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), + ( + "", + "CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \ + ParagraphAttributes ParagraphStyle ParagraphStyleAttributes ParagraphStyles Paragraphs TextFont TextFonts TextFrame \ + TextFrames TextOrientation TextRange TextType Words", + ), + ("TextFrames.", "prototype"), + ("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"), + ("TextFrame.", "prototype"), + ( + "TextFrame.prototype.", + "anchor anchor= antialias antialias= characters columnCount columnCount= columnGutter columnGutter= constructor \ + contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \ + insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \ + opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \ + rowGutter= startTValue startTValue= story textPath textPath= textRange textRanges textRanges= textSelection \ + textSelection= words", + ), + ("TextRange.", "prototype"), + ( + "TextRange.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ + characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \ + duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \ + getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \ + horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \ + leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles \ + paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \ + spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \ + textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ + verticalScale= words", + ), + ("Characters.", "prototype"), + ("Characters.prototype.", "add addBefore constructor length parent typename"), + ("Words.", "prototype"), + ("Words.prototype.", "add addBefore constructor length parent typename"), + ("Paragraphs.", "prototype"), + ("Paragraphs.prototype.", "add addBefore constructor length parent typename"), + ("CharacterAttributes.", "prototype"), + ( + "CharacterAttributes.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ + rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ + underline= verticalScale verticalScale=", + ), + ("ParagraphAttributes.", "prototype"), + ( + "ParagraphAttributes.prototype.", + "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ + rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", + ), + ("CharacterStyles.", "prototype"), + ("CharacterStyles.prototype.", "add constructor getByName index length parent removeAll typename"), + ("CharacterStyle.", "prototype"), + ("CharacterStyle.prototype.", "applyTo characterAttributes constructor name name= parent remove typename"), + ("CharacterStyleAttributes.", "prototype"), + ( + "CharacterStyleAttributes.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ + rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ + underline= verticalScale verticalScale=", + ), + ("ParagraphStyles.", "prototype"), + ("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"), + ("ParagraphStyle.", "prototype"), + ( + "ParagraphStyle.prototype.", + "applyTo characterAttributes characterAttributes= constructor name name= paragraphAttributes parent remove typename", + ), + ("ParagraphStyleAttributes.", "prototype"), + ( + "ParagraphStyleAttributes.prototype.", + "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ + rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", + ), + ("TextFonts.", "prototype"), + ("TextFonts.prototype.", "constructor getByName index length parent typename"), + ("TextFont.", "prototype"), + ("TextFont.prototype.", "constructor family name parent style typename"), + ("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"), + ("TextOrientation.", "HORIZONTAL VERTICAL"), + ("TextType.", "AREATEXT PATHTEXT POINTTEXT"), + ("", "Stories Story StoryCharacters StoryParagraphs StoryRange StoryWords"), + ("Stories.", "prototype"), + ("Stories.prototype.", "constructor index length parent typename"), + ("Story.", "prototype"), + ( + "Story.prototype.", + "characters constructor insertionPoints insertionPoints= length lines lines= paragraphs parent textFrames textRange \ + textRanges textRanges= textSelection textSelection= typename words", + ), + ("StoryRange.", "prototype"), + ( + "StoryRange.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \ + characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \ + contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \ + getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \ + getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \ + length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \ + paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \ + strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ + underline underline= verticalScale verticalScale= words", + ), + ("StoryCharacters.", "prototype"), + ("StoryCharacters.prototype.", "constructor length parent typename"), + ("StoryWords.", "prototype"), + ("StoryWords.prototype.", "constructor length parent typename"), + ("StoryParagraphs.", "prototype"), + ("StoryParagraphs.prototype.", "constructor length parent typename"), // Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s // `visibilityVariable` is in its row above. ("", "Dataset Datasets Variable VariableKind Variables"), @@ -160,7 +284,7 @@ const INSIDE: &[(&str, &str)] = &[ /// The classes the host adds with nothing but a prototype and its constructor: the page item types. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/engine/tests/it/selection_commands.rs b/crates/engine/tests/it/selection_commands.rs index c5bcc1d9dd..7d9c01bf3b 100644 --- a/crates/engine/tests/it/selection_commands.rs +++ b/crates/engine/tests/it/selection_commands.rs @@ -16,7 +16,7 @@ fn session() -> (Session, NodeId, NodeId) { #[test] fn selection_commands_reject_invalid_ids_without_changing_state() { - for command in ["select.set", "select.add", "select.toggle"] { + for command in ["select.set", "select.add", "select.toggle", "select.remove"] { let (mut s, a, b) = session(); s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap(); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); @@ -37,7 +37,7 @@ fn selection_commands_reject_invalid_ids_without_changing_state() { #[test] fn selection_commands_require_an_id_array() { - for command in ["select.set", "select.add", "select.toggle"] { + for command in ["select.set", "select.add", "select.toggle", "select.remove"] { let (mut s, _, _) = session(); for params in [json!({}), json!({"ids": null}), json!({"ids": 2}), json!({"ids": "2"}), json!({"ids": true})] { let selection = s.active().unwrap().selection.clone(); @@ -78,13 +78,52 @@ fn toggle_and_add_handle_each_listed_id_in_order() { #[test] fn single_id_toggle_validates_before_mutating() { let (mut s, a, _) = session(); - for invalid in [json!(999), json!(-1), json!(2.5), json!("2"), Value::Null, json!(true)] { - let selection = s.active().unwrap().selection.clone(); - assert!(matches!(s.execute("select.toggle", &json!({"id": invalid})), Err(EngineError::BadParams { .. }))); - assert_eq!(s.active().unwrap().selection, selection); + for command in ["select.toggle", "select.remove"] { + for invalid in [json!(999), json!(-1), json!(2.5), json!("2"), Value::Null, json!(true)] { + let selection = s.active().unwrap().selection.clone(); + assert!(matches!(s.execute(command, &json!({"id": invalid})), Err(EngineError::BadParams { .. })), "{command}: {invalid}"); + assert_eq!(s.active().unwrap().selection, selection); + } + // A malformed array must not silently fall back to a valid single id. + assert!(s.execute(command, &json!({"ids": "bad", "id": a.0})).is_err()); } - // A malformed array must not silently fall back to a valid single id. - assert!(s.execute("select.toggle", &json!({"ids": "bad", "id": a.0})).is_err()); +} + +/// Direct Selection's Shift-click on a member of a selected group: `select.remove` deselects the +/// member and keeps the group's other objects selected, and `select.anchors` with mode toggle on +/// one of the member's anchors deselects only that anchor. +#[test] +fn remove_and_anchor_toggle_open_a_selected_group() { + let (mut s, a, b) = session(); + let c = NodeId(s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let reset = |s: &mut Session| s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + reset(&mut s); + assert_eq!(s.execute("select.remove", &json!({"id": b.0})).unwrap(), json!({"count": 2, "ids": [a.0, c.0]})); + assert_eq!(s.execute("select.remove", &json!({"id": b.0})).unwrap(), json!({"count": 2, "ids": [a.0, c.0]}), "b is not selected"); + assert_eq!(s.execute("select.remove", &json!({"ids": [c.0]})).unwrap(), json!({"count": 1, "ids": [a.0]})); + // A member selected beside its group (as Group Selection leaves it) leaves the selection with the group. + s.execute("select.set", &json!({"ids": [group.0, b.0]})).unwrap(); + assert_eq!(s.execute("select.remove", &json!({"id": b.0})).unwrap(), json!({"count": 2, "ids": [a.0, c.0]})); + reset(&mut s); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "toggle"})).unwrap(); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.objects, [a, b, c]); + assert_eq!(sel.partial(a), Some(&[(0, 0), (0, 2), (0, 3)].into()), "the other anchors of a stay selected"); + assert_eq!((sel.partial(b), sel.partial(c)), (None, None), "b and c stay selected whole"); + // A second Shift-click, on an anchor of b, deselects only that anchor of b. + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 2]], "mode": "toggle"})).unwrap(); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.objects, [a, b, c]); + assert_eq!(sel.partial(a), Some(&[(0, 0), (0, 2), (0, 3)].into())); + assert_eq!(sel.partial(b), Some(&[(0, 0), (0, 1), (0, 3)].into()), "the other anchors of b stay selected"); + assert_eq!(sel.partial(c), None); + // An anchor of a path that is not selected joins the selection by itself. + let d = NodeId(s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": d.0, "anchors": [[0, 1]], "mode": "toggle"})).unwrap(); + assert_eq!(s.active().unwrap().selection.partial(d), Some(&[(0, 1)].into())); } #[test] diff --git a/crates/engine/tests/it/several_handles.rs b/crates/engine/tests/it/several_handles.rs new file mode 100644 index 0000000000..7b5469c278 --- /dev/null +++ b/crates/engine/tests/it/several_handles.rs @@ -0,0 +1,212 @@ +//! Direct Selection picks several direction handles and drags them together (`path.moveHandles`). + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{Anchor, AnchorKind, Point}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +fn view() -> ViewInfo { + ViewInfo { + smart_guides: false, + guides: false, + snap_to_point: false, + snap_to_grid: false, + snap_to_pixel: false, + snap_to_glyph: false, + corner_widgets: false, + show_bbox: false, + ..ViewInfo::default() + } +} + +/// A path selected whole with Direct Selection chosen: anchor 1 is smooth, its incoming handle at +/// (50, 100) and its outgoing one at (180, 100); anchor 2's incoming handle is at (300, 140). +fn session() -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 900, "height": 700})).unwrap(); + for (key, value) in [("constrainAngle", json!(0)), ("showHandlesMultipleAnchors", json!(true))] { + s.execute("prefs.set", &json!({"key": key, "value": value})).unwrap(); + } + let id = s + .execute( + "path.create", + &json!({"anchors": [ + {"x": 20, "y": 220}, + {"x": 100, "y": 100, "in": [50, 100], "out": [180, 100]}, + {"x": 320, "y": 220, "in": [300, 140]} + ]}), + ) + .unwrap(); + let id = NodeId(id["id"].as_u64().unwrap()); + s.select_tool("directSelection", view()).unwrap(); + (s, id) +} + +fn anchor(s: &Session, id: NodeId, i: usize) -> Anchor { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[i] +} + +fn pointer(s: &mut Session, kind: PointerKind, at: Point, mods: Mods) { + s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(mods), view()).unwrap(); +} + +fn click(s: &mut Session, at: Point, mods: Mods) { + pointer(s, PointerKind::Down, at, mods); + pointer(s, PointerKind::Up, at, mods); +} + +fn drag(s: &mut Session, from: Point, to: Point, mods: Mods) { + pointer(s, PointerKind::Down, from, mods); + pointer(s, PointerKind::Drag, Point::new((from.x + to.x) / 2.0, (from.y + to.y) / 2.0), mods); + pointer(s, PointerKind::Drag, to, mods); + pointer(s, PointerKind::Up, to, mods); +} + +fn shift() -> Mods { + Mods { shift: true, ..Mods::default() } +} + +fn near(actual: Point, expected: Point) { + assert!(actual.distance(expected) < 1e-6, "point {actual:?}, expected {expected:?}"); +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn document(s: &Session) -> Value { + json!(s.doc().unwrap().doc) +} + +/// A click picks a handle and a Shift-click adds another without moving it; a drag of either then +/// moves both by the same offset, and a smooth anchor turns its other handle in line, as one undo +/// step that Undo takes back whole. +#[test] +fn a_drag_of_one_of_two_picked_handles_moves_both_in_one_undo_step() { + let (mut s, id) = session(); + let before = document(&s); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + // A Shift-click with a small slip of the pointer picks the handle and leaves it where it is. + pointer(&mut s, PointerKind::Down, Point::new(300.0, 140.0), shift()); + pointer(&mut s, PointerKind::Drag, Point::new(301.0, 140.0), shift()); + pointer(&mut s, PointerKind::Up, Point::new(301.0, 140.0), shift()); + near(anchor(&s, id, 2).h_in, Point::new(300.0, 140.0)); + let undo = undo_len(&s); + drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 130.0), Mods::default()); + let a = anchor(&s, id, 1); + near(a.h_out, Point::new(180.0, 130.0)); + assert_eq!(a.kind, AnchorKind::Smooth); + // The incoming handle keeps its length (50) and turns in line with the moved one. + let dir = (a.p - a.h_out) / (a.p - a.h_out).hypot(); + near(a.h_in, a.p + dir * 50.0); + near(anchor(&s, id, 2).h_in, Point::new(300.0, 170.0)); + assert_eq!(undo_len(&s), undo + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(document(&s), before); +} + +/// The picked handles stay picked after their drag, and a second drag of the other one moves both +/// again. +#[test] +fn picked_handles_stay_picked_after_they_are_dragged() { + let (mut s, id) = session(); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(300.0, 140.0), shift()); + drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 130.0), Mods::default()); + drag(&mut s, Point::new(300.0, 170.0), Point::new(310.0, 170.0), Mods::default()); + near(anchor(&s, id, 1).h_out, Point::new(190.0, 130.0)); + near(anchor(&s, id, 2).h_in, Point::new(310.0, 170.0)); +} + +/// A Shift-click on a picked handle takes it away, and Escape lets every picked handle go: a drag +/// then moves only the handle pressed. +#[test] +fn shift_click_and_escape_let_picked_handles_go() { + for escape in [false, true] { + let (mut s, id) = session(); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(300.0, 140.0), shift()); + if escape { + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + } else { + click(&mut s, Point::new(180.0, 100.0), shift()); + } + drag(&mut s, Point::new(300.0, 140.0), Point::new(300.0, 170.0), Mods::default()); + near(anchor(&s, id, 2).h_in, Point::new(300.0, 170.0)); + near(anchor(&s, id, 1).h_out, Point::new(180.0, 100.0)); + } +} + +/// Both handles of a smooth anchor picked move together and the anchor becomes a corner; with Alt, +/// each picked handle's anchor becomes a corner and keeps its other handle. +#[test] +fn both_handles_of_an_anchor_or_alt_make_a_corner() { + let (mut s, id) = session(); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(50.0, 100.0), shift()); + drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 120.0), Mods::default()); + let a = anchor(&s, id, 1); + near(a.h_out, Point::new(180.0, 120.0)); + near(a.h_in, Point::new(50.0, 120.0)); + assert_eq!(a.kind, AnchorKind::Corner); + + let (mut s, id) = session(); + let alt = Mods { alt: true, ..Mods::default() }; + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(300.0, 140.0), shift()); + drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 130.0), alt); + let a = anchor(&s, id, 1); + near(a.h_out, Point::new(180.0, 130.0)); + near(a.h_in, Point::new(50.0, 100.0)); + assert_eq!(a.kind, AnchorKind::Corner); + near(anchor(&s, id, 2).h_in, Point::new(300.0, 170.0)); +} + +/// `path.moveHandles` refuses a list it cannot act on, moves a handle listed twice once, and +/// records no undo step for a move by nothing. +#[test] +fn move_handles_checks_its_params() { + let (mut s, id) = session(); + let h = |anchor: u64, which: &str| json!({"id": id.0, "anchor": anchor, "which": which}); + let before = document(&s); + let undo = undo_len(&s); + for (params, message) in [ + (json!({"dx": 1, "dy": 1}), "missing handles"), + (json!({"handles": [], "dx": 1, "dy": 1}), "`handles` is empty"), + (json!({"handles": {}, "dx": 1, "dy": 1}), "`handles` must be an array"), + (json!({"handles": [h(1, "out")], "dy": 1}), "missing number `dx`"), + (json!({"handles": [h(1, "out")], "dx": 1, "dy": 1, "independent": "yes"}), "`independent` must be true or false"), + (json!({"handles": [{"id": id.0, "anchor": 1}], "dx": 1, "dy": 1}), "`which` must be \"in\" or \"out\""), + (json!({"handles": [h(1, "out"), h(9, "in")], "dx": 1, "dy": 1}), "has no anchor 9 in subpath 0"), + (json!({"handles": [{"anchor": 1, "which": "in"}], "dx": 1, "dy": 1}), "missing id"), + ] { + let err = s.execute("path.moveHandles", ¶ms).unwrap_err().to_string(); + assert!(err.contains(message), "{params}: {err}"); + } + s.execute("path.moveHandles", &json!({"handles": [h(1, "out")], "dx": 0, "dy": 0})).unwrap(); + assert_eq!(document(&s), before); + assert_eq!(undo_len(&s), undo, "no undo step for a refused call or a move by nothing"); + s.execute("path.moveHandles", &json!({"handles": [h(2, "in"), h(2, "in")], "dx": 5, "dy": 0})).unwrap(); + near(anchor(&s, id, 2).h_in, Point::new(305.0, 140.0)); + assert_eq!(undo_len(&s), undo + 1); +} + +/// A move by nothing that makes one path's smooth anchor a corner leaves a listed handle of a live +/// rectangle, which needs no change, alone: the rectangle stays live. +#[test] +fn a_move_by_nothing_leaves_a_live_shape_that_needs_no_change_live() { + let (mut s, id) = session(); + let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 100, "height": 60})).unwrap(); + let rect = NodeId(rect["id"].as_u64().unwrap()); + let live = |s: &Session| matches!(&s.doc().unwrap().doc.node(rect).unwrap().kind, NodeKind::Path { live: Some(_), .. }); + assert!(live(&s), "shape.rectangle makes a live rectangle"); + let handles = json!([ + {"id": id.0, "anchor": 1, "which": "in"}, + {"id": id.0, "anchor": 1, "which": "out"}, + {"id": rect.0, "anchor": 0, "which": "out"} + ]); + s.execute("path.moveHandles", &json!({"handles": handles, "dx": 0, "dy": 0})).unwrap(); + assert_eq!(anchor(&s, id, 1).kind, AnchorKind::Corner, "both handles listed make the smooth anchor a corner"); + assert!(live(&s), "the rectangle's listed handle needed no change, so the rectangle stays live"); +} diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 1987b8adba..48c90cad29 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -793,10 +793,11 @@ proptest! { } /// Manifests with hostile `commands` (junk of every type, bad and repeated ids, labels with - /// control and bidirectional override characters, a `menu` of any shape naming any menu, junk - /// parameters) at API level 1 or 2 parse to an error or to commands whose menu labels show no - /// hidden character and that sit under Plug-ins, or at level 2 in one of the menus a manifest - /// may name, with the plug-in's name; installing one and running each of its commands ends as an + /// control and bidirectional override characters, a `menu` of any shape naming any menu or + /// context menu, junk parameters) at API level 1 or 2 parse to an error or to commands whose + /// menu labels show no hidden character and that sit under Plug-ins, or at level 2 in one of the + /// menus a manifest may name, with the plug-in's name, and in at most the capped number of + /// context menu items; installing one and running each of its commands ends as an /// error or an edit, never a panic, and the document then renders and exports. #[test] fn hostile_manifest_commands_never_crash( @@ -819,6 +820,11 @@ proptest! { Just(json!({"path": ["Select"], "after": "\u{202E}Inverse"})), arb_junk().prop_map(|j| json!({"path": j})), arb_junk().prop_map(|j| json!({"path": ["Select"], "after": j})), + Just(json!({"context": [{"menu": "canvas", "when": "typeObject"}, {"menu": "layers", "when": "layerRow"}]})), + Just(json!({"context": [{"menu": "canvas", "when": "layerRow"}]})), + arb_junk().prop_map(|j| json!({"context": j})), + arb_junk().prop_map(|j| json!({"context": [{"menu": "layers", "when": j}]})), + arb_junk().prop_map(|j| json!({"path": ["Select"], "context": [j]})), arb_junk(), ], prop_oneof![Just(Value::Null), Just(json!({"by": {"type": "number", "min": 0, "max": 10, "default": 2}})), arb_junk()], @@ -860,6 +866,11 @@ proptest! { prop_assert!(api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&place.path), "{:?}", place); prop_assert!(placed.ends_with(')') && placed.len() > shown.len(), "a placed item names its plug-in: {}", placed); } + prop_assert!(api >= 2 || c.context.is_empty(), "level 1 lists no context menu: {:?}", c.context); + prop_assert!(c.context.iter().all(|p| p.menu == vectorcraft_plugins::ContextMenu::Layers || p.when != Some(vectorcraft_plugins::ContextWhen::LayerRow))); + } + for menu in [vectorcraft_plugins::ContextMenu::Canvas, vectorcraft_plugins::ContextMenu::Layers] { + prop_assert!(man.context_commands(menu).count() <= vectorcraft_plugins::manifest::MAX_CONTEXT_COMMANDS); } } let mut s = rich_session(); diff --git a/crates/engine/tests/plugin_generate.rs b/crates/engine/tests/plugin_generate.rs new file mode 100644 index 0000000000..4e936f0d88 --- /dev/null +++ b/crates/engine/tests/plugin_generate.rs @@ -0,0 +1,369 @@ +//! Generator plug-ins (`"kind": "generator"`, docs/plugins.md › Generators) through the engine: the +//! generated art objects `plugin.generate` makes, `plugin.editGenerated` drawing them again, Expand, +//! and what a saved file keeps and says when the plug-in is missing, its fields are damaged or its +//! art no longer matches. Opening a file never runs a plug-in. +//! +//! A test binary of its own: installed plug-ins are process-wide. +// 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 serde_json::{Value, json}; +use vectorcraft_doc::Node; +use vectorcraft_doc::generated::State; +use vectorcraft_engine::Session; +use vectorcraft_plugins::wat::{self as tpl, Given}; + +/// A generator's art: a 10 pt square at (0, 0). +const SMALL: &str = r#"{"objects":[{"type":"path","name":"Small","path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[10,0]},{"p":[10,10]},{"p":[0,10]}]}]}}]}"#; + +/// A generator's art: a 20 pt square at (0, 0) and a line. +const BIG: &str = r#"{"objects":[{"type":"path","name":"Big","path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[20,0]},{"p":[20,20]},{"p":[0,20]}]}]}},{"type":"path","name":"Line","path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,30]},{"p":[20,30]}]}]}}]}"#; + +/// The parameters of the test generators. +const PARAMS: &str = r#"{"size":{"type":"int","min":1,"max":100,"default":10},"label":{"type":"string","default":"a"}}"#; + +/// Installs the plug-in written in WAT `src` (`replace`: in place of the one with its id). +fn install(s: &mut Session, src: &str, replace: bool) -> Value { + let wasm = wat::parse_str(src).unwrap_or_else(|e| panic!("bad test WAT: {e}")); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "replace": replace})).unwrap() +} + +/// A generator `id` that draws [`BIG`] when its `size` is 20 and [`SMALL`] otherwise. +fn sizes(s: &mut Session, id: &str) { + install(s, &tpl::when_given_else(&tpl::generator(id, PARAMS), Given::Params, r#""size":20"#, BIG, SMALL), false); +} + +/// A new document with generated art from generator `id` → the object's id. +fn generated(s: &mut Session, id: &str) -> u64 { + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let r = s.execute("plugin.generate", &json!({"id": id})).unwrap(); + assert_eq!(r["plugin"], json!(id)); + r["id"].as_u64().unwrap() +} + +/// The node `id` of the active document. +fn node(s: &Session, id: u64) -> Node { + s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap() +} + +/// The names of `id`'s children. +fn art(s: &Session, id: u64) -> Vec { + node(s, id).children().unwrap().iter().map(|c| c.name.clone().unwrap_or_default()).collect() +} + +/// The undo steps of the active document. +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The active document saved as native text and opened again → the open's warnings. +fn reopen(s: &mut Session) -> Vec { + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + reopen_bytes(s, &bytes) +} + +fn reopen_bytes(s: &mut Session, bytes: &[u8]) -> Vec { + let r = s.execute("document.open", &json!({"name": "Gen.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + r["warnings"].as_array().map(|w| w.iter().map(|w| w.as_str().unwrap_or_default().to_string()).collect()).unwrap_or_default() +} + +/// The only generated art object of the active document → its id. +fn the_generated(s: &Session) -> u64 { + let mut ids = vec![]; + s.doc().unwrap().doc.walk(|n| { + if n.extras().generated.is_some() { + ids.push(n.id.0); + } + }); + assert_eq!(ids.len(), 1, "{ids:?}"); + ids[0] +} + +#[test] +fn a_generator_draws_a_generated_art_object_as_one_undo_step() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.create"); + let entry = s.execute("plugin.info", &json!({"id": "test.gen.create"})).unwrap(); + assert_eq!((&entry["kind"], &entry["permissions"]), (&json!("generator"), &json!(["doc.write"]))); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let before = steps(&s); + let id = s.execute("plugin.generate", &json!({"id": "test.gen.create"})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(steps(&s), before + 1); + assert_eq!(art(&s, id), ["Small"]); + let n = node(&s, id); + let g = n.extras().generated.as_deref().unwrap(); + assert_eq!((g.plugin.as_str(), g.name.as_str(), g.state), ("test.gen.create", "Test test.gen.create", State::Intact)); + assert_eq!(serde_json::to_value(&g.params).unwrap(), json!({"size": 10, "label": "a"})); + assert_eq!(s.doc().unwrap().selection.objects, [vectorcraft_doc::NodeId(id)]); + // Given parameters are checked: a bad one is an error and nothing is added. + for bad in [json!({"size": 500}), json!({"size": "big"}), json!({"color": 1})] { + assert!(s.execute("plugin.generate", &json!({"id": "test.gen.create", "params": bad})).is_err(), "{bad}"); + } + assert_eq!(steps(&s), before + 1); + // Another kind of plug-in is not a generator, and plugin.run doesn't run a generator. + install(&mut s, &tpl::module(&tpl::manifest("test.gen.filter", "filter", "{}"), tpl::ECHO, "", 1), false); + let e = s.execute("plugin.generate", &json!({"id": "test.gen.filter"})).unwrap_err().to_string(); + assert!(e.contains("not a generator"), "{e}"); + let e = s.execute("plugin.run", &json!({"id": "test.gen.create"})).unwrap_err().to_string(); + assert!(e.contains("plugin.generate"), "{e}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).is_none()); +} + +#[test] +fn editing_the_parameters_draws_the_art_again_as_one_undo_step() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.edit"); + let id = generated(&mut s, "test.gen.edit"); + // Moved since it was drawn: the new art is drawn where the object is. + s.execute("object.move", &json!({"dx": 100, "dy": 50})).unwrap(); + let before = steps(&s); + let r = s.execute("plugin.editGenerated", &json!({"params": {"size": 20}})).unwrap(); + assert_eq!((&r["id"], &r["changed"]), (&json!(id), &json!(true))); + assert_eq!(steps(&s), before + 1); + assert_eq!(art(&s, id), ["Big", "Line"]); + let b = s.doc().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (100.0, 50.0, 120.0, 80.0)); + let n = node(&s, id); + let g = n.extras().generated.as_deref().unwrap(); + assert_eq!(serde_json::to_value(&g.params).unwrap(), json!({"size": 20, "label": "a"})); + // The same parameters again change nothing and make no undo step. + let r = s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap(); + assert_eq!(r["changed"], json!(false)); + assert_eq!(steps(&s), before + 1); + // A bad parameter is an error, and the art stays. + for bad in [json!({"size": 0}), json!({"size": true}), json!({"other": 1})] { + assert!(s.execute("plugin.editGenerated", &json!({"id": id, "params": bad})).is_err(), "{bad}"); + } + assert!(s.execute("plugin.editGenerated", &json!({"id": id, "params": [1]})).is_err()); + assert_eq!((steps(&s), art(&s, id)), (before + 1, vec!["Big".to_string(), "Line".to_string()])); + // One undo step brings back the art and the parameters it had. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(art(&s, id), ["Small"]); + let n = node(&s, id); + assert_eq!(serde_json::to_value(&n.extras().generated.as_deref().unwrap().params).unwrap(), json!({"size": 10, "label": "a"})); + // Nothing selected that is generated art. + s.execute("select.none", &json!({})).unwrap(); + let e = s.execute("plugin.editGenerated", &json!({"params": {"size": 20}})).unwrap_err().to_string(); + assert!(e.contains("select one generated art object"), "{e}"); + // The generated art object selected with another object: neither command picks it out. + let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap(); + s.execute("select.set", &json!({"ids": [id, square["id"]]})).unwrap(); + for (c, p) in [("plugin.editGenerated", json!({"params": {"size": 20}})), ("plugin.generatedInfo", json!({}))] { + let e = s.execute(c, &p).unwrap_err().to_string(); + assert!(e.contains("select one generated art object"), "{c}: {e}"); + } + assert_eq!(art(&s, id), ["Small"]); +} + +/// A generator's art: a line with a 2 pt stroke. +const STROKED: &str = r#"{"objects":[{"type":"path","name":"Stroked","path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,0]},{"p":[10,0]}]}]},"strokes":[{"paint":{"type":"solid","color":{"model":"rgb","r":0,"g":0,"b":0}},"width":2}]}]}"#; + +/// The stroke weights of the art of generated art object `id`. +fn stroke_widths(s: &Session, id: u64) -> Vec { + let n = node(s, id); + let mut widths = vec![]; + for c in n.children().unwrap() { + for it in &c.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(st) = it { + widths.push(st.width); + } + } + } + widths +} + +#[test] +fn drawing_again_keeps_the_stroke_weights_a_scale_gave_the_art() { + let mut s = Session::new(); + install(&mut s, &tpl::returning(&tpl::generator("test.gen.strokes", PARAMS), STROKED), false); + let id = generated(&mut s, "test.gen.strokes"); + assert_eq!(stroke_widths(&s, id), [2.0]); + // Scaled to 200% with Scale Strokes & Effects: the stroke doubles, and stays doubled when the + // art is drawn again. + s.execute("object.scale", &json!({"sx": 200, "strokes": true})).unwrap(); + assert_eq!(stroke_widths(&s, id), [4.0]); + s.execute("plugin.editGenerated", &json!({"params": {"label": "b"}})).unwrap(); + assert_eq!(stroke_widths(&s, id), [4.0]); + // Scaled to 50% without it: the stroke keeps its weight, drawn again too. + s.execute("object.scale", &json!({"sx": 50, "strokes": false})).unwrap(); + assert_eq!(stroke_widths(&s, id), [4.0]); + s.execute("plugin.editGenerated", &json!({"params": {"label": "c"}})).unwrap(); + assert_eq!(stroke_widths(&s, id), [4.0]); + // A saved file keeps what the strokes were scaled by. + reopen(&mut s); + let id = the_generated(&s); + s.execute("plugin.editGenerated", &json!({"id": id, "params": {"label": "d"}})).unwrap(); + assert_eq!(stroke_widths(&s, id), [4.0]); +} + +#[test] +fn a_plug_in_of_another_kind_in_place_of_the_generator_is_named_on_open() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.kind"); + generated(&mut s, "test.gen.kind"); + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + install(&mut s, &tpl::module(&tpl::manifest("test.gen.kind", "filter", "{}"), tpl::ECHO, "", 1), true); + let warnings = reopen_bytes(&mut s, &bytes); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("`test.gen.kind` is a plug-in of kind `filter`, not a generator"), "{warnings:?}"); + let id = the_generated(&s); + assert_eq!(art(&s, id), ["Small"]); + assert_eq!(s.execute("plugin.generatedInfo", &json!({"id": id})).unwrap()["installed"], json!(false)); +} + +#[test] +fn expand_makes_generated_art_an_ordinary_group() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.expand"); + let id = generated(&mut s, "test.gen.expand"); + s.execute("object.expand", &json!({"object": true})).unwrap(); + let n = node(&s, id); + assert!(n.extras().generated.is_none()); + assert_eq!(art(&s, id), ["Small"]); + let e = s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap_err().to_string(); + assert!(e.contains("select one generated art object"), "{e}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, id).extras().generated.is_some()); +} + +#[test] +fn a_saved_file_keeps_the_parameters_and_the_art_and_opening_runs_no_plug_in() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.save"); + generated(&mut s, "test.gen.save"); + s.execute("plugin.editGenerated", &json!({"params": {"size": 20, "label": "b"}})).unwrap(); + // The installed generator now always draws the small square: opening must not run it. + install(&mut s, &tpl::returning(&tpl::generator("test.gen.save", PARAMS), SMALL), true); + let warnings = reopen(&mut s); + assert!(warnings.is_empty(), "{warnings:?}"); + let id = the_generated(&s); + assert_eq!(art(&s, id), ["Big", "Line"]); + let info = s.execute("plugin.generatedInfo", &json!({"id": id})).unwrap(); + assert_eq!((&info["plugin"], &info["state"], &info["installed"]), (&json!("test.gen.save"), &json!("intact"), &json!(true))); + assert_eq!(info["params"], json!({"size": 20, "label": "b"})); + // An explicit edit runs it. + s.execute("plugin.editGenerated", &json!({"id": id, "params": {"label": "c"}})).unwrap(); + assert_eq!(art(&s, id), ["Small"]); +} + +#[test] +fn a_missing_plug_in_keeps_the_art_and_is_named() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.gone"); + generated(&mut s, "test.gen.gone"); + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + s.execute("plugin.remove", &json!({"id": "test.gen.gone"})).unwrap(); + let warnings = reopen_bytes(&mut s, &bytes); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("“Test test.gen.gone” (test.gen.gone) isn't installed"), "{warnings:?}"); + let id = the_generated(&s); + assert_eq!(art(&s, id), ["Small"]); + let info = s.execute("plugin.generatedInfo", &json!({})).unwrap_or_else(|_| s.execute("plugin.generatedInfo", &json!({"id": id})).unwrap()); + assert_eq!((&info["state"], &info["installed"]), (&json!("intact"), &json!(false))); + let e = s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap_err().to_string(); + assert!(e.contains("isn't installed"), "{e}"); + assert_eq!(art(&s, id), ["Small"]); + // Saved again without the plug-in, it keeps its fields. + let again = vectorcraft_format::save(&s.doc().unwrap().doc, true); + sizes(&mut s, "test.gen.gone"); + assert!(reopen_bytes(&mut s, &again).is_empty()); + let id = the_generated(&s); + s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap(); + assert_eq!(art(&s, id), ["Big", "Line"]); +} + +#[test] +fn a_missing_generator_in_an_opacity_mask_is_named_on_open() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.mask.gone"); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let target = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone(); + let mask = s.execute("plugin.generate", &json!({"id": "test.gen.mask.gone"})).unwrap()["id"].clone(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [target, mask]})).unwrap(); + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + s.execute("plugin.remove", &json!({"id": "test.gen.mask.gone"})).unwrap(); + let warnings = reopen_bytes(&mut s, &bytes); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("test.gen.mask.gone") && warnings[0].contains("isn't installed"), "{warnings:?}"); +} + +#[test] +fn a_missing_generator_in_a_symbol_definition_is_named_on_open() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.symbol.gone"); + generated(&mut s, "test.gen.symbol.gone"); + s.execute("symbol.new", &json!({"name": "Generated"})).unwrap(); + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + s.execute("plugin.remove", &json!({"id": "test.gen.symbol.gone"})).unwrap(); + let warnings = reopen_bytes(&mut s, &bytes); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("test.gen.symbol.gone") && warnings[0].contains("isn't installed"), "{warnings:?}"); +} + +#[test] +fn generated_art_inside_live_containers_can_be_drawn_again() { + for (index, command) in ["object.blend.make", "object.repeat.grid", "object.envelope.makeWithWarp"].into_iter().enumerate() { + let mut s = Session::new(); + let plugin = format!("test.gen.container.{index}"); + sizes(&mut s, &plugin); + let generated = generated(&mut s, &plugin); + let other = s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()["id"].clone(); + s.execute(command, &json!({"ids": [generated, other]})).unwrap(); + let before = steps(&s); + s.execute("plugin.editGenerated", &json!({"id": generated, "params": {"size": 20}})).unwrap(); + assert_eq!(art(&s, generated), ["Big", "Line"], "{command}"); + assert_eq!(steps(&s), before + 1, "{command}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(art(&s, generated), ["Small"], "{command}"); + } +} + +/// The saved native text `bytes` with the generated art object's JSON changed by `f`. +fn tampered(bytes: &[u8], f: impl FnOnce(&mut Value)) -> Vec { + fn find(v: &mut Value) -> Option<&mut Value> { + match v { + Value::Object(o) if o.contains_key("generated") => Some(v), + Value::Object(o) => o.values_mut().find_map(find), + Value::Array(a) => a.iter_mut().find_map(find), + _ => None, + } + } + let mut v: Value = serde_json::from_slice(bytes).unwrap(); + f(find(&mut v).unwrap()); + serde_json::to_vec(&v).unwrap() +} + +#[test] +fn a_garbled_id_or_changed_art_keeps_the_art() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.garbled"); + generated(&mut s, "test.gen.garbled"); + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + for bad in [json!("test.gen.garbled/../x"), json!(""), json!(42), json!("t\u{0}x")] { + let file = tampered(&bytes, |n| n["generated"]["plugin"] = bad.clone()); + let warnings = reopen_bytes(&mut s, &file); + assert!(warnings.iter().any(|w| w.contains("plug-in id or parameters are damaged")), "{bad}: {warnings:?}"); + let id = the_generated(&s); + assert_eq!(art(&s, id), ["Small"], "{bad}"); + let info = s.execute("plugin.generatedInfo", &json!({"id": id})).unwrap(); + assert_eq!((&info["state"], &info["installed"]), (&json!("damaged"), &json!(false)), "{bad}"); + let e = s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap_err().to_string(); + assert!(e.contains("damaged"), "{bad}: {e}"); + } + // Art edited outside the app no longer matches the hash: it is kept as it is. + let file = tampered(&bytes, |n| { + let child = &mut n["kind"]["children"][0]; + assert!(child.get("name").is_some(), "{child}"); + child["name"] = json!("Edited"); + }); + let warnings = reopen_bytes(&mut s, &file); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("doesn't match the hash its file gave"), "{warnings:?}"); + let id = the_generated(&s); + assert_eq!(art(&s, id), ["Edited"]); + assert_eq!(s.execute("plugin.generatedInfo", &json!({"id": id})).unwrap()["state"], json!("changed")); + // An explicit edit may still draw it again with its plug-in. + s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap(); + assert_eq!(art(&s, id), ["Big", "Line"]); +} diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index 9bf9b87f0d..11a42a6f90 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -273,7 +273,7 @@ fn failures_open_nothing() { ("test.fail.notjson", "not json", "JSON"), ("test.fail.empty", r#"{"objects":[]}"#, "the importer returned no objects"), ("test.fail.key", r#"{"objects":[],"layers":[]}"#, "an importer returns `objects` and `warnings`, not `layers`"), - ("test.fail.id", r#"{"objects":[{"id":3}]}"#, "is not the id of an input object"), + ("test.fail.id", r#"{"objects":[{"id":3}]}"#, "an importer returns new paths without `id`"), ("test.fail.far", far, "4000000"), ("test.fail.warnings", bad_warnings.as_str(), "`warnings` must be a list of strings"), ]; @@ -441,3 +441,161 @@ fn a_built_in_file_past_the_input_limit_still_opens() { assert_eq!(s.execute("document.open", &encoded).unwrap()["format"], "png"); let _ = std::fs::remove_dir_all(&dir); } + +/// An importer at plug-in API level 4 `id` reading `.trc` files, listing `kinds` (a JSON list) in +/// `outputKinds`, whose output is the file it is given. +fn rich_echo(s: &mut Session, id: &str, kinds: &str) -> Value { + let manifest = + format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"importer","api":4,"extensions":["trc"],"outputKinds":{kinds}}}"#); + install(s, &tpl::module(&manifest, tpl::ECHO, "", 1)) +} + +/// The pixels of a 2 × 1 image: opaque red, then half-transparent blue. +const PIXELS: [u8; 8] = [255, 0, 0, 255, 0, 0, 255, 128]; + +/// Rich importer output: type, the image of [`PIXELS`] and the rectangle of [`RECT`], with two +/// layers (the image and the rectangle in "Art", the type in the hidden, locked "Words") and two +/// artboards. +fn rich_output() -> Value { + let rect: Value = serde_json::from_str(RECT).unwrap(); + json!({ + "objects": [ + {"type": "type", "text": "Hello\nWorld", "fontFamily": "No Such Family Q9617", "fontSize": 24, + "fill": {"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}, "transform": [1, 0, 0, 1, 10, 40], "name": "Title"}, + {"type": "image", "pixelSize": [2, 1], "pixelsBase64": vectorcraft_format::base64_encode(&PIXELS), "transform": [10, 0, 0, 10, 0, 100]}, + rect["objects"][0], + ], + "layers": [{"name": "Art", "objects": [1, 2]}, {"name": "Words", "visible": false, "locked": true, "objects": [0]}], + "artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}, {"name": "Back", "rect": [220, 0, 200, 100]}], + "warnings": ["from the importer"], + }) +} + +/// The active document's layers (name, shown, locked, kinds of its objects), its artboards (name +/// and rectangle), its type (text, family, size, fill), the RGBA of its first image, and the transforms +/// of its text and images. +#[allow(clippy::type_complexity)] +fn structure( + s: &Session, +) -> (Vec<(String, bool, bool, Vec<&'static str>)>, Vec<(String, [f64; 4])>, Vec<(String, String, f64, String)>, Vec, Vec<(&'static str, [f64; 6])>) +{ + let d = &s.doc().unwrap().doc; + let kind = |n: &vectorcraft_doc::Node| match &n.kind { + vectorcraft_doc::NodeKind::Text(_) => "type", + vectorcraft_doc::NodeKind::Image(_) => "image", + vectorcraft_doc::NodeKind::Path { .. } => "path", + _ => "other", + }; + let layers = d + .layers + .iter() + .map(|l| (l.name.clone().unwrap_or_default(), l.visible, l.locked, l.children().unwrap().iter().map(|c| kind(c)).collect())) + .collect(); + let boards = d.artboards.iter().map(|a| (a.name.clone(), [a.rect.x0, a.rect.y0, a.rect.x1, a.rect.y1])).collect(); + let (mut types, mut pixels, mut transforms) = (Vec::new(), Vec::new(), Vec::new()); + d.walk(|n| match &n.kind { + vectorcraft_doc::NodeKind::Text(t) => { + transforms.push(("type", t.xf.as_coeffs())); + let st = &t.runs[0].style; + let text: String = t.runs.iter().map(|r| r.text.as_str()).collect(); + types.push((text, st.font_family.clone(), st.size, serde_json::to_string(&st.fill).unwrap())); + } + vectorcraft_doc::NodeKind::Image(im) => { + transforms.push(("image", im.xf.as_coeffs())); + // Read back through the filter input's own decoder, not the importer's. + if pixels.is_empty() { + let o = vectorcraft_plugins::objects::encode_read_only(d, n).unwrap(); + pixels = vectorcraft_format::base64_decode(o["pixelsBase64"].as_str().unwrap()).unwrap(); + } + } + _ => {} + }); + (layers, boards, types, pixels, transforms) +} + +/// An importer at API level 4 that lists every output kind opens editable type, an embedded image, +/// paths, layers and artboards as it returned them; the artboards replace the one around the art, +/// a missing font is reported with the importer's warnings, and the document saves and opens again +/// in the native format with all of it. +#[test] +fn an_api_4_importer_opens_type_images_layers_and_artboards() { + let mut s = Session::new(); + let entry = rich_echo(&mut s, "test.rich", r#"["type","image","layer","artboard"]"#); + assert_eq!((&entry["api"], &entry["outputKinds"]), (&json!(4), &json!(["type", "image", "layer", "artboard"]))); + assert_eq!(entry["permissions"], json!(["import.read"])); + let r = open(&mut s, "Rich.trc", rich_output().to_string().as_bytes(), json!({})).unwrap(); + let warnings = r["warnings"].as_array().unwrap(); + assert_eq!(warnings.first(), Some(&json!("from the importer"))); + assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("No Such Family Q9617")), "{warnings:?}"); + let opened = structure(&s); + let blue = serde_json::to_string(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))).unwrap(); + assert_eq!(opened.0, [("Art".to_string(), true, false, vec!["image", "path"]), ("Words".to_string(), false, true, vec!["type"])]); + assert_eq!(opened.1, [("Front".to_string(), [0.0, 0.0, 200.0, 100.0]), ("Back".to_string(), [220.0, 0.0, 420.0, 100.0])]); + assert_eq!(opened.2, [("Hello\nWorld".to_string(), "No Such Family Q9617".to_string(), 24.0, blue)]); + assert_eq!(opened.3, PIXELS); + assert_eq!(opened.4, [("image", [10.0, 0.0, 0.0, 10.0, 0.0, 100.0]), ("type", [1.0, 0.0, 0.0, 1.0, 10.0, 40.0])]); + // The type is laid out at the place the transform gives: its first baseline starts at (10, 40). + let d = &s.doc().unwrap().doc; + let words = d.layers[1].children().unwrap()[0].clone(); + let b = d.bounds_of(&[words.id], false).unwrap(); + assert!(b.x0 >= 9.0 && b.x0 < 12.0 && b.y0 < 40.0 && b.y1 > 40.0, "{b:?}"); + + let native = fileio::encode(&s.doc().unwrap().doc, "vectorcraft", &json!({})).unwrap(); + open(&mut s, "Again.vectorcraft", &native, json!({})).unwrap(); + assert_eq!(structure(&s), opened, "saved and opened again"); +} + +/// An importer at API level 4 that lists only some kinds: output with another kind, a malformed +/// image, a bad layer, or an image or type that reaches past the canvas opens nothing and leaves the open document as it was; a blank document of +/// artboards alone opens. +#[test] +fn rich_output_that_fails_its_checks_changes_nothing() { + let mut s = Session::new(); + rich_echo(&mut s, "test.richsome", r#"["type","image","layer"]"#); + let before = open_edited(&mut s, "test.richsome.edited"); + let mut short = rich_output(); + short["objects"][1]["pixelsBase64"] = json!(vectorcraft_format::base64_encode(&PIXELS[..4])); + let mut twice = rich_output(); + twice["layers"][1]["objects"] = json!([0, 2]); + let mut wide = rich_output(); + wide["objects"][1]["transform"] = json!([4000000, 0, 0, 1, 0, 0]); + let mut far = rich_output(); + far["objects"][0]["transform"] = json!([1, 0, 0, 1, 4000000, 40]); + let cases = [ + (rich_output(), "`artboard`"), + (short, "= 8 bytes"), + (twice, "exactly one layer"), + (wide, "objects[1]: it reaches more than 4000000 pt"), + (far, "objects[0]: it reaches more than 4000000 pt"), + (json!({"objects": [], "layers": [{"name": "A\u{202E}B"}]}), "text direction"), + ]; + for (mut output, says) in cases { + if says != "`artboard`" { + output.as_object_mut().unwrap().remove("artboards"); + } + let e = open(&mut s, "x.trc", output.to_string().as_bytes(), json!({"importer": "plugin.test.richsome"})).unwrap_err(); + assert!(e.to_string().contains(says) && e.to_string().contains("x.trc"), "{says}: {e}"); + assert_eq!(state(&mut s), before, "{says}"); + } + rich_echo(&mut s, "test.richboards", r#"["artboard"]"#); + let blank = json!({"objects": [], "artboards": [{"name": "Only", "rect": [0, 0, 50, 60]}]}); + open(&mut s, "Blank.trc", blank.to_string().as_bytes(), json!({"importer": "plugin.test.richboards"})).unwrap(); + let (layers, boards, types, _, _) = structure(&s); + assert_eq!((layers.len(), layers[0].3.len(), boards, types.len()), (1, 0, vec![("Only".to_string(), [0.0, 0.0, 50.0, 60.0])], 0)); +} + +/// An importer below API level 4 reads paths alone, as it always has: type is not a path, and it +/// can't return layers. +#[test] +fn an_older_importer_reads_paths_alone() { + let mut s = Session::new(); + echo(&mut s, "test.older", r#"["tol"]"#); + let e = open(&mut s, "x.tol", rich_output().to_string().as_bytes(), json!({})).unwrap_err(); + assert!(e.to_string().contains("an importer returns `objects` and `warnings`, not `"), "{e}"); + let typed = json!({"objects": [rich_output()["objects"][0]]}); + let e = open(&mut s, "x.tol", typed.to_string().as_bytes(), json!({})).unwrap_err(); + assert!(e.to_string().contains("`type` must be \"path\" or \"compound\""), "{e}"); + assert!(s.documents().is_empty()); + open(&mut s, "Shapes.tol", RECT.as_bytes(), json!({})).unwrap(); + assert_eq!((objects(&s), artboard(&s), s.doc().unwrap().doc.layers.len()), (1, (10.0, 20.0, 110.0, 70.0), 1)); +} diff --git a/crates/engine/tests/plugin_place.rs b/crates/engine/tests/plugin_place.rs index e5996c7a36..c15982cd07 100644 --- a/crates/engine/tests/plugin_place.rs +++ b/crates/engine/tests/plugin_place.rs @@ -58,6 +58,56 @@ fn state(s: &mut Session) -> (usize, usize, usize, Value) { (d.history.undo.len(), d.history.redo.len(), d.doc.layers.len(), content) } +#[test] +fn placing_importer_checks_the_transformed_bounds_before_editing() { + let image = json!({"objects": [{ + "type": "image", "pixelSize": [1, 1], "pixelsBase64": vectorcraft_format::base64_encode(&[255, 0, 0, 255]), + "transform": [20, 0, 0, 10, 0, 0], + }]}) + .to_string(); + for (index, output, half_width) in [(0, ART, 50.0), (1, image.as_str(), 10.0)] { + let mut s = with_document(); + let mut manifest: Value = serde_json::from_str(&placing(&format!("test.place.canvas{index}"), r#"["tpc"]"#)).unwrap(); + if index == 1 { + manifest["api"] = json!(4); + manifest["outputKinds"] = json!(["image"]); + } + install(&mut s, &tpl::returning(&manifest.to_string(), output)); + let importer = format!("plugin.test.place.canvas{index}"); + let before = state(&mut s); + for at in [[4_000_000.0, 400.0], [-4_000_000.0, 400.0], [400.0, 4_000_000.0], [400.0, -4_000_000.0]] { + for template in [false, true] { + assert!( + place(&mut s, "Art.tpc", b"?", json!({"at": at, "template": template, "importer": importer})).is_err(), + "{index}: {at:?}, template: {template}" + ); + assert_eq!(state(&mut s), before); + } + } + let inside = place(&mut s, "Art.tpc", b"?", json!({"at": [4_000_000.0 - half_width, 400.0], "importer": importer})); + assert!(inside.is_ok(), "{index}: {inside:?}"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.0 + 1); + } +} + +#[test] +fn cropped_svg_placement_checks_art_outside_its_frame_before_editing() { + let svg = br#""#; + for at in [[3_999_940.0, 400.0], [-3_999_940.0, 400.0], [400.0, 3_999_940.0], [400.0, -3_999_940.0]] { + for template in [false, true] { + let mut s = with_document(); + let before = state(&mut s); + assert!( + place(&mut s, "cropped.svg", svg, json!({"at": at, "crop": "crop", "template": template})).is_err(), + "{at:?}, template: {template}" + ); + assert_eq!(state(&mut s), before); + } + } + let mut s = with_document(); + assert!(place(&mut s, "cropped.svg", svg, json!({"at": [3_999_930.0, 400.0], "crop": "crop"})).is_ok()); +} + /// A placed group: its name, the names of its children, and its bounds as `(x0, y0, x1, y1)`. type Placed = (Option, Vec>, (f64, f64, f64, f64)); @@ -159,6 +209,37 @@ fn guides_are_left_out_of_what_is_placed() { assert_eq!(state(&mut s), before); } +/// An importer at plug-in API level 4 places its type and images with its paths: the objects of its +/// visible layers go in the group, in order, the objects of a hidden layer are left out, and its +/// artboards leave the document's as they were. +#[test] +fn an_api_4_importer_places_type_and_images_of_its_visible_layers() { + let mut s = with_document(); + let manifest = r#"{"id":"test.place.rich","name":"Test test.place.rich","version":"1","kind":"importer","api":4,"extensions":["tpr"],"place":true,"outputKinds":["type","image","layer","artboard"]}"#; + let rect: Value = serde_json::from_str(ART).unwrap(); + let output = json!({ + "objects": [ + {"type": "type", "text": "Hello", "fontFamily": "No Such Family P9129", "fontSize": 24, "transform": [1, 0, 0, 1, 10, 40], "name": "Title"}, + {"type": "image", "pixelSize": [2, 1], "pixelsBase64": vectorcraft_format::base64_encode(&[255, 0, 0, 255, 0, 0, 255, 128]), "transform": [10, 0, 0, 10, 0, 100], "name": "Pic"}, + rect["objects"][0], + ], + "layers": [{"name": "Shown", "objects": [0, 1]}, {"name": "Hidden", "visible": false, "objects": [2]}], + "artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}], + }); + install(&mut s, &tpl::returning(manifest, &output.to_string())); + let boards = s.doc().unwrap().doc.artboards.clone(); + let r = place(&mut s, "Rich.tpr", b"?", json!({"at": [300, 400]})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let NodeKind::Group { children, .. } = &d.node(id).expect("placed").kind else { panic!("not a group") }; + let kinds: Vec<(Option<&str>, bool, bool)> = children + .iter() + .map(|c| (c.name.as_deref(), matches!(c.kind, NodeKind::Text(_)), matches!(&c.kind, NodeKind::Image(im) if d.images.contains_key(&im.key)))) + .collect(); + assert_eq!(kinds, [(Some("Title"), true, false), (Some("Pic"), false, true)]); + assert_eq!(d.artboards, boards); +} + /// The importer is told it places the file (`_context.mode`), with the file's extension and name, /// and is given its parameters. #[test] diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 364f3a1646..8c3b4ad12d 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -10388,6 +10388,8 @@ fn brush_library() -> Vec { rotation_relative_to_path: true, colorization: Colorization::Tints, hue_jitter: 0.0, + saturation_jitter: 0.0, + brightness_jitter: 0.0, modes: Some([Variation::Random, Variation::Fixed, Variation::Pressure, Variation::Random]), }), }, @@ -10510,6 +10512,36 @@ fn a_scatter_brush_with_hue_jitter_is_left_out() { assert_eq!(back.iter().map(|b| b.name.as_str()).collect::>(), ["Nib", "Ribbon", "Plain ribbon"]); } +/// Nor its saturation jitter: such a brush is left out and reported too. +#[test] +fn a_scatter_brush_with_saturation_jitter_is_left_out() { + use vectorcraft_brush::BrushKind; + let mut lib = brush_library(); + let BrushKind::Scatter(s) = &mut lib[1].kind else { panic!("scatter") }; + s.saturation_jitter = 30.0; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back = vectorcraft_brush::library(&read_back(&doc)); + assert_eq!(back.iter().map(|b| b.name.as_str()).collect::>(), ["Nib", "Ribbon", "Plain ribbon"]); +} + +/// Nor its brightness jitter: such a brush is left out and reported too. +#[test] +fn a_scatter_brush_with_brightness_jitter_is_left_out() { + use vectorcraft_brush::BrushKind; + let mut lib = brush_library(); + let BrushKind::Scatter(s) = &mut lib[1].kind else { panic!("scatter") }; + s.brightness_jitter = 30.0; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back = vectorcraft_brush::library(&read_back(&doc)); + assert_eq!(back.iter().map(|b| b.name.as_str()).collect::>(), ["Nib", "Ribbon", "Plain ribbon"]); +} + /// An Art brush's options, without its art. #[derive(Debug, PartialEq)] struct ArtBrushOptions(serde_json::Value); @@ -10841,6 +10873,8 @@ fn more_brush_settings_are_read_back() { rotation_relative_to_path: false, colorization: Colorization::None, hue_jitter: 0.0, + saturation_jitter: 0.0, + brightness_jitter: 0.0, modes: Some([Variation::Tilt, Variation::Bearing, Variation::Fixed, Variation::Rotation]), }; let lib = vec![ diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 3c9ce44a77..b6941e4730 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -634,7 +634,7 @@ fn font_name(st: &CharStyle) -> FontRecord { .collect(); let name = face.postscript_name(); // The reader takes the face of a name alone as `postscript_face` finds it. - let by_name = crate::import::postscript_face(&name, None).is_some_and(|f| f.id() == face.id()); + let by_name = crate::import::postscript_face(&name, None, None).is_some_and(|f| f.id() == face.id()); let version = if design.is_empty() && by_name { String::new() } else { face.version.clone() }; FontRecord { name, truetype: face.is_truetype(), design, version } } @@ -681,7 +681,7 @@ fn fixed(v: f32) -> i64 { fn font_kept(st: &CharStyle) -> bool { let record = font_name(st); let version = crate::import::record_version(&record.version); - let (family, style, read) = crate::import::document_font(&record.name, version); + let (family, style, read) = crate::import::document_font(&record.name, version, None); let db = vectorcraft_text::FontDb::global(); let face = |family: &str, style: &str, version: Option<&str>| db.face_version(family, style, version).map(|f| f.id()); family == st.font_family diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 38fba94616..6c85414463 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -103,7 +103,10 @@ pub(crate) use ai::{ parsed_type_color, read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number, }; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; -pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; +pub use native::{ + AiLayers, ai_alone, ai_alone_decoded, ai_alone_on_page, ai_alone_on_page_decoded, ai_alone_with, ai_layers_alone, ai_layers_alone_decoded, + ai_opened_artboard, ai_opened_artboard_decoded, decode_ai_private, is_loss, layered_ai, layered_ai_from, +}; pub(crate) use native::{MAX_TEXT, MAX_WRAP_WORK, scale_document, scale_symbols}; pub use text::family_style; pub(crate) use text::{document_font, postscript_face}; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 525eb71f22..a87bbe470c 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -6,8 +6,8 @@ //! `%AI24_DataStream` (Zstandard) or `%AI9_DataStream` (zlib) and the compressed data as ASCII85 //! on comment lines, up to `%AI9_PrivateDataEnd`. Data that isn't compressed follows the header //! as it is. -//! - In a `.ai` file the streams joined start with `%AI24_ZStandard_Data` (Zstandard) or -//! `%AI12_CompressedData` (zlib), else are the data itself ([`decode_private`]). +//! - In a `.ai` file the streams, read one after the other, start with `%AI24_ZStandard_Data` +//! (Zstandard) or `%AI12_CompressedData` (zlib), else are the data itself ([`decode_private_from`]). //! //! The data is a PostScript-like program of the legacy Illustrator format's operators (layers, //! groups, paths, colours, gradients, images) with newer ones (transparency, hidden objects) and @@ -174,25 +174,89 @@ fn eps_section(section: &[u8]) -> Result, String> { } let packed = ps::ascii85_decode(&text).ok_or_else(|| damaged("its ASCII85 encoding"))?; let mut data = header; - data.extend(codec.decode(&packed, max_data().saturating_sub(data.len() as u64))?); + data.extend(codec.decode(packed.as_slice(), max_data().saturating_sub(data.len() as u64))?); Ok(data) } -/// The editing data of a `.ai` file: its `AIPrivateData` streams joined (`raw`), decompressed. The -/// compressed data may follow header comments that aren't. +/// The markers the compressed editing data of a `.ai` file follows, with its compression. +const PRIVATE_MARKERS: [(&[u8], Codec); 2] = [(b"%AI24_ZStandard_Data", Codec::Zstd), (b"%AI12_CompressedData", Codec::Zlib)]; + +/// The editing data of a `.ai` file: its `AIPrivateData` streams joined (`raw`), decompressed, as +/// [`decode_private_from`] reads them. pub fn decode_private(raw: &[u8]) -> Result, String> { - if raw.len() as u64 > max_data() { + decode_private_from(raw) +} + +/// The editing data of a `.ai` file, read from its `AIPrivateData` streams one after the other +/// (`raw`) and decompressed as it is read: the streams are never joined in memory. The compressed +/// data follows the first [`PRIVATE_MARKERS`] marker, which may follow header comments that aren't +/// compressed; without a marker the streams are the data itself. The data decompresses to at most +/// [`max_data`] bytes, and at most [`max_encoded`] bytes are read from `raw`. +pub fn decode_private_from(raw: impl std::io::Read) -> Result, String> { + decode_private_within(raw, max_encoded()) +} + +/// [`decode_private_from`], reading at most `most` bytes of `raw`. +fn decode_private_within(raw: impl std::io::Read, most: u64) -> Result, String> { + let mut counted = Counted { inner: raw.take(most + 1), read: 0 }; + let data = private_from(&mut counted); + if counted.read > most { return Err(too_large()); } - for (marker, codec) in [(&b"%AI24_ZStandard_Data"[..], Codec::Zstd), (b"%AI12_CompressedData", Codec::Zlib)] { - if let Some(at) = find(raw, marker) { - let (header, body) = raw.split_at(at); - let mut data = header.to_vec(); - data.extend(codec.decode(body.get(marker.len()..).unwrap_or_default(), max_data().saturating_sub(header.len() as u64))?); + data +} + +/// Most bytes of a `.ai` file's editing data streams read ([`decode_private_from`]): [`max_data`] +/// and a sixteenth more. Compressed data that decompresses to at most [`max_data`] bytes takes no +/// more than that: the compression's own block headers add a few bytes in 64 KiB, and only zero +/// padding or blocks that hold nothing would go past it. +fn max_encoded() -> u64 { + max_data().saturating_add(max_data() >> 4) +} + +/// [`decode_private_from`] of `raw`, with no limit on what it reads of `raw`. +fn private_from(raw: impl std::io::Read) -> Result, String> { + use std::io::BufRead as _; + let longest = PRIVATE_MARKERS.iter().map(|(m, _)| m.len()).max().unwrap_or(0); + let mut src = std::io::BufReader::with_capacity(64 << 10, raw); + let mut data = Vec::new(); + loop { + let buf = src.fill_buf().map_err(|e| e.to_string())?; + if buf.is_empty() { return Ok(data); } + let (read, from) = (buf.len(), data.len().saturating_sub(longest - 1)); + data.extend_from_slice(buf); + src.consume(read); + let tail = data.get(from..).unwrap_or_default(); + let marker = PRIVATE_MARKERS.iter().filter_map(|&(m, codec)| Some((from + find(tail, m)?, m.len(), codec))).min_by_key(|&(at, ..)| at); + if let Some((at, len, codec)) = marker { + if at as u64 > max_data() { + return Err(too_large()); + } + let body = data.split_off(at + len); + data.truncate(at); + data.extend(codec.decode(std::io::Cursor::new(body).chain(src), max_data() - at as u64)?); + return Ok(data); + } + if data.len() as u64 > max_data() { + return Err(too_large()); + } + } +} + +/// A reader that counts the bytes read from `inner`. +struct Counted { + inner: R, + read: u64, +} + +impl std::io::Read for Counted { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = self.inner.read(buf)?; + self.read = self.read.saturating_add(n as u64); + Ok(n) } - Ok(raw.to_vec()) } #[derive(Clone, Copy)] @@ -203,7 +267,8 @@ enum Codec { impl Codec { /// `data` decompressed, at most `max` bytes. - fn decode(self, data: &[u8], max: u64) -> Result, String> { + fn decode(self, data: impl std::io::Read, max: u64) -> Result, String> { + use std::io::BufRead as _; let mut out = Vec::new(); match self { Codec::Zlib => { @@ -212,24 +277,44 @@ impl Codec { Codec::Zstd => { // The data may be several frames one after the other, padded with zeros. A frame // can itself end in a zero byte, so the padding is what is left after the last frame. - let mut src = data; + let zstd_damaged = || damaged("its Zstandard compression"); + let mut src = std::io::BufReader::new(data); let mut frames = 0usize; - while src.iter().any(|b| { - #[cfg(test)] - PADDING_LOOKS.set(PADDING_LOOKS.get().saturating_add(1)); - *b != 0 - }) { + loop { + // Zeros before a frame aren't padding: the frame that would start there is damaged. + let mut after_zeros = false; + loop { + let buf = src.fill_buf().map_err(|_| zstd_damaged())?; + let Some(&first) = buf.first() else { break }; + #[cfg(test)] + PADDING_LOOKS.set(PADDING_LOOKS.get().saturating_add(1)); + if first != 0 { + break; + } + let zeros = buf.iter().position(|b| *b != 0); + #[cfg(test)] + PADDING_LOOKS.set(PADDING_LOOKS.get().saturating_add(zeros.unwrap_or(buf.len()) as u64)); + // (Zeros that end a buffer may go on in the next one, or end the data.) + after_zeros = true; + let n = zeros.unwrap_or(buf.len()); + src.consume(n); + } + if src.fill_buf().map_err(|_| zstd_damaged())?.is_empty() { + break; + } frames += 1; if frames > MAX_FRAMES { - return Err(damaged("its Zstandard compression")); + return Err(zstd_damaged()); } let left = (max + 1).saturating_sub(out.len() as u64); if left == 0 { break; } - let d = ruzstd::decoding::StreamingDecoder::new_with_max_window_size(&mut src, MAX_ZSTD_WINDOW) - .map_err(|_| damaged("its Zstandard compression"))?; - d.take(left).read_to_end(&mut out).map_err(|_| damaged("its Zstandard compression"))?; + if after_zeros { + return Err(zstd_damaged()); + } + let d = ruzstd::decoding::StreamingDecoder::new_with_max_window_size(&mut src, MAX_ZSTD_WINDOW).map_err(|_| zstd_damaged())?; + d.take(left).read_to_end(&mut out).map_err(|_| zstd_damaged())?; } } } diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index a3864b43d0..e35f61cb54 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -564,7 +564,7 @@ impl Reader<'_> { st.cmap = cmap; // The installed face of that PostScript name, as type from a text document // takes it; else the name split into a family and style. - let text = super::super::super::text::named_font(name, None); + let text = super::super::super::text::named_font(name, None, None); let (family, style, version) = text.unwrap_or_else(|| { let (family, style) = super::super::super::text::family_style(name); (family, style, None) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index dc757b1462..17d9896ab9 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -236,6 +236,10 @@ pub struct Structure { /// placed in the document, or a color linked to its swatch at its tint (see /// `ate::Texts::with_paints`). pub text_paints: HashMap, + /// The widths a `.ai`'s PDF part gives the characters of its fonts, which tell installed copies + /// of a font apart for type whose font record keeps no version (see + /// `ate::Texts::with_page_widths`): none until the importer sets them. + pub page_widths: vectorcraft_pdf::PageWidths, /// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not. pub canvas_scale: f64, /// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 9621e7a9b0..20102b29c4 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1481,6 +1481,7 @@ impl<'a> Reader<'a> { }, styles_read, text_paints, + page_widths: Default::default(), canvas_scale: self.canvas_scale, symbols_own_size: self.symbols_own_size, xml_ids: self.xml_ids, diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 9e309bc458..28e31e52c6 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -6618,6 +6618,72 @@ fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() { } } +/// A reader that gives at most `.1` bytes of `.0` at a time, as private data streams read one after +/// the other give them. +struct Trickle<'a>(&'a [u8], usize); + +impl std::io::Read for Trickle<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = buf.len().min(self.1).min(self.0.len()); + let (now, rest) = self.0.split_at(n); + buf[..n].copy_from_slice(now); + self.0 = rest; + Ok(n) + } +} + +/// The editing data decoded as it is read gives what decoding it whole gives, whatever the size of +/// the reads: the compression's marker, its header and its frames may be split between them. +#[test] +fn editing_data_decoded_as_it_is_read_is_the_data_decoded_whole() { + let body = stream(&layer("")); + let body = body.as_bytes(); + let header = b"%%BoundingBox: 0 0 1 1\r\n"; + let frame = [0x28, 0xB5, 0x2F, 0xFD, 0x20, 3, 0x19, 0, 0, b'a', b'b', 0]; + for raw in [ + [&b"%AI24_ZStandard_Data"[..], &zstd(body)].concat(), + [&header[..], b"%AI12_CompressedData", &crate::ps::deflate(body)].concat(), + [&b"%AI24_ZStandard_Data"[..], &frame, &frame, &[0; 64]].concat(), + body.to_vec(), + ] { + let whole = decode_private(&raw).unwrap(); + for step in [1, 3, 7, 19, 64 << 10] { + assert_eq!(decode_private_from(Trickle(&raw, step)).unwrap(), whole, "{step} bytes at a time"); + } + } + let zeros_between = [&b"%AI24_ZStandard_Data"[..], &frame, &[0; 4], &frame].concat(); + for damaged in [&b"%AI12_CompressedDataxx"[..], &zeros_between] { + assert!(decode_private(damaged).is_err()); + for step in 1..=damaged.len() { + assert!(decode_private_from(Trickle(damaged, step)).is_err(), "{step} bytes at a time"); + } + } +} + +/// The first marker read is the one the compressed data follows: the other marker's bytes after it +/// are not a marker. +#[test] +fn editing_data_is_decoded_after_the_first_marker() { + let body = stream(&layer("")); + let mut raw = [&b"%AI12_CompressedData"[..], &crate::ps::deflate(body.as_bytes())].concat(); + let data = decode_private(&raw).unwrap(); + // Bytes after the end of the zlib data aren't read. + raw.extend_from_slice(b"%AI24_ZStandard_Data"); + assert_eq!(decode_private(&raw).unwrap(), data); +} + +/// Of the editing data's streams, no more is read than the limit: data that goes on past it is +/// refused as too large, even where all it holds past the limit is zero padding. +#[test] +fn no_more_of_the_private_data_streams_is_read_than_the_limit() { + let frame = [0x28, 0xB5, 0x2F, 0xFD, 0x20, 3, 0x19, 0, 0, b'a', b'b', 0]; + let raw = [&b"%AI24_ZStandard_Data"[..], &frame, &[0; 100]].concat(); + let most = raw.len() as u64; + assert_eq!(decode_private_within(raw.as_slice(), most).unwrap(), b"ab\0"); + assert_eq!(decode_private_within(raw.as_slice(), most - 1), Err(too_large())); + assert_eq!(max_encoded(), max_data() + max_data() / 16); +} + /// A `]` without its `[` looks at a few operand stack slots, not at every slot below it: hundreds /// of thousands of them look at no more than four slots each. #[test] diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index a4c32b092b..3fb4393b19 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -23,6 +23,7 @@ //! a layout has its point type's anchor at its frame's point. See [`Story::place`]. use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen}; use vectorcraft_color::{Color, Paint}; @@ -581,15 +582,20 @@ struct DocFont { /// Key 5, when the record keeps it: the font's version string (name ID 5), which tells installed /// copies of one font apart. version: Option, - /// [`Self::font`]'s answer, found once for every run that names the record. - font: std::sync::OnceLock, + /// The widths the file's page gives the font's characters, when it has them + /// ([`Texts::with_page_widths`]): without a version, they tell the copies apart. Every record + /// of the font shares them. + widths: Option>, + /// [`Self::font`]'s answer, found once for every run that names the record, and shared by the + /// records of the same name and version, which give the same answer. + font: Arc>, } impl DocFont { /// The font type set in this record's font takes: the installed copy it names /// ([`super::text::document_font`]). fn font(&self) -> &Font { - self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref())) + self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref(), self.widths.as_deref())) } } @@ -639,6 +645,17 @@ impl Texts { Texts { paints, ..self } } + /// The text document with the widths `page` (the file's page, [`vectorcraft_pdf::PageWidths`]) + /// gives the characters of its fonts, by each record's PostScript name: a record that keeps no + /// version is set in the installed copy of its font that sets them at those widths + /// ([`super::text::postscript_face`]). + pub(super) fn with_page_widths(mut self, page: &vectorcraft_pdf::PageWidths) -> Texts { + for f in &mut self.fonts { + f.widths = page.widths(super::text::bare_name(&f.name)).cloned(); + } + self + } + /// The text document in the editing copy `data`, if it has one that can be read. pub(super) fn read(data: &[u8]) -> Option { fn find(h: &[u8], n: &[u8], from: usize) -> Option { @@ -666,6 +683,8 @@ impl Texts { return None; } let doc = names::numbered(read(&bytes)?); + // Records of one name and version share their answer. + let mut answers: HashMap<(String, Option), Arc>> = HashMap::new(); let fonts = doc .get("0")? .get("1")? @@ -675,11 +694,10 @@ impl Texts { .map(|f| { let record = f.get("0").and_then(|f| f.get("0")); let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str); - DocFont { - name: text("0").unwrap_or_default().to_string(), - version: text("5").and_then(record_version).map(str::to_string), - font: std::sync::OnceLock::new(), - } + let name = text("0").unwrap_or_default().to_string(); + let version = text("5").and_then(record_version).map(str::to_string); + let font = answers.entry((name.clone(), version.clone())).or_default().clone(); + DocFont { name, version, widths: None, font } }) .collect(); let main = doc.get("1")?; @@ -1653,6 +1671,40 @@ fn art_scale(to_doc: Affine) -> f64 { mod tests { use super::*; + /// The records of a text document's font list that name one font share the widths the file's + /// page gives it and the face they resolve to, however many there are: 20,000 records of a font + /// whose page gives 4,096 characters hold one copy of those widths, and resolve once. A record + /// of another version is resolved apart. + #[test] + fn records_of_one_font_share_its_page_widths_and_answer() { + let n = 20_000; + let records = "<< /0 << /0 << /0 (Sharetest-Regular) >> >> >> ".repeat(n) + "<< /0 << /0 << /0 (Sharetest-Regular) /5 (2.0) >> >> >>"; + let doc = format!("/0 << /1 << /0 [ {records} ] >> /8 << /0 [ ] >> >>\n/1 << /1 [ ] /2 << >> >>\n"); + let data = + format!("%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", crate::ps::ascii85(doc.as_bytes())); + let mut cmap = String::from("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n16 beginbfrange\n"); + for hi in 1..=16u32 { + cmap.push_str(&format!("<{hi:02X}00> <{hi:02X}FF> <{hi:02X}00>\n")); + } + cmap.push_str("endbfrange\nendcmap\n"); + let extra = vectorcraft_testkit::pdf::first_extra(1); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+Sharetest-Regular /Encoding /Identity-H /ToUnicode {extra} 0 R \ + /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+Sharetest-Regular /W [256 4351 500] >>] >> >>" + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + let pdf = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None); + let widths = vectorcraft_pdf::open_pdf(&pdf, None).unwrap().page_widths(); + let shared = widths.widths("Sharetest-Regular").unwrap(); + assert_eq!(shared.len(), 4096); + let texts = Texts::read(data.as_bytes()).unwrap().with_page_widths(&widths); + assert_eq!(texts.fonts.len(), n + 1); + assert!(texts.fonts.iter().all(|f| f.widths.as_ref().is_some_and(|w| Arc::ptr_eq(w, shared)))); + let first = &texts.fonts[0].font; + assert!(texts.fonts[..n].iter().all(|f| Arc::ptr_eq(&f.font, first))); + assert!(texts.fonts.last().is_some_and(|f| !Arc::ptr_eq(&f.font, first)), "another version resolves apart"); + } + #[test] fn right_to_left_paragraphs_swap_left_and_right_alignment() { let texts = Texts { diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index df97114506..a8146e679e 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -58,7 +58,10 @@ pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols}; use compare::{ MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour, }; -pub use layers::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, layered_ai, layered_ai_from}; +pub use layers::{ + AiLayers, ai_alone, ai_alone_decoded, ai_alone_on_page, ai_alone_on_page_decoded, ai_alone_with, ai_layers_alone, ai_layers_alone_decoded, + ai_opened_artboard, ai_opened_artboard_decoded, decode_ai_private, layered_ai, layered_ai_from, +}; pub(super) use layers::{layered, program_alone}; pub(crate) use slots::MAX_TEXT; pub use slots::is_loss; diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index d5d7dbc1c8..5b0eb51a73 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -178,17 +178,25 @@ impl ReadText { self.frames.get_or_insert_with(|| ai::text_frames(data)) } - /// The text document of `data` ([`Texts::read`]), if it has one that can be read. - fn texts(&mut self, data: &[u8]) -> Option<&Texts> { + /// The text document of `data` ([`Texts::read`]), if it has one that can be read, with the widths + /// `page_widths` the file's page gives its fonts ([`Texts::with_page_widths`]). They are given + /// when it is first read, before any of its fonts is found: each is found once, with the widths + /// it has then. Every check and build of one open passes the same widths. + fn texts(&mut self, data: &[u8], page_widths: &vectorcraft_pdf::PageWidths) -> Option<&Texts> { self.forget_in_tests(); - self.texts.get_or_insert_with(|| Texts::read(data)).as_ref() + self.texts.get_or_insert_with(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))).as_ref() } /// [`Self::texts`] with its characters painted by `paints` ([`Texts::with_paints`]). - fn texts_with(&mut self, data: &[u8], paints: std::collections::HashMap) -> Option<&Texts> { + fn texts_with( + &mut self, + data: &[u8], + paints: std::collections::HashMap, + page_widths: &vectorcraft_pdf::PageWidths, + ) -> Option<&Texts> { self.forget_in_tests(); - let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_paints(paints)); - self.texts.insert(texts).as_ref() + let read = self.texts.take().unwrap_or_else(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))); + self.texts.insert(read.map(|t| t.with_paints(paints))).as_ref() } } @@ -217,7 +225,7 @@ fn type_all_made(structure: &Structure, data: &[u8], text: &mut ReadText) -> boo for info in &mut infos { info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(structure.to_doc * p.clone()))); } - let Some(texts) = text.texts(data) else { return false }; + let Some(texts) = text.texts(data, &structure.page_widths) else { return false }; let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos .iter() @@ -338,6 +346,7 @@ pub(super) fn build_weighing( envelopes_drawn, styles_read, text_paints, + page_widths, canvas_scale, symbols_own_size, xml_ids, @@ -498,7 +507,7 @@ pub(super) fn build_weighing( // The page's type that needs no text object of the layers: the layers' own legacy text, or // placed files that show it. let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; - let texts = text.texts_with(data, text_paints); + let texts = text.texts_with(data, text_paints, &page_widths); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index d46da2b8ff..bbbacc1c4b 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -149,7 +149,7 @@ pub fn layered_ai_from( all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part")); all }; - let AiLayers { data, structure, alone, mut text } = layers; + let AiLayers { data, structure, alone, mut text, page_widths } = layers; let data = match data { Ok(data) => data, Err(why) => return (visible, unread(warnings, &why), false), @@ -189,10 +189,17 @@ pub fn layered_ai_from( add_notes(&mut all, read.notes()); (visible, all, false) }; + // The layers read, with the widths the PDF part gives the characters of its fonts. + let read = || { + ai::read_over_page(&data, false, names).map(|mut structure| { + structure.page_widths = page_widths.clone(); + structure + }) + }; // The envelopes of type the page doesn't hold against layers that don't draw as it, and how many // envelopes of type the layers had. let (mut free, mut count) = (None, 0); - let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| { + let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| { count = structure.warped_type.envelope_count(); build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text) }); @@ -205,7 +212,7 @@ pub fn layered_ai_from( let live = free.is_none() && matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers)); if !live && let Some((mut done, notes)) = alone.and_then(|(pages, unit)| { - let mut structure = ai::read_over_page(&data, false, names).ok()?; + let mut structure = read().ok()?; // With none free, nothing needs settling again: every envelope keeps its drawn art. if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) { structure.warped_type.open_alone(free, count); @@ -244,32 +251,53 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { /// reading it, when the file's text document makes all of its type and nothing in its layers needs /// the PDF part (see `build_without_page`). Nothing is compared with the PDF part. Else, as the /// error, what was decoded and read of the editing copy, for [`layered_ai_from`] once the PDF part -/// is imported. `names`: the encoding of names that aren't UTF-8. -pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec), AiLayers> { - let data = match ai::decode_private(private) { +/// is imported. `names`: the encoding of names that aren't UTF-8. `page_widths`: the widths the +/// PDF part gives the characters of its fonts, which tell installed copies of a font apart +/// ([`AiLayers::with_page_widths`]). +pub fn ai_layers_alone( + private: &[u8], + pages: &[(f64, f64)], + unit: f64, + names: ai::NameEncoding, + page_widths: vectorcraft_pdf::PageWidths, +) -> Result<(Document, Vec), AiLayers> { + ai_layers_alone_decoded(ai::decode_private(private), pages, unit, names, page_widths) +} + +/// [`ai_layers_alone`] of an editing copy already decoded (`decoded`, as [`decode_ai_private`] +/// gives it, or why it can't be). +pub fn ai_layers_alone_decoded( + decoded: Result, String>, + pages: &[(f64, f64)], + unit: f64, + names: ai::NameEncoding, + page_widths: vectorcraft_pdf::PageWidths, +) -> Result<(Document, Vec), AiLayers> { + let data = match decoded { Ok(data) => data, - Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default() }), + Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default(), page_widths }), }; if !has_layers(&data) { - return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default() }); + return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default(), page_widths }); } // An image past the hard limits is read as an unread box, which the PDF part's art replaces. - let structure = match ai::read_over_page(&data, false, names) { + let mut structure = match ai::read_over_page(&data, false, names) { Ok(structure) => structure, - Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default() }), + Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default(), page_widths }), }; + structure.page_widths = page_widths.clone(); let mut text = Box::::default(); // An envelope of type opens live only where the layers with it draw as the page, as the other // live envelopes do: the PDF part is imported to compare them with. Should none open live, the // layers open alone as they would have, the envelopes keeping their drawn art ([`layered_ai_from`]). if structure.warped_type.has_envelopes() && alone_scale(&structure, &data, pages, unit, &mut text).is_some() { let alone = Some((pages.to_vec(), unit)); - return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text }); + return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text, page_widths }); } match build_without_page(structure, &data, pages, unit, &mut text) { Ok(Ok((doc, notes))) => Ok((doc, notes)), - Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text }), - Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text }), + Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text, page_widths }), + Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text, page_widths }), } } @@ -286,13 +314,41 @@ pub struct AiLayers { alone: Option<(Vec<(f64, f64)>, f64)>, /// The text objects' frames and the text document of the editing copy, as far as they were read. text: Box, + /// The widths the PDF part gives the characters of its fonts ([`Self::with_page_widths`]). + page_widths: vectorcraft_pdf::PageWidths, } impl AiLayers { /// The editing copy `private` (as [`layered_ai`] takes it), decoded. pub fn decode(private: &[u8]) -> Self { - Self { data: ai::decode_private(private), structure: None, alone: None, text: Box::default() } + Self::decoded(ai::decode_private(private)) } + + /// An editing copy already decoded (`decoded`, as [`decode_ai_private`] gives it, or why it + /// can't be). + pub fn decoded(decoded: Result, String>) -> Self { + Self { data: decoded, structure: None, alone: None, text: Box::default(), page_widths: Default::default() } + } + + /// The editing copy with `page_widths`, the widths the file's PDF part gives the characters of + /// its fonts ([`vectorcraft_pdf::Opened::page_widths`]): type whose font record keeps no + /// version is set in the installed copy of its font that sets them at those widths, where + /// several copies answer to its name. The layers read before take them too, and a text document + /// read before is read again with them, since its fonts are found once, with the widths they had + /// then. + pub fn with_page_widths(mut self, page_widths: vectorcraft_pdf::PageWidths) -> Self { + if let Some(Ok(structure)) = &mut self.structure { + structure.page_widths = page_widths.clone(); + } + Self { page_widths, text: Box::default(), ..self } + } +} + +/// A `.ai`'s editing copy read from its `AIPrivateData` or `AIPDFPrivateData` streams one after the +/// other (`private`), decoded as it is read: the streams aren't joined first, so they are under the +/// limits of the decoded data alone. +pub fn decode_ai_private(private: impl std::io::Read) -> Result, String> { + ai::decode_private_from(private) } /// The id of the artboard of `doc` that the editing copy `private` (as [`layered_ai`] takes it) @@ -300,8 +356,13 @@ impl AiLayers { /// restored from the document a `.ai` file carries beside that copy: `None` when the copy names /// the first artboard, names none, can't be decoded, or names an artboard `doc` doesn't have. pub fn ai_opened_artboard(private: &[u8], doc: &Document) -> Option { - let data = ai::decode_private(private).ok()?; - active_page(ai::active_artboard(&data), doc) + ai_opened_artboard_decoded(&ai::decode_private(private).ok()?, doc) +} + +/// [`ai_opened_artboard`] of an editing copy already decoded (`data`, as [`decode_ai_private`] +/// gives it). +pub fn ai_opened_artboard_decoded(data: &[u8], doc: &Document) -> Option { + active_page(ai::active_artboard(data), doc) } /// `doc` (a file read as its page or PDF part, in place of its layers) with the variables, data @@ -581,13 +642,21 @@ fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) { /// Editing data written on a large canvas comes in at its declared scale: no page holds the size. /// Names that aren't UTF-8 are read as Windows-1252 ([`ai_alone_with`]). pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec), String> { - ai_alone_with(private, ai::NameEncoding::default()) + ai_alone_with(private, ai::NameEncoding::default(), Default::default()) } -/// [`ai_alone`], with the names that aren't UTF-8 read in `names`. -pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec), String> { - let data = ai::decode_private(private)?; - build_from(ai::read_in(&data, true, names)?, &data, None, Page::Artboard, false, false, 1.0) +/// [`ai_alone`], with the names that aren't UTF-8 read in `names`, and `page_widths`, the widths the +/// file's PDF part gives the characters of its fonts when it has one that holds the art +/// ([`AiLayers::with_page_widths`]). +pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec), String> { + ai_alone_decoded(&ai::decode_private(private)?, names, page_widths) +} + +/// [`ai_alone_with`] of an editing copy already decoded (`data`, as [`decode_ai_private`] gives it). +pub fn ai_alone_decoded(data: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec), String> { + let mut structure = ai::read_in(data, true, names)?; + structure.page_widths = page_widths; + build_from(structure, data, None, Page::Artboard, false, false, 1.0) } /// [`ai_alone`] for a `.ai` whose PDF part can't be read, its first page `page` (width and height) @@ -596,8 +665,13 @@ pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding) -> Result<(Documen /// large, as [`layered_ai`] reads it. A page turned a quarter (`/Rotate 90`) is measured either /// way round. `names`: the encoding of names that aren't UTF-8. pub fn ai_alone_on_page(private: &[u8], page: (f64, f64), unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec), String> { - let data = ai::decode_private(private)?; - build_on_page(&data, page, unit, names) + ai_alone_on_page_decoded(&ai::decode_private(private)?, page, unit, names) +} + +/// [`ai_alone_on_page`] of an editing copy already decoded (`data`, as [`decode_ai_private`] gives +/// it). +pub fn ai_alone_on_page_decoded(data: &[u8], page: (f64, f64), unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec), String> { + build_on_page(data, page, unit, names) } /// Does the editing data (or a program in the legacy format) have layers? diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index e55d2fe4da..2d8d270cc7 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3452,6 +3452,105 @@ fn type_from_the_text_document_takes_the_version_its_font_record_keeps() { assert_eq!(version("/0 (VertestInk-Regular) /VersionString (1.1)"), "1.1"); } +/// The widths a `.ai`'s PDF part gives the characters of `text` in its font `name` (a subset of +/// it, a TrueType font in `WinAnsiEncoding`): those `width` gives each, in thousandths of an em. +fn page_widths(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths { + let widths: Vec = (32u8..=126).map(char::from).map(|c| if text.contains(c) { width(c).to_string() } else { "0".into() }).collect(); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>", + widths.join(" ") + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + vectorcraft_pdf::open_pdf(&vectorcraft_testkit::pdf::pdf_with(&[page], &[], None), None).unwrap().page_widths() +} + +/// [`page_widths`] of a composite font (`Identity-H`, a TrueType CIDFont) whose `ToUnicode` map gives +/// CID 1 the first character of `text`, CID 2 the next and so on, `W` their widths. +fn page_widths_cid(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths { + let chars: Vec = text.chars().collect(); + let pairs: Vec = chars.iter().enumerate().map(|(i, c)| format!("<{:04X}> <{:04X}>", i + 1, u32::from(*c))).collect(); + let cmap = format!( + "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n{} beginbfchar\n{}\nendbfchar\nendcmap\n", + pairs.len(), + pairs.join("\n") + ); + let w: Vec = chars.iter().map(|c| width(*c).to_string()).collect(); + let extra = vectorcraft_testkit::pdf::first_extra(1); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+{name}-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \ + /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+{name} /W [1 [{}]] >>] >> >>", + w.join(" ") + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + let file = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None); + vectorcraft_pdf::open_pdf(&file, None).unwrap().page_widths() +} + +/// The advance of `c` in installed `face`, in thousandths of an em. +fn advance(face: &vectorcraft_text::FontFace, c: char) -> f64 { + face.advance(face.glyph_for(c)) * 1000.0 / face.units_per_em() +} + +/// The version of the face that type from the text document of a `.ai` whose font record is +/// `record` (in place of `/0 (Helvetica)`) is set in, its layers read alone with `widths`, the +/// widths its PDF part gives the characters of its fonts. +fn version_on_page(record: &str, widths: vectorcraft_pdf::PageWidths) -> String { + let doc = text_document(&[("Hamburg\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]).replacen("/0 (Helvetica)", record, 1); + let file = private(&native_with_text(&layer("Art", true, &text_object(0)), &doc)); + let names = crate::NameEncoding::default(); + let Ok((d, notes)) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, widths) else { panic!("{record}: opened with the page") }; + let texts = text_of(&d.layers[0]); + assert_eq!(texts.len(), 1, "{record}: {notes:?}"); + vectorcraft_text::FontDb::global().style_face(&texts[0].runs[0].style).unwrap().version.clone() +} + +/// Two installed copies of one font can share its PostScript name, family and style, and differ +/// in their glyphs' widths alone. Type from the text document of a `.ai` whose font record keeps no +/// version is set in the copy that sets the characters its PDF part draws at the widths the PDF +/// part gives them, also when the record spells the name with other punctuation. Without those +/// widths, or when no copy sets the characters at them, it takes the copy it took before (the first +/// loaded); a version the record keeps decides first. The widths of a simple font in +/// `WinAnsiEncoding` and of a composite font with a `ToUnicode` map both tell the copies apart. +#[test] +fn type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths() { + install(&[(true, ("Widtest Ink", "Regular", "1.0", "WidtestInk-Regular")), (false, ("Widtest Ink", "Regular", "1.1", "WidtestInk-Regular"))]); + let copies = vectorcraft_text::FontDb::global().postscript_faces("WidtestInk-Regular"); + let copy = |version: &str| copies.iter().find(|f| f.version == version).unwrap().clone(); + let (old, new) = (copy("1.0"), copy("1.1")); + assert!((advance(&old, 'H') - advance(&new, 'H')).abs() > 10.0, "the copies set the type at other widths"); + let on = |name: &str, face: &vectorcraft_text::FontFace| page_widths(name, "Hamburg", |c| advance(face, c)); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", Default::default()), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &new)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &old)), "1.0"); + // Widths a file rounds are within 1/1000 em of the advances; farther off, they aren't the copy's. + let off = |by: f64| page_widths("WidtestInk-Regular", "Hamburg", |c| advance(&new, c) + by); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(0.9)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(-0.9)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(2.0)), "1.0"); + // A record whose name differs from the copies' in punctuation alone, as its PDF part's font. + assert_eq!(version_on_page("/0 (Widtest-Ink-Regular)", on("Widtest-Ink-Regular", &new)), "1.1"); + // Widths of another font, or no copy setting the characters at the PDF part's widths. + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("OtherInk-Regular", &new)), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths("WidtestInk-Regular", "Hamburg", |_| 1000.0)), "1.0"); + // A version the record keeps picks the copy, and one that isn't installed gives the copy it gave. + assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (1.0)", on("WidtestInk-Regular", &new)), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (9.9)", on("WidtestInk-Regular", &new)), "1.0"); + // The widths of a composite font. + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&new, c))), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&old, c))), "1.0"); + // A font installed once is set in that copy whatever the widths. + install(&[(true, ("Onewtest Ink", "Regular", "1.0", "OnewtestInk-Regular"))]); + assert_eq!(version_on_page("/0 (OnewtestInk-Regular)", on("OnewtestInk-Regular", &new)), "1.0"); + // Of several copies that set the characters at the widths, the first in the order the faces + // are found (the first loaded). + install(&[ + (true, ("Firstwtest Ink", "Regular", "1.0", "FirstwtestInk-Regular")), + (false, ("Firstwtest Ink", "Regular", "1.1", "FirstwtestInk-Regular")), + (false, ("Firstwtest Ink", "Regular", "1.2", "FirstwtestInk-Regular")), + ]); + assert_eq!(version_on_page("/0 (FirstwtestInk-Regular)", on("FirstwtestInk-Regular", &new)), "1.1"); +} + /// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character /// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large /// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point @@ -6490,7 +6589,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; // A PDF part the layers don't draw as. let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, false, 1.0, names); assert!(read, "{notes:?}"); @@ -6499,7 +6598,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { assert_eq!(loose, [("Note".to_string(), true), ("FLUX".to_string(), false)], "{notes:?}"); assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}"); // A PDF part that draws as those layers, with the drawn art: the envelope opens live. - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; let (d, notes, read) = crate::layered_ai_from(layers, d, vec![], false, false, 1.0, names); assert!(read, "{notes:?}"); let (envelopes, loose) = envelopes_and_type(&d); @@ -6527,7 +6626,7 @@ fn layers_that_open_alone_read_their_text_once() { let doc = unsplit_text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Mid\r", 2, (8191.5, 8191.5), (0.0, 0.0), -10.0)]); let art = layer("Art", true, &format!("{}\n{}{}", square(10, 10), text_object(0), text_object(1))); let file = private(&native_with_text(&art, &doc)); - let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default()).ok(); + let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default(), Default::default()).ok(); let (opened, texts, frames) = text_reads(false, open); let Some((d, notes)) = opened else { panic!("didn't open without the page") }; assert_eq!((texts, frames), (1, 1), "{notes:?}"); @@ -6546,7 +6645,7 @@ fn layers_whose_text_document_cannot_be_read_read_it_once_with_the_page() { let file = private(&native_with_text(&art, "not a text document")); let names = crate::NameEncoding::default(); let open = || { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, pdf_part(10.0, 86.0), vec![], false, false, 1.0, names) }; let (opened, texts, frames) = text_reads(false, open); @@ -6573,7 +6672,7 @@ fn an_envelope_of_type_waiting_on_the_page_reads_the_text_once() { let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // A PDF part the layers don't draw as: they open alone, after a build with the page and one without. @@ -6657,7 +6756,7 @@ fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_dr let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, true, 1.0, names); assert!(read, "{notes:?}"); let (envelopes, loose) = envelopes_and_type(&d); @@ -6751,7 +6850,7 @@ fn layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_di let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // The layers alone, with the envelope's drawn art: what the page draws. @@ -6794,7 +6893,7 @@ fn trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_ let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document, trust: bool| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, trust, 1.0, names) }; let (mut page, _, _) = open(pdf_part(80.0, 80.0), false); @@ -6833,7 +6932,7 @@ fn layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_do let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // The layers alone, with the drawn art of both envelopes, but the first's: the page draws diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index eff4f8b20e..4b6e5414f9 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -44,7 +44,7 @@ fn style_word(w: &str) -> String { /// A font's PostScript name without a subset prefix (`ABCDEF+`) or the `*1` of a re-encoded copy /// (`ABCDEF+RollerBabyBV*1` is `RollerBabyBV`). -fn bare_name(name: &str) -> &str { +pub(super) fn bare_name(name: &str) -> &str { let name = match name.split_once('+') { Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest, _ => name, @@ -56,14 +56,15 @@ fn bare_name(name: &str) -> &str { } /// The font of type that a text document's font record names: by `name`, its PostScript name, and -/// `version`, the version string (name ID 5) the record keeps, if any. An installed face of that -/// name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) and the -/// family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is +/// `version`, the version string (name ID 5) the record keeps, if any; `widths`, the widths the +/// file's page gives the font's characters, if it has them ([`postscript_face`]). An installed face +/// of that name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) +/// and the family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is /// Microsoft YaHei). → (family, style, version). /// /// [`FontDb::find_family`]: vectorcraft_text::FontDb::find_family -pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, String, Option) { - named_font(name, version).unwrap_or_else(|| { +pub(crate) fn document_font(name: &str, version: Option<&str>, widths: Option<&vectorcraft_pdf::FontWidths>) -> (String, String, Option) { + named_font(name, version, widths).unwrap_or_else(|| { let (family, style) = family_style(name); let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); (family, style, None) @@ -71,37 +72,69 @@ pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, Strin } /// The font of type set in the installed face of PostScript name `name` (a subset prefix and a -/// re-encoded copy's `*1` aside) in `version` ([`postscript_face`]): that face's own family and -/// style, and its version when the family and style alone resolve to another installed copy of -/// the font. A library can keep two copies under one family and style that differ in their -/// PostScript names or their versions, and draw the same text at different widths. → (family, -/// style, version); `None` when no installed face has the name. -pub(crate) fn named_font(name: &str, version: Option<&str>) -> Option<(String, String, Option)> { - let face = postscript_face(bare_name(name), version)?; +/// re-encoded copy's `*1` aside) in `version`, or that sets the characters at `widths` +/// ([`postscript_face`]): that face's own family and style, and its version when the family and +/// style alone resolve to another installed copy of the font. A library can keep two copies under +/// one family and style that differ in their PostScript names or their versions, and draw the same +/// text at different widths. → (family, style, version); `None` when no installed face has the name. +pub(crate) fn named_font( + name: &str, + version: Option<&str>, + widths: Option<&vectorcraft_pdf::FontWidths>, +) -> Option<(String, String, Option)> { + let face = postscript_face(bare_name(name), version, widths)?; // As the PDF import names a version: only one that the family and style don't resolve to. let default = vectorcraft_text::FontDb::global().face(&face.family, &face.style); let version = default.filter(|d| d.version != face.version).map(|_| face.version.clone()); Some((face.family.clone(), face.style.clone(), version)) } +/// How far an installed face's advance may be from the width a page gives a character, in +/// thousandths of an em, for the face to set it at that width: files write widths rounded. +const PAGE_WIDTH_SLACK: f64 = 1.0; + +/// The most characters of a page's font [`sets_page_widths`] compares. +const MAX_WIDTHS_COMPARED: usize = 512; + +/// Does installed `face` set the characters of `widths` (a page's, [`vectorcraft_pdf::FontWidths`]) +/// at their widths, each within [`PAGE_WIDTH_SLACK`]? The first [`MAX_WIDTHS_COMPARED`] characters +/// in code-point order are compared; a character the face has no glyph for isn't set at its width. +fn sets_page_widths(face: &vectorcraft_text::FontFace, widths: &vectorcraft_pdf::FontWidths) -> bool { + let k = 1000.0 / face.units_per_em(); + widths.iter().take(MAX_WIDTHS_COMPARED).all(|(c, w)| { + let gid = face.glyph_for(*c); + gid != 0 && (face.advance(gid) * k - f64::from(*w)).abs() <= PAGE_WIDTH_SLACK + }) +} + /// The installed face of PostScript name `name` (without a subset prefix), among the installed /// faces that answer to it ([`FontDb::postscript_faces`]): those of exactly that name when there /// are any (PostScript names are case-sensitive, so `SampleSans` isn't the face named /// `SAMPLESANS`, and `SampleSerif-Bold` isn't `SampleSerifBold`), and of those the one in -/// `version` when it is installed, else the first. `None` when no installed face has the name. +/// `version` when it is installed. Without a version, copies whose names, family and style are all +/// one can still set the type at other widths: of those, the first that sets the characters of +/// `widths` (the file's page's, when it has them) at their widths ([`sets_page_widths`], which +/// compares the first 512 characters). Else the first. `None` when no installed face has the name. /// /// [`FontDb::postscript_faces`]: vectorcraft_text::FontDb::postscript_faces -pub(crate) fn postscript_face(name: &str, version: Option<&str>) -> Option> { +pub(crate) fn postscript_face( + name: &str, + version: Option<&str>, + widths: Option<&vectorcraft_pdf::FontWidths>, +) -> Option> { let db = vectorcraft_text::FontDb::global(); let found = db.find_postscript(name)?; - if found.postscript_name() == name && version.is_none_or(|v| v == found.version) { + let widths = widths.filter(|_| version.is_none()); + let on_page = |f: &vectorcraft_text::FontFace| widths.is_none_or(|w| sets_page_widths(f, w)); + if found.postscript_name() == name && version.is_none_or(|v| v == found.version) && on_page(&found) { return Some(found); } let faces = db.postscript_faces(name); let named: Vec<_> = faces.iter().filter(|f| f.postscript_name() == name).cloned().collect(); let pool = if named.is_empty() { faces } else { named }; let in_version = version.and_then(|v| pool.iter().find(|f| f.version == v).cloned()); - Some(in_version.or_else(|| pool.into_iter().next()).unwrap_or(found)) + let by_widths = || pool.iter().find(|f| on_page(f)).cloned(); + Some(in_version.or_else(by_widths).or_else(|| pool.into_iter().next()).unwrap_or(found)) } /// A font's family and style from its PostScript name, without a subset prefix (`ABCDEF+`) or the @@ -620,7 +653,7 @@ impl Interp<'_> { } // The installed face of that PostScript name, as type from a text document takes it; else // the available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei". - let (font_family, font_style, font_version) = document_font(&name, None); + let (font_family, font_style, font_version) = document_font(&name, None, None); let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() }; let style = CharStyle { font_family, font_style, font_version, size, fill, stroke: Paint::None, ..CharStyle::default() }; let mut t = TextObject::point(Point::ZERO, text, style); diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 1abfd0210e..d8b9a96295 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -52,8 +52,9 @@ pub use ai_editing::{AiEditingOptions, AiEditingOutput, CREATOR_VERSION, export_ #[cfg(any(test, feature = "work-count"))] pub use import::blend_work; pub use import::{ - AiLayers, Imported, NameEncoding, POSTSCRIPT_ERRORS, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, - family_style, import, import_ai, import_names, import_trusting, import_with, is_loss, layered_ai, layered_ai_from, page, + AiLayers, Imported, NameEncoding, POSTSCRIPT_ERRORS, ai_alone, ai_alone_decoded, ai_alone_on_page, ai_alone_on_page_decoded, ai_alone_with, + ai_layers_alone, ai_layers_alone_decoded, ai_opened_artboard, ai_opened_artboard_decoded, decode_ai_private, family_style, import, import_ai, + import_names, import_trusting, import_with, is_loss, layered_ai, layered_ai_from, page, }; pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai, writes_image_mask}; pub use print::{PrintFonts, PrintJob, PrintPage, print}; diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 49cc392f80..5264414cb3 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -403,11 +403,32 @@ impl SubPath { /// Bend segment `seg` so its point at `t` moves by `dv`: both inner control points move by /// dv / 3t(1-t), since B(t) moves by 3t(1-t) times that. A smooth anchor stays smooth: its other /// handle turns with the moved one. False when there is no such segment. + /// + /// A straight segment's handles lie on its anchors, so moving them as they are curls its ends + /// round (#9225). It is bent as the same line with its handles at its thirds instead, so it + /// bows evenly, the point at `t` still landing `dv` away. pub fn bend_segment(&mut self, seg: usize, t: f64, dv: kurbo::Vec2) -> bool { let n = self.anchors.len(); if seg >= self.segment_count() || n == 0 { return false; } + if dv == kurbo::Vec2::ZERO { + return true; + } + let mut t = t; + if self.segment_is_line(seg) { + let c = self.segment(seg); + let third = (c.p3 - c.p0) / 3.0; + if let Some(a) = self.anchors.get_mut(seg % n) { + a.set_handle(true, c.p0 + third, false); + } + if let Some(b) = self.anchors.get_mut((seg + 1) % n) { + b.set_handle(false, c.p3 - third, false); + } + // With its handles on its anchors, the line is at t²(3 - 2t) of the way along at t; with + // them at its thirds, that far along is where it is at that same parameter. + t = t * t * (3.0 - 2.0 * t); + } let v = dv / (3.0 * t * (1.0 - t)); if let Some(a) = self.anchors.get_mut(seg % n) { a.set_handle(true, a.h_out + v, false); @@ -940,6 +961,28 @@ fn push_curve(cur: &mut Option, last: Point, c1: Point, c2: Point, p: P #[cfg(test)] mod tests { + /// #9225: a straight segment bent from its middle bows evenly: its handles leave from along the + /// line, toward the middle, not straight out of its anchors, and the grabbed point follows. + #[test] + fn bending_a_straight_segment_pulls_its_handles_from_along_the_line() { + for t in [0.5, 0.3, 0.1] { + let mut sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(300.0, 0.0)], false); + let grabbed = sp.segment(0).eval(t); + let dv = kurbo::Vec2::new(0.0, 60.0); + assert!(sp.bend_segment(0, t, dv)); + let (a, b) = (sp.anchors[0], sp.anchors[1]); + assert!(a.h_out.x > a.p.x + 1.0 && b.h_in.x < b.p.x - 1.0, "t {t}: {a:?} {b:?}"); + let landed = sp.segment(0).nearest(grabbed + dv, 1e-9).distance_sq.sqrt(); + assert!(landed < 1e-6, "t {t}: the grabbed point is {landed} off the pointer"); + } + // No move leaves it as it was, a smooth end's other handle included. + let mut sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(300.0, 0.0)], false); + sp.anchors[1].h_out = Point::new(300.0, 50.0); + sp.anchors[1].kind = AnchorKind::Smooth; + let before = sp.clone(); + assert!(sp.bend_segment(0, 0.5, kurbo::Vec2::ZERO)); + assert_eq!(sp.anchors, before.anchors); + } use super::*; /// `bounds` walks the anchors in place: bit for bit what the kurbo path it stands for gives, diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index 8efa1458eb..a0bf7f1f09 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -250,6 +250,54 @@ pub enum Expr { arg: Option, delegate: bool, }, + /// A class expression. + Class(Box), + /// `super(arguments)` in a derived class's constructor. + SuperCall(Vec), + /// `super.property` in a class's methods and constructor. + SuperMember(Name), + /// `super[index]`. + SuperIndex(ExprId), + /// `new.target`. + NewTarget, +} + +/// A class declaration or expression (ECMA-262 2015 section 14.5). +#[derive(Clone, Debug, PartialEq)] +pub struct ClassDef { + pub name: Option, + /// The expression after `extends`. + pub heritage: Option, + /// The constructor as written, or the default one a class without one gets. Its span is the + /// class's. + pub constructor: FunctionId, + /// The methods and accessors other than the constructor, in source order. + pub elements: Vec, + pub span: Span, +} + +/// A method or accessor in a class body. +#[derive(Clone, Debug, PartialEq)] +pub struct ClassElement { + pub key: ClassKey, + /// Defined on the constructor (`static`) rather than on its `prototype`. + pub is_static: bool, + pub kind: MethodKind, + pub function: FunctionId, +} + +/// A class element's name: written out, or computed (`[expression]`). +#[derive(Clone, Debug, PartialEq)] +pub enum ClassKey { + Fixed(PropertyKey), + Computed(ExprId), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MethodKind { + Method, + Get, + Set, } /// A piece of a template literal's text between its substitutions. @@ -359,6 +407,8 @@ pub enum Stmt { /// `let` or `const` declarations (a `const` always has an initializer). Lexical(LexKind, Vec), FunctionDecl(FunctionId), + /// A class declaration, its name a `let`-like binding of the scope it stands in. + Class(Box), Expr(ExprId), Block(Vec), Empty, @@ -428,8 +478,12 @@ pub enum FunctionKind { Setter, /// An arrow function; one with an expression body has a body of one `return` statement. Arrow, - /// A method in an object literal. + /// A method in a class body or an object literal. Method, + /// The constructor of a class without `extends`. + ClassConstructor, + /// The constructor of a class with `extends`. + DerivedConstructor, } #[derive(Clone, Debug, PartialEq)] @@ -449,9 +503,17 @@ pub struct Function { /// A generator function (`function*`, or `*name() {…}` in an object literal). pub generator: bool, pub span: Span, + /// The function is defined in a class body (a method, an accessor or the constructor): it has + /// a home object for `super.property`. + pub home: bool, } impl Function { + /// The function is a class constructor. + pub fn is_class_constructor(&self) -> bool { + matches!(self.kind, FunctionKind::ClassConstructor | FunctionKind::DerivedConstructor) + } + /// The parameters are plain names: no pattern, no default value and no rest parameter. pub fn simple_params(&self) -> bool { self.rest.is_none() && self.defaults.iter().all(Option::is_none) && self.params.iter().all(|p| matches!(p, Binding::Name(_))) diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 6e6a6edccc..8bf8783adf 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -591,15 +591,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || is_host_member_pk(interp, o, &k)?)) -} - -/// [`Interp::is_host_member`] for either kind of key: a Symbol never names a host member. -fn is_host_member_pk(interp: &Interp, o: ObjId, k: &crate::symbol::PropKey) -> JsResult { - match k { - crate::symbol::PropKey::Str(name) => interp.is_host_member(o, name), - crate::symbol::PropKey::Sym(_) => Ok(false), - } + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?)) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -618,7 +610,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || is_host_member_pk(interp, o, &k)?)) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?)) } // ---- Function ---- diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 39734bb088..3ec93edc07 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -15,12 +15,13 @@ //! every buffer's bytes are checked against the heap before they are allocated. Every element //! a method visits takes a unit of fuel, and a sort's comparisons take one each. //! -//! The language has no iterators yet, so constructing from an object reads an array or an object -//! with a `length`, by index, and `%TypedArray%.from` reads those or a string, by code point. A -//! constructor given a primitive string reads it as a length. +//! Constructing from an object that is not a buffer or a typed array, and `%TypedArray%.from`, +//! read a source with an `@@iterator` method through its iterator (a string by code point), and +//! any other source as an array-like object, by index. `%TypedArray%.prototype[@@iterator]` is +//! `values`. A constructor given a primitive string reads it as a length. -use super::collections::{for_each_item, getter, length_of, new_iter, new_proto}; -use super::{arg, array, data, method, native, require_callable, to_integer}; +use super::collections::{getter, length_of, new_iter, new_proto}; +use super::{arg, array, data, method, native, new_array, require_callable, to_integer}; use crate::heap::{Class, Elem, HIDDEN, IterKind, IterSource, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, VIEW_BYTES, View, key}; use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult}; use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint32}; @@ -28,9 +29,6 @@ use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint3 /// The longest buffer, in bytes. const MAX_BUFFER: u64 = u32::MAX as u64; -/// The bytes each item a method gathers before it writes them is charged. -const ITEM_BYTES: usize = 16; - pub(super) fn install(interp: &mut Interp) -> JsResult<()> { install_array_buffer(interp)?; install_data_view(interp)?; @@ -124,6 +122,11 @@ fn install_typed_arrays(interp: &mut Interp) -> JsResult<()> { for (name, f, length) in methods { method(interp, proto, name, f, length)?; } + // `%TypedArray%.prototype[@@iterator]` is `values` (section 22.2.3.30). + if let Some(iterator) = interp.well_known(|w| &w.iterator) { + let values = interp.get_from(proto, &key("values"), &Value::Object(proto))?; + interp.define_sym(proto, iterator, crate::heap::Prop::Data { value: values, flags: HIDDEN })?; + } // `%TypedArray%.prototype.toString` is `Array.prototype.toString` (section 22.2.3.28). let array_proto = interp.intrinsics.array_proto; let to_string = interp.get_from(array_proto, &key("toString"), &Value::Object(array_proto))?; @@ -645,21 +648,59 @@ fn typed_ctor(interp: &mut Interp, args: &[Value], constructing: bool, elem: Ele } return Ok(Value::Object(ta)); } - let len = length_of(interp, o)?; - let ta = new_typed(interp, elem, len)?; - interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, &first, len))?; - Ok(Value::Object(ta)) + // Any other object is read as TypedArrayFrom reads it (section 22.2.1.4). + typed_array_from(interp, &first, None, |interp, len| new_typed(interp, elem, len)) } -/// Writes the elements `0` to `len - 1` of the array-like object `src` to the typed array `ta`, -/// each converted with ToNumber. -fn fill_from(interp: &mut Interp, ta: ObjId, src: &Value, len: u64) -> JsResult<()> { - let Value::Object(o) = src else { return Ok(()) }; +/// TypedArrayFrom (section 22.2.2.1.1): a typed array with the values of `items`, made by `make` +/// once their number is known, each value mapped with `map` (the function and its `this`) when +/// one is given and converted with ToNumber. An `items` with an `@@iterator` method is read +/// through its iterator to the end before the typed array is made. Any other value is read as +/// an array-like object, each element read, mapped and written before the next is read. +fn typed_array_from( + interp: &mut Interp, + items: &Value, + map: Option<(&Value, &Value)>, + make: impl FnOnce(&mut Interp, u64) -> JsResult, +) -> JsResult { + let using_iterator = match interp.well_known(|w| &w.iterator) { + Some(iterator) => interp.get_value_sym(items, &iterator)?, + None => Value::Undefined, + }; + let src = if using_iterator.is_nullish() { + interp.to_object(items)? + } else { + let rec = interp.get_iterator_with(items, &using_iterator)?; + interp.rooted(&[Value::Object(rec)], |interp| { + let list = new_array(interp, 0)?; + interp.rooted(&[Value::Object(list)], |interp| interp.append_values(rec, list))?; + Ok(list) + })? + }; + let src_value = Value::Object(src); + interp.rooted(std::slice::from_ref(&src_value), |interp| { + let len = length_of(interp, src)?; + let ta = make(interp, len)?; + interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, src, len, map))?; + Ok(Value::Object(ta)) + }) +} + +/// Writes the elements `0` to `len - 1` of the object `src` to the typed array `ta`, each mapped +/// with `map` when one is given and converted with ToNumber. Each element is read just before it +/// is mapped and written. +fn fill_from(interp: &mut Interp, ta: ObjId, src: ObjId, len: u64, map: Option<(&Value, &Value)>) -> JsResult<()> { let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + let src_value = Value::Object(src); for i in 0..len { interp.use_fuel()?; #[allow(clippy::cast_precision_loss)] - let v = interp.get_from(*o, &super::key_of(i as f64), src)?; + let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?; + #[allow(clippy::cast_precision_loss)] + let v = match map { + Some((f, this_arg)) => interp.call(f, this_arg, &[item, Value::Number(i as f64)])?, + None => item, + }; let n = interp.to_number(&v)?; write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); } @@ -741,54 +782,11 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe require_callable(interp, &map_fn, "the map function")?; } let this_arg = arg(args, 2); - let source = arg(args, 0); - if !matches!(source, Value::String(_)) { - // An array-like source: each element is read, mapped and written before the next is read. - let src = interp.to_object(&source)?; - let src_value = Value::Object(src); - let len = length_of(interp, src)?; + let map = mapping.then_some((&map_fn, &this_arg)); + typed_array_from(interp, &arg(args, 0), map, |interp, len| { let elem = ctor_elem(interp, &this, "from")?; - let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; - return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { - for i in 0..len { - interp.use_fuel()?; - #[allow(clippy::cast_precision_loss)] - let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?; - #[allow(clippy::cast_precision_loss)] - let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; - let n = interp.to_number(&v)?; - write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); - } - Ok(Value::Object(ta)) - }); - } - // A string is read by code point first, as an iterable source is, and then mapped. - let mark = interp.temp_roots.len(); - let mut held = crate::interp::HeldBytes::new(interp); - let gathered = for_each_item(interp, &source, false, |interp, item| { - held.add(interp, ITEM_BYTES)?; - interp.temp_roots.push(item); - Ok(()) - }); - let result = gathered.and_then(|()| { - let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); - let elem = ctor_elem(interp, &this, "from")?; - let ta = new_typed(interp, elem, items.len() as u64)?; - interp.temp_roots.push(Value::Object(ta)); - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; - for (i, item) in items.into_iter().enumerate() { - interp.use_fuel()?; - #[allow(clippy::cast_precision_loss)] - let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; - let n = interp.to_number(&v)?; - write(interp, &view, i, n); - } - Ok(Value::Object(ta)) - }); - interp.temp_roots.truncate(mark); - drop(held); - result + new_typed(interp, elem, len) + }) } /// `%TypedArray%.of(...items)` (section 22.2.2.2). diff --git a/crates/js/src/builtins/collections.rs b/crates/js/src/builtins/collections.rs index 70da37c39c..2d9f6176d3 100644 --- a/crates/js/src/builtins/collections.rs +++ b/crates/js/src/builtins/collections.rs @@ -8,18 +8,20 @@ //! entries hold their key weakly: the collector removes an entry once its key is reachable only //! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed. //! -//! The language has no iterators yet, so the constructors read their argument by index: an -//! array or an object with a `length`, or a string by code point. Every entry added is checked -//! against the heap limit before it is added, and every entry visited takes a unit of fuel. +//! The constructors read their argument through its `@@iterator` method (GetIterator, section +//! 7.4.1), and close the iterator when adding an entry throws (IteratorClose, section 7.4.6). +//! `Map.prototype[@@iterator]` is `entries`, `Set.prototype[@@iterator]` is `values`, and the +//! iterators inherit from `%IteratorPrototype%`. Every entry added is checked against the heap +//! limit before it is added, and every entry visited takes a unit of fuel. -use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable}; +use super::{arg, constructor, create_at, method, native, new_array, require_callable}; use crate::heap::{ COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes, }; use crate::interp::{Abrupt, Interp, JsResult}; use crate::string_builtins::flat_charged; -use crate::value::{Str, Value}; +use crate::value::Value; /// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does /// to the globals. @@ -137,7 +139,14 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> { getter(interp, set_proto, "get size", set_size)?; // `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8). let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?; - interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?; + interp.define(set_proto, key("keys"), Prop::Data { value: values.clone(), flags: crate::heap::HIDDEN })?; + // `Map.prototype[@@iterator]` is `entries` and `Set.prototype[@@iterator]` is `values` + // (sections 23.1.3.12 and 23.2.3.11). + if let Some(iterator) = interp.well_known(|w| &w.iterator) { + let entries = interp.get_from(map_proto, &key("entries"), &Value::Object(map_proto))?; + interp.define_sym(map_proto, iterator.clone(), Prop::Data { value: entries, flags: crate::heap::HIDDEN })?; + interp.define_sym(set_proto, iterator, Prop::Data { value: values, flags: crate::heap::HIDDEN })?; + } let weak_map_proto = new_proto(interp, object_proto); interp.intrinsics.es2015.weak_map_proto = weak_map_proto; @@ -158,8 +167,12 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> { method(interp, weak_set_proto, name, f, length)?; } + // The iterators' prototypes inherit from `%IteratorPrototype%` (sections 23.1.5.2, 23.2.5.2 + // and 22.1.5.2), whose `@@iterator` gives the iterator itself. + let iterator_proto = + interp.symbols.objects.and_then(|o| interp.heap.object(o.array_iterator_proto).and_then(|p| p.proto)).unwrap_or(object_proto); for source in [IterSource::Map, IterSource::Set, IterSource::Array] { - let proto = new_proto(interp, object_proto); + let proto = new_proto(interp, iterator_proto); let next: NativeFn = match source { IterSource::Map => map_iterator_next, IterSource::Set => set_iterator_next, @@ -209,56 +222,10 @@ pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 }) } -/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`, -/// or a string's code points. Any other value is a `TypeError`, and so is an object without a -/// `length` when `need_length` is true. Each item takes a unit of fuel. -pub(crate) fn for_each_item( - interp: &mut Interp, - list: &Value, - need_length: bool, - mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>, -) -> JsResult<()> { - match list { - Value::Object(o) => { - if need_length && !interp.has_property(*o, &key("length"))? { - return Err(interp.type_error("the value is not an array, a string or an object with a length")); - } - let len = length_of(interp, *o)?; - let mut i = 0u64; - while i < len { - interp.use_fuel()?; - #[allow(clippy::cast_precision_loss)] - let item = interp.get_from(*o, &key_of(i as f64), list)?; - f(interp, item)?; - i += 1; - } - Ok(()) - } - Value::String(s) => { - let units = flat_charged(interp, s)?; - let mut i = 0; - while i < units.len() { - interp.use_fuel()?; - let width = match (units.get(i), units.get(i + 1)) { - (Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2, - _ => 1, - }; - let piece = units.get(i..i + width).unwrap_or_default().to_vec(); - let bytes = string_bytes(piece.len()); - interp.reserve_heap(bytes)?; - interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); - f(interp, Value::String(Str::from_units(piece)))?; - i += width; - } - Ok(()) - } - _ => Err(interp.type_error("the value is not an array, a string or an object with a length")), - } -} - -/// Adds the items of `list` to the new collection `target` with its `adder` method, as the -/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item -/// as a `[key, value]` entry. +/// Adds the values the iterator of `list` gives to the new collection `target` with its `adder` +/// method, as the constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` +/// reads each value as a `[key, value]` entry, which must be an object. When reading an entry +/// or adding it throws, the iterator is closed. fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> { if list.is_nullish() { return Ok(()); @@ -268,7 +235,8 @@ fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bo let add = interp.get_from(target, &key(adder), &this)?; require_callable(interp, &add, adder)?; interp.rooted(std::slice::from_ref(&add), |interp| { - for_each_item(interp, list, true, |interp, item| { + let rec = interp.get_iterator(list)?; + interp.for_each_value(rec, |interp, item| { if !pairs { return interp.call(&add, &this, &[item]).map(drop); } diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 9122362928..7f684fbbf5 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -33,6 +33,7 @@ use crate::bytecode::Code; use crate::heap::{ BOUND_ARG_BYTES, CONFIGURABLE, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key, }; +use crate::host::ArgRead; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; use crate::value::Value; @@ -934,7 +935,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let mut v = v.clone(); loop { @@ -945,6 +947,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { match func { Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator), Func::Native { constructor, .. } => return Ok(constructor), + Func::Data { read: ArgRead::Hosted, .. } => return Ok(v.as_object().is_some_and(|o| interp.is_constructible_host_class(o))), Func::Bound { target, .. } => { interp.use_fuel()?; v = Value::Object(target); diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 5a44e6385a..101e3e55b5 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -36,6 +36,8 @@ pub(crate) enum Op { Swap, /// `a b c` → `b c a`. Rot3, + /// Pushes a copy of the value `n` places under the top one (`Pick(0)` is `Dup`). + Pick(u32), /// Pushes the value of the variable `names[i]`. GetVar(u32), /// Pushes the value of the variable and the `this` a call to it gets. @@ -223,6 +225,68 @@ pub(crate) enum Op { ToStr, /// Pushes the template object of `templates[i]`, the same object for each evaluation. TemplateObject(u32), + /// Starts (`true`) or ends (`false`) a class's heritage and computed keys in code that is not + /// strict mode code: the code between runs as strict mode code (ECMA-262 2015 section 10.2.1). + StrictClass(bool), + /// `[superclass]` → `constructor prototype`: makes a class's prototype object and its + /// constructor from `functions[ctor]`, the superclass on the stack when `heritage` is true + /// (ECMA-262 2015 section 14.5.14). + ClassStart { + ctor: u32, + heritage: bool, + }, + /// `constructor prototype key` → `constructor prototype`: defines the method, getter (`kind` 1) + /// or setter (`kind` 2) made from `functions[func]` under the key, on the constructor when + /// `is_static` is true and otherwise on the prototype. + ClassMethod { + func: u32, + kind: u8, + is_static: bool, + }, + /// `object` → `object`: defines the enumerable method, getter (`kind` 1) or setter (`kind` + /// 2) made from `functions[func]` under `names[name]` on an object literal's object, its home + /// object (section 12.2.6.8). + InitMethod { + func: u32, + kind: u8, + name: u32, + }, + /// `object key` → `object`: [`Op::InitMethod`] under a computed key, already a name or a + /// Symbol. + InitMethodKey { + func: u32, + kind: u8, + }, + /// `this key` → `this home key`: the key as a property name, with the prototype of the + /// running method's home object between, for a `super` property (section 12.3.5.3). + SuperRef, + /// `this home key` → the property's value, read from the home object with `this` as the + /// receiver. + SuperGet, + /// `this home key` → `value this`, for a call. + SuperGetThis, + /// `this home key value` → `value`, written through the home object with `this` as the + /// receiver. + SuperSet, + /// `this home key` → `this home key this home key`. + SuperDup, + /// `this home key` → the old or new value: `++` or `--` on a `super` property. + SuperInc { + prefix: bool, + dec: bool, + }, + /// Pushes the constructor `super(…)` calls: the prototype of the running class constructor. + SuperCtor, + /// `constructor arg…` → the object it constructs, with the running constructor's + /// `new.target`. + SuperCall(u32), + /// `constructor array` → the object it constructs, with the array's elements as arguments. + SuperCallSpread, + /// `value` → `value`: binds the running derived constructor's `this` to the value; a + /// `ReferenceError` when it is bound already. + BindThis, + /// Pushes `new.target`. + NewTarget, /// `value` → its Iterator Record (GetIterator, ECMA-262 11th edition section 7.4.1). GetIterator, /// `record` → `record value`, or jumps with `record` when the iterator is done. @@ -361,9 +425,16 @@ pub(crate) struct Code { pub(crate) arrow: bool, /// The code reads `this` or calls `eval`, itself or in an arrow function inside it. pub(crate) uses_this: bool, - /// The function has default, rest or destructured parameters: its parameters start - /// uninitialized, its code initializes them and then enters its body with [`Op::BodyEnv`]. + /// The function has parameters with default values or destructured parameters: its + /// parameters start uninitialized, its code initializes them and then enters its body with + /// [`Op::BodyEnv`]. pub(crate) param_init: bool, + /// The code is a class constructor's: calling it without `new` is a `TypeError`. + pub(crate) class_ctor: bool, + /// The code is a derived class constructor's: its `this` is bound by `super(…)`. + pub(crate) derived: bool, + /// The code reads `new.target`, itself or in an arrow function inside it. + pub(crate) uses_new_target: bool, /// The names the destructured parameters bind, which start uninitialized beside the /// parameters. A destructured parameter's own entry in `params` is a name no script can /// write. @@ -375,8 +446,9 @@ pub(crate) struct Code { /// and 14.1.20): a declaration's or a named function expression's name, with /// [`crate::Options::es2015`]. pub(crate) own_name: Option, - /// The code is a method's, a getter's or a setter's, read with [`crate::Options::es2015`]: - /// its functions have no `prototype` and cannot be constructed (section 14.3.8). + /// The code is a method's, a getter's or a setter's, read with [`crate::Options::es2015`], or + /// a class method's or accessor's: its functions have no `prototype` and cannot be + /// constructed (section 14.3.8). pub(crate) method: bool, /// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]), /// and it is not a constructor. @@ -424,6 +496,12 @@ impl Code { let offset = self.positions.get(pc).copied().unwrap_or(self.span.0); self.source.lines.line_column(offset) } + + /// The parameters are plain names, without default values or a rest parameter, so outside + /// strict mode code the `arguments` object follows them (ECMA-262 2015 section 9.2.12). + pub(crate) fn simple_params(&self) -> bool { + !self.param_init && self.rest.is_none() + } } /// What an instruction does to the stack on each way out of it. @@ -459,6 +537,10 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::Dup2 => e(2, 4), Op::Swap | Op::ToKey => e(2, 2), Op::Rot3 => e(3, 3), + Op::Pick(n) => { + let below = n.checked_add(1).ok_or("operand too large")?; + e(below, below.checked_add(1).ok_or("operand too large")?) + } Op::GetVarThis(_) => e(0, 2), Op::SetVar(_) | Op::GetMember(_) | Op::DeleteMember(_) | Op::IncMember { .. } => e(1, 1), Op::Neg | Op::Plus | Op::BitNot | Op::Not | Op::Typeof | Op::ToNumber | Op::ArrayHole | Op::ForInStart | Op::CheckObject => e(1, 1), @@ -491,11 +573,25 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::XmlScopeRef => e(1, 2), Op::ForEachValue(n) => e(n + 2, n + 3), Op::SetDefaultNamespace => e(1, 0), - Op::PushBlock(_) | Op::CopyEnv | Op::BodyEnv => e(0, 0), + Op::PushBlock(_) | Op::CopyEnv | Op::BodyEnv | Op::StrictClass(_) => e(0, 0), Op::InitVar(_) | Op::AnnexB(_) => e(1, 0), Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1), Op::ArraySpread | Op::NewSpread => e(2, 1), Op::CallSpread(_) => e(3, 1), + Op::ClassStart { heritage, .. } => e(u32::from(heritage), 2), + Op::ClassMethod { .. } => e(3, 2), + Op::InitMethod { .. } => e(1, 1), + Op::InitMethodKey { .. } => e(2, 1), + Op::SuperRef => e(2, 3), + Op::SuperGet => e(3, 1), + Op::SuperGetThis => e(3, 2), + Op::SuperSet => e(4, 1), + Op::SuperDup => e(3, 6), + Op::SuperInc { .. } => e(3, 1), + Op::SuperCtor | Op::NewTarget => e(0, 1), + Op::SuperCall(n) => e(n.checked_add(1).ok_or("operand too large")?, 1), + Op::SuperCallSpread => e(2, 1), + Op::BindThis => e(1, 1), Op::ToStr | Op::GetIterator | Op::IterSkip | Op::RequireObjectCoercible => e(1, 1), Op::IterStep(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] }, Op::IterValue(n) | Op::IterRest(n) => e(n.checked_add(1).ok_or("operand too large")?, n.checked_add(2).ok_or("operand too large")?), @@ -540,7 +636,13 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> { | Op::InitVar(i) | Op::LoadParam(i) | Op::AnnexB(i) => check(i, code.names.len(), "name"), - Op::Closure(i) => check(i, code.functions.len(), "function"), + Op::Closure(i) | Op::ClassStart { ctor: i, .. } | Op::ClassMethod { func: i, .. } | Op::InitMethodKey { func: i, .. } => { + check(i, code.functions.len(), "function") + } + Op::InitMethod { func, name, .. } => { + check(func, code.functions.len(), "function")?; + check(name, code.names.len(), "name") + } Op::PushBlock(i) => check(i, code.scopes.len(), "scope"), Op::TemplateObject(i) => check(i, code.templates.len(), "template"), Op::RegExp(i) => check(i, code.regexps.len(), "regular expression"), diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs new file mode 100644 index 0000000000..ed114612d4 --- /dev/null +++ b/crates/js/src/class_ops.rs @@ -0,0 +1,603 @@ +//! Classes, `super` and `new.target` (ECMA-262 2015 sections 12.3.5, 12.3.8 and 14.5), and +//! `new` with a `new.target` (sections 7.3.13 and 9.2.2). +//! +//! The running code reaches what these need through bindings whose names start with a NUL, +//! which no identifier holds: +//! +//! - `\0this` holds a derived class constructor's `this`, uninitialized until `super(…)` returns, +//! and the `this` an arrow function closes over. +//! - `\0func` holds a derived class constructor's function object, whose prototype `super(…)` +//! constructs. +//! - `\0newtarget` holds `new.target` for the arrow functions inside a function. +//! - `\0home` holds the home object of a class method, in an environment of the method's own. + +use std::rc::Rc; + +use crate::bytecode::{Code, NamePrefix}; +use crate::heap::{ + Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, Func, HIDDEN, OBJECT_BYTES, ObjId, Object, Prop, PropMap, WRITABLE, key, + string_bytes, +}; +use crate::interp::{ARROW_THIS, Abrupt, Desc, Entry, ErrorType, Interp, JsResult, binding_bytes, closure_bytes, internal}; +use crate::symbol::PropKey; +use crate::value::{Str, Value}; + +const FUNC: &[u16] = &[0, 0x66, 0x75, 0x6E, 0x63]; +const NEW_TARGET: &[u16] = &[0, 0x6E, 0x65, 0x77, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74]; +const HOME: &[u16] = &[0, 0x68, 0x6F, 0x6D, 0x65]; + +/// The most bound functions `new` and `IsConstructor` unwrap in one chain. +const MAX_BOUND_CHAIN: usize = 10_000; + +/// The bytes of the hidden bindings [`Interp::function_bindings`] adds for `code`. +pub(crate) fn hidden_bytes(code: &Code) -> usize { + if code.derived { + binding_bytes(ARROW_THIS.len()) + binding_bytes(FUNC.len()) + binding_bytes(NEW_TARGET.len()) + } else if code.uses_new_target && !code.arrow { + binding_bytes(NEW_TARGET.len()) + } else { + 0 + } +} + +impl Interp { + /// The nearest declarative environment from `start` outward that holds `name`. + fn hidden_env(&self, start: EnvId, name: &[u16]) -> Option { + let mut cur = Some(start); + while let Some(e) = cur { + match self.heap.env(e)? { + Env::Decl { bindings, outer } => { + if bindings.contains(name) { + return Some(e); + } + cur = *outer; + } + Env::Obj { outer, .. } => cur = *outer, + } + } + None + } + + /// The value of the hidden binding `name` nearest the running code, or `undefined`. + fn hidden_value(&self, name: &[u16]) -> JsResult { + let env = self.frame()?.env; + match self.hidden_env(env, name) { + Some(e) => self.binding_value(e, name), + None => Ok(Value::Undefined), + } + } + + /// The `new.target` of the function the running code is in, for a direct `eval` it calls: + /// `None` outside a function. A function that calls `eval` keeps its `new.target` in a hidden + /// binding ([`Interp::function_bindings`]). Each scope looked at takes a unit of fuel. + pub(crate) fn caller_new_target(&mut self) -> JsResult> { + let mut cur = Some(self.frame()?.env); + while let Some(e) = cur { + self.use_fuel()?; + cur = match self.heap.env(e) { + Some(Env::Decl { bindings, outer }) => { + if bindings.contains(NEW_TARGET) { + return self.binding_value(e, NEW_TARGET).map(Some); + } + *outer + } + Some(Env::Obj { outer, .. }) => *outer, + None => None, + }; + } + Ok(None) + } + + /// Adds the hidden bindings of a call to `code` to its function environment `env`: a derived + /// class constructor's `this`, function object and `new.target`, and the `new.target` of a + /// function whose arrow functions read it. Gives the environment of a derived constructor's + /// `this`. The caller has reserved [`hidden_bytes`] of `code`. + pub(crate) fn function_bindings(&mut self, code: &Code, env: EnvId, callee: ObjId, new_target: Option) -> JsResult> { + let nt = new_target.map_or(Value::Undefined, Value::Object); + if code.derived { + self.env_insert(env, Rc::from(ARROW_THIS), Binding::lexical(false))?; + self.env_insert(env, Rc::from(FUNC), Binding::new(Value::Object(callee), false, false))?; + self.env_insert(env, Rc::from(NEW_TARGET), Binding::new(nt, false, false))?; + return Ok(Some(env)); + } + if code.uses_new_target && !code.arrow { + self.env_insert(env, Rc::from(NEW_TARGET), Binding::new(nt, false, false))?; + } + Ok(None) + } + + /// The `this` an arrow function closing over `env` starts with: `undefined` while a derived + /// constructor's `this` is not yet bound. + pub(crate) fn arrow_this(&self, env: EnvId) -> Value { + match self.hidden_env(env, ARROW_THIS) { + Some(e) if !self.uninitialized(e, ARROW_THIS) => self.binding_value(e, ARROW_THIS).unwrap_or(Value::Undefined), + _ => Value::Undefined, + } + } + + fn this_not_bound(&mut self) -> Abrupt { + self.throw(ErrorType::Reference, "'this' is used before super() is called") + } + + /// The value of `this` in the running code (ResolveThisBinding, section 8.3.2). In a derived + /// class constructor and the arrow functions and direct eval code inside it, reading it before + /// `super(…)` returns is a `ReferenceError`. + pub(crate) fn this_value(&mut self) -> JsResult { + let frame = self.frame()?; + if frame.this_in_env + && let Some(e) = self.hidden_env(frame.env, ARROW_THIS) + { + if self.uninitialized(e, ARROW_THIS) { + return Err(self.this_not_bound()); + } + return self.binding_value(e, ARROW_THIS); + } + Ok(self.frame()?.this.clone()) + } + + /// What a derived class constructor whose `this` is in `env` gives for the return value `v` + /// (section 9.2.2, steps 13 to 15). + pub(crate) fn derived_result(&mut self, env: EnvId, v: Value) -> JsResult { + match v { + Value::Object(_) => Ok(v), + Value::Undefined if self.uninitialized(env, ARROW_THIS) => Err(self.this_not_bound()), + Value::Undefined => self.binding_value(env, ARROW_THIS), + _ => Err(self.type_error("a derived class constructor must return an object or undefined")), + } + } + + /// IsConstructor (section 7.2.4). + pub(crate) fn is_constructor(&self, v: &Value) -> bool { + let mut v = v.clone(); + for _ in 0..MAX_BOUND_CHAIN { + match self.func_of(&v) { + Some(Func::Closure { code, .. }) => return !(code.arrow || code.method || code.generator), + Some(Func::Native { constructor, .. }) => return constructor, + Some(Func::Data { read: crate::host::ArgRead::Hosted, .. }) => return v.as_object().is_some_and(|o| self.is_host_constructor(o)), + Some(Func::Bound { target, .. }) => v = Value::Object(target), + _ => return false, + } + } + false + } + + /// Does the built-in constructor `f` make objects that a subclass may give its own + /// prototype? It does when its `prototype` is one of the realm's built-in prototypes. + fn subclassable(&self, f: ObjId) -> JsResult { + let Some(Prop::Data { value: Value::Object(p), .. }) = self.get_own_property(f, &key("prototype"))? else { return Ok(false) }; + let i = &self.intrinsics; + Ok([i.object_proto, i.function_proto, i.array_proto, i.string_proto, i.number_proto, i.boolean_proto, i.regexp_proto, i.date_proto] + .contains(&p) + || i.error_protos.contains(&p)) + } + + /// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14). + fn prototype_from(&mut self, new_target: ObjId, fallback: ObjId) -> JsResult { + match self.get_from(new_target, &key("prototype"), &Value::Object(new_target))? { + Value::Object(p) => Ok(p), + _ => Ok(fallback), + } + } + + /// Does the prototype chain from `start` reach `target`? + fn chain_reaches(&self, start: ObjId, target: ObjId) -> JsResult { + let mut cur = Some(start); + let mut steps = 0usize; + while let Some(o) = cur { + if o == target { + return Ok(true); + } + steps += 1; + if steps > 1_000_000 { + return Ok(true); + } + cur = self.object(o)?.proto; + } + Ok(false) + } + + /// Constructs `f` with `args` and `new_target` (`f` itself when `None`) and pushes the + /// result, or the frame that makes it, after taking the stack back to `start`. The operands + /// at `start` and above keep `f` and `args` reachable. + pub(crate) fn construct(&mut self, start: usize, f: Value, mut args: Vec, new_target: Option) -> JsResult<()> { + let mut f = f; + let mut new_target = new_target; + // A bound function constructs its target with its arguments first, and a `new.target` + // that is the bound function becomes the target (section 9.4.1.2). + let mut steps = 0usize; + while let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) { + self.use_fuel()?; + steps += 1; + if steps > MAX_BOUND_CHAIN { + return Err(self.type_error("the value is not a constructor")); + } + let mut all = bound_args.to_vec(); + all.append(&mut args); + args = all; + if new_target.is_some() && new_target == f.as_object() { + new_target = Some(target); + } + f = Value::Object(target); + } + let Some(callee) = f.as_object() else { return Err(self.type_error("the value is not a constructor")) }; + let nt = new_target.unwrap_or(callee); + match self.func_of(&f) { + Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, .. }) if code.generator => Err(self.type_error("a generator function is not a constructor")), + Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")), + Some(Func::Closure { code, env }) if code.derived => { + self.stack.truncate(start); + self.enter_function(Entry { callee, code, env, this: Value::Undefined, args, new_target: Some(nt) }, None, false) + } + Some(Func::Closure { code, env }) => { + let fallback = self.intrinsics.object_proto; + let proto = self.prototype_from(nt, fallback)?; + let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + self.stack.truncate(start); + self.enter_function(Entry { callee, code, env, this: Value::Object(obj), args, new_target: Some(nt) }, Some(obj), false) + } + Some(Func::Native { f: native, constructor: true, .. }) => { + let subclass = nt != callee; + if subclass && !self.subclassable(callee)? { + return Err(self.type_error("this built-in cannot be subclassed")); + } + let intrinsic = match self.get_own_property(callee, &key("prototype"))? { + Some(Prop::Data { value: Value::Object(p), .. }) => Some(p), + _ => None, + }; + let v = if subclass && intrinsic == Some(self.intrinsics.object_proto) { + // `Object` constructed for a subclass makes an ordinary object, whatever its + // argument (section 19.1.1.1, step 1). + let fallback = self.intrinsics.object_proto; + let proto = self.prototype_from(nt, fallback)?; + Value::Object(self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)))) + } else { + let held = self.held_bytes; + let r = native(self, Value::Undefined, &args, true); + self.held_bytes = held; + let v = r?; + if subclass && let Value::Object(o) = v { + let proto = self.rooted(std::slice::from_ref(&v), |i| { + let fallback = intrinsic.unwrap_or(i.intrinsics.object_proto); + i.prototype_from(nt, fallback) + })?; + if self.object(o)?.proto == intrinsic && !self.chain_reaches(proto, o)? { + self.object_mut(o)?.proto = Some(proto); + } + } + v + }; + self.stack.truncate(start); + self.push(v) + } + // A host class's constructor ([`crate::host_classes`]) gives the object it makes. A plain + // object it gives inherits from the class's prototype. The class's other functions are + // not constructors. A constructor called with `new` cannot wait for its result. + Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) if self.is_host_constructor(callee) => { + if nt != callee { + return Err(self.type_error("this built-in cannot be subclassed")); + } + let was = std::mem::replace(&mut self.constructing, true); + let v = self.call_data(&host, &name, &Value::Undefined, &args, &read); + self.constructing = was; + let v = v?; + if let Value::Object(o) = &v + && matches!(self.object(*o)?.class, Class::Ordinary) + && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? + { + self.object_mut(*o)?.proto = Some(proto); + } + self.stack.truncate(start); + self.push(v) + } + _ => Err(self.type_error("the value is not a constructor")), + } + } + + /// `heritage?` → `F proto`: the constructor and prototype of a class whose constructor is + /// `functions[ctor]` (ClassDefinitionEvaluation, section 14.5.14, steps 5 to 18). + pub(crate) fn op_class_start(&mut self, ctor: u32, heritage: bool) -> JsResult<()> { + self.use_fuel()?; + let (proto_parent, ctor_parent) = if heritage { + let h = self.peek(0)?; + match h { + Value::Null => (None, self.intrinsics.function_proto), + Value::Object(c) if self.is_constructor(&h) => match self.get_from(c, &key("prototype"), &h)? { + Value::Object(p) => (Some(p), c), + Value::Null => (None, c), + _ => return Err(self.type_error("the prototype of the class's superclass is not an object or null")), + }, + _ => return Err(self.type_error("a class can extend only a constructor or null")), + } + } else { + (Some(self.intrinsics.object_proto), self.intrinsics.function_proto) + }; + let frame = self.frame()?; + let env = frame.env; + let Some(code) = frame.code.functions.get(ctor as usize).cloned() else { return internal("function out of range") }; + let need = (2 * OBJECT_BYTES) + .saturating_add(ENV_BYTES) + .saturating_add(binding_bytes(HOME.len())) + .saturating_add(closure_bytes(&code)) + .saturating_add(binding_bytes("prototype".len())) + .saturating_add(binding_bytes("constructor".len())); + let roots: Vec = proto_parent.map(Value::Object).into_iter().collect(); + self.rooted(&roots, |i| i.reserve_heap(need))?; + let proto = self.heap.alloc_object(Object::new(Class::Ordinary, proto_parent)); + // The constructor's home object is the prototype, as for the other prototype methods + // (section 14.5.14, step 12). + let home = self.home_env(proto, env); + let f = self.make_closure(code, home)?; + self.object_mut(f)?.proto = Some(ctor_parent); + self.define(f, key("prototype"), Prop::Data { value: Value::Object(proto), flags: 0 })?; + self.define(proto, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?; + if heritage { + self.pop()?; + } + self.push(Value::Object(f))?; + self.push(Value::Object(proto)) + } + + /// An environment inside `outer` whose home object is `home`. + fn home_env(&mut self, home: ObjId, outer: EnvId) -> EnvId { + let mut bindings = PropMap::default(); + bindings.insert(Rc::from(HOME), Binding::new(Value::Object(home), false, false)); + self.heap.bytes += string_bytes(HOME.len()); + self.heap.alloc_env(Env::Decl { bindings, outer: Some(outer) }) + } + + /// `F proto key` → `F proto`: defines the method `functions[func]` (`kind` 0), getter (1) or + /// setter (2) named `key` on the prototype, or with `is_static` on the constructor (section + /// 14.3.8 and 14.5.14, step 21). + pub(crate) fn op_class_method(&mut self, func: u32, kind: u8, is_static: bool) -> JsResult<()> { + let kv = self.peek(0)?; + let k = self.to_prop_key(&kv)?; + let Value::Object(target) = self.peek(if is_static { 2 } else { 1 })? else { return internal("class operand is not an object") }; + self.define_method(target, k, func, kind, false)?; + self.pop().map(drop) + } + + /// `object` → `object`: defines an object literal's method or accessor `functions[func]` + /// under `names[name]` (section 12.2.6.8). + pub(crate) fn op_init_method(&mut self, func: u32, kind: u8, name: u32) -> JsResult<()> { + let k = self.name(name)?; + let Value::Object(target) = self.peek(0)? else { return internal("object literal is not an object") }; + self.define_method(target, PropKey::Str(k), func, kind, true) + } + + /// `object key` → `object`: defines an object literal's method or accessor `functions[func]` + /// under a computed key, already a name or a Symbol (section 12.2.6.8). + pub(crate) fn op_init_method_key(&mut self, func: u32, kind: u8) -> JsResult<()> { + let kv = self.peek(0)?; + let k = self.to_prop_key(&kv)?; + let Value::Object(target) = self.peek(1)? else { return internal("object literal is not an object") }; + self.define_method(target, k, func, kind, true)?; + self.pop().map(drop) + } + + /// Defines the method (`kind` 0), getter (1) or setter (2) made from `functions[func]` of the + /// running code under `k` on `target`, its home object (MakeMethod, section 14.3.8), and + /// names the function after `k`, with `get ` or `set ` before an accessor's name (section + /// 9.2.11). The caller keeps `target` and a Symbol key reachable. + fn define_method(&mut self, target: ObjId, k: PropKey, func: u32, kind: u8, enumerable: bool) -> JsResult<()> { + self.use_fuel()?; + let frame = self.frame()?; + let env = frame.env; + let Some(code) = frame.code.functions.get(func as usize).cloned() else { return internal("function out of range") }; + let named = code.own_name.is_some(); + let key_bytes = match &k { + PropKey::Str(name) => binding_bytes(name.len()), + PropKey::Sym(_) => binding_bytes(0), + }; + let need = OBJECT_BYTES + .saturating_add(ENV_BYTES) + .saturating_add(binding_bytes(HOME.len())) + .saturating_add(closure_bytes(&code)) + .saturating_add(key_bytes); + let root = match &k { + PropKey::Str(name) => Value::String(Str::from_rc(name.clone())), + PropKey::Sym(s) => Value::Symbol(s.clone()), + }; + self.rooted(std::slice::from_ref(&root), |i| i.reserve_heap(need))?; + let home = self.home_env(target, env); + let f = self.make_closure(code, home)?; + if named { + let prefix = match kind { + 0 => NamePrefix::None, + 1 => NamePrefix::Get, + _ => NamePrefix::Set, + }; + self.rooted(&[Value::Object(f), root], |i| { + let name = i.key_name(prefix, &k)?; + i.set_function_name(f, name) + })?; + } + let (enumerable, configurable) = (Some(enumerable), Some(true)); + let desc = match kind { + 0 => Desc { value: Some(Value::Object(f)), writable: Some(true), enumerable, configurable, ..Desc::default() }, + 1 => Desc { get: Some(Some(f)), enumerable, configurable, ..Desc::default() }, + _ => Desc { set: Some(Some(f)), enumerable, configurable, ..Desc::default() }, + }; + self.rooted(&[Value::Object(f)], |i| i.define_own_pk(target, k, &desc, true)).map(drop) + } + + /// The `name` of a function defined under `k`: the name with `prefix` before it, or a + /// Symbol's description in brackets, or `prefix` alone for a Symbol without one (SetFunctionName, + /// section 9.2.11). + fn key_name(&mut self, prefix: NamePrefix, k: &PropKey) -> JsResult { + match k { + PropKey::Str(name) if prefix == NamePrefix::None => Ok(Value::String(Str::from_rc(name.clone()))), + PropKey::Str(name) => self.wrap_str(prefix.text(), Some(&Str::from_rc(name.clone())), ""), + PropKey::Sym(s) => match s.description() { + Some(d) => { + let d = d.clone(); + self.wrap_str(&format!("{}[", prefix.text()), Some(&d), "]") + } + None => self.wrap_str(prefix.text(), None, ""), + }, + } + } + + /// `this key` → `this home key`: the prototype of the running method's home object, `null` + /// when it has none, and the key as a property name or a Symbol (MakeSuperPropertyReference, + /// section 12.3.5.3). + pub(crate) fn op_super_ref(&mut self) -> JsResult<()> { + let kv = self.peek(0)?; + let k = match self.to_prop_key(&kv)? { + PropKey::Str(name) => Value::String(Str::from_rc(name)), + PropKey::Sym(s) => Value::Symbol(s), + }; + let Value::Object(home) = self.hidden_value(HOME)? else { return Err(self.throw(ErrorType::Syntax, "'super' is allowed only in methods")) }; + let proto = self.object(home)?.proto.map_or(Value::Null, Value::Object); + self.replace(1, proto)?; + self.push(k) + } + + /// The three operands of a `super` property: `this`, the prototype and the key. + fn super_operands(&mut self, depth: usize) -> JsResult<(Value, ObjId, PropKey)> { + let k = self.peek(depth)?; + let proto = self.peek(depth + 1)?; + let this = self.peek(depth + 2)?; + let k = self.to_prop_key(&k)?; + let Value::Object(p) = proto else { + let name = self.pk_name(&k)?; + return Err(self.type_error(&format!("cannot use super property '{name}': the home object has no prototype"))); + }; + Ok((this, p, k)) + } + + /// The key as text for a message. + fn pk_name(&mut self, k: &PropKey) -> JsResult { + match k { + PropKey::Str(name) => Ok(String::from_utf16_lossy(name)), + PropKey::Sym(s) => self.sym_name(s), + } + } + + /// The property `k` of `start` or an object it inherits from. + fn find_pk(&mut self, start: ObjId, k: &PropKey) -> JsResult> { + match k { + PropKey::Str(name) => self.find_property(start, name), + PropKey::Sym(s) => self.find_sym(start, s), + } + } + + /// [[Get]] of `k` from `start` with `receiver` as `this`. + fn get_pk_from(&mut self, start: ObjId, k: &PropKey, receiver: &Value) -> JsResult { + match k { + PropKey::Str(name) => self.get_from(start, name, receiver), + PropKey::Sym(s) => self.get_sym_from(start, s, receiver), + } + } + + /// `this home key` → `value`, or with `with_this` → `value this`. + pub(crate) fn op_super_get(&mut self, with_this: bool) -> JsResult<()> { + let (this, p, k) = self.super_operands(0)?; + let v = self.get_pk_from(p, &k, &this)?; + self.replace(3, v)?; + if with_this { self.push(this) } else { Ok(()) } + } + + /// `this home key value` → `value`. + pub(crate) fn op_super_set(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let (this, p, k) = self.super_operands(1)?; + self.super_put(p, k, v.clone(), &this)?; + self.replace(4, v) + } + + /// `this home key` → the old or new number of a `++` or `--` on a `super` property. + pub(crate) fn op_super_inc(&mut self, prefix: bool, dec: bool) -> JsResult<()> { + let (this, p, k) = self.super_operands(0)?; + let v = self.get_pk_from(p, &k, &this)?; + let old = self.to_number(&v)?; + let new = if dec { old - 1.0 } else { old + 1.0 }; + self.super_put(p, k, Value::Number(new), &this)?; + self.replace(3, Value::Number(if prefix { new } else { old })) + } + + /// [[Set]] of `k` on `proto` with `receiver` as `this` (OrdinarySet, section 9.1.9). A write + /// that cannot be made throws a `TypeError` in strict mode code and in code from a source with + /// [`crate::bytecode::Source::strict_writes`], and does nothing otherwise (PutValue, section + /// 6.2.3.2). + fn super_put(&mut self, proto: ObjId, k: PropKey, v: Value, receiver: &Value) -> JsResult<()> { + let throw = self.strict_writes(); + let why = match self.find_pk(proto, &k)? { + Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), receiver, &[v]).map(drop), + Some(Prop::Accessor { set: None, .. }) => Some("it has only a getter"), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => Some("it is read-only"), + _ => None, + }; + let (r, desc) = match (why, receiver) { + (Some(why), _) => return self.super_reject(throw, &k, why), + (None, Value::Object(r)) => match self.get_own_pk(*r, &k)? { + Some(Prop::Accessor { .. }) => return self.super_reject(throw, &k, "it is an accessor"), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.super_reject(throw, &k, "it is read-only"), + Some(Prop::Data { .. }) => (*r, Desc { value: Some(v), ..Desc::default() }), + None => (*r, Desc::data(v, WRITABLE | ENUMERABLE | CONFIGURABLE)), + }, + (None, _) => return self.super_reject(throw, &k, "`this` is a primitive value"), + }; + self.define_own_pk(r, k, &desc, throw).map(drop) + } + + fn super_reject(&mut self, throw: bool, k: &PropKey, why: &str) -> JsResult<()> { + if !throw { + return Ok(()); + } + let name = self.pk_name(k)?; + Err(self.type_error(&format!("cannot assign to property '{name}': {why}"))) + } + + /// Pushes the constructor `super(…)` calls: the prototype of the running derived class + /// constructor (GetSuperConstructor, section 12.3.5.2). + pub(crate) fn op_super_ctor(&mut self) -> JsResult<()> { + let Value::Object(f) = self.hidden_value(FUNC)? else { return Err(self.throw(ErrorType::Syntax, "'super' is allowed only in constructors")) }; + let proto = self.object(f)?.proto.map_or(Value::Null, Value::Object); + self.push(proto) + } + + /// `ctor args…` → the object `ctor` constructs with the running code's `new.target` + /// (section 12.3.5.1, steps 6 to 9). + pub(crate) fn op_super_call(&mut self, argc: u32) -> JsResult<()> { + let n = argc as usize; + let start = + self.stack.len().checked_sub(n + 1).filter(|&s| s >= self.base()).ok_or_else(|| Abrupt::Internal("super call below the stack".into()))?; + let ctor = self.stack.get(start).cloned().unwrap_or(Value::Undefined); + if !self.is_constructor(&ctor) { + return Err(self.type_error("the superclass is not a constructor")); + } + let Value::Object(nt) = self.hidden_value(NEW_TARGET)? else { return Err(self.type_error("super() needs new.target")) }; + let args: Vec = self.stack.get(start + 1..).map(<[Value]>::to_vec).unwrap_or_default(); + self.construct(start, ctor, args, Some(nt)) + } + + /// `value` → `value`: binds the running derived class constructor's `this` to the object + /// `super(…)` made; a second binding is a `ReferenceError` (section 8.1.1.3.1). + pub(crate) fn op_bind_this(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let frame = self.frame()?; + let (start, own) = (frame.env, frame.this_env); + let Some(env) = self.hidden_env(start, ARROW_THIS) else { return internal("super() outside a derived constructor") }; + if !self.uninitialized(env, ARROW_THIS) { + return Err(self.throw(ErrorType::Reference, "super() was already called")); + } + if let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(env) + && let Some(b) = bindings.get_mut(ARROW_THIS) + { + b.value = v.clone(); + b.uninitialized = false; + } + if own == Some(env) { + self.frame_mut()?.this = v; + } + Ok(()) + } + + /// Pushes `new.target` (section 12.3.8.1). + pub(crate) fn op_new_target(&mut self) -> JsResult<()> { + let frame = self.frame()?; + let v = if frame.code.arrow { self.hidden_value(NEW_TARGET)? } else { frame.new_target.map_or(Value::Undefined, Value::Object) }; + self.push(v) + } +} diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs index cbc35d3929..31230e4958 100644 --- a/crates/js/src/collections_tests.rs +++ b/crates/js/src/collections_tests.rs @@ -131,10 +131,11 @@ fn iterators_step_through_live_entries() { } #[test] -fn constructors_read_arrays_strings_and_array_likes() { +fn constructors_read_arrays_and_strings() { truth("var m = new Map([[1, 'a'], [2, 'b']]); m.size === 2 && m.get(2) === 'b'"); truth("new Set('ab\u{1F600}b').size === 3"); - truth("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'}).size === 2"); + // An object without `@@iterator` is not iterable, whatever its `length` (section 23.2.1.1). + throws("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'})", "TypeError"); truth("new Map(null).size === 0 && new Set(undefined).size === 0"); truth("Object.prototype.toString.call(new Set()) === '[object Set]' && Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'"); throws("Map()", "TypeError"); @@ -146,7 +147,8 @@ fn constructors_read_arrays_strings_and_array_likes() { truth("Uint8Array.from({}).length === 0 && new Uint8Array({}).length === 0 && DataView.length === 1 && Uint8Array.length === 3"); // `from` reads each element of an array-like source just before mapping it (section 22.2.2.1). truth("var src = {length: 2, 0: 1, 1: 1}; Uint8Array.from(src, function (v, i) { src[1] = 7; return v; }).join() === '1,7'"); - truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,14'"); + // An iterable source is read to the end before the first value is mapped (section 22.2.2.1.1). + truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,2'"); truth("Uint8Array.from('ab', function (v) { return v.charCodeAt(0); }).join() === '97,98'"); throws("Map.prototype.get.call({}, 1)", "TypeError"); throws("Object.getOwnPropertyDescriptor(Map.prototype, 'size').get.call(new Set())", "TypeError"); @@ -158,6 +160,86 @@ fn constructors_read_arrays_strings_and_array_likes() { truth("JSON.stringify(new Map([[1, 2]])) === '{}' && JSON.stringify(new Set([1])) === '{}'"); } +/// An iterable that gives `values` and counts the calls of its `return` method in `closed`. +const CLOSING: &str = "var closed = 0; function closing(values) { var i = 0; return { [Symbol.iterator]: function () { return this; }, \ + next: function () { return i < values.length ? { value: values[i++], done: false } : { done: true }; }, \ + return: function () { closed++; return {}; } }; }"; + +#[test] +fn constructors_read_their_argument_through_its_iterator() { + // GetIterator and IteratorStep (sections 23.1.1.1, 23.2.1.1, 23.3.1.1, 23.4.1.1 and 22.2.1.4). + truth("function* g() { yield 1; yield 2; yield 1; } var s = new Set(g()); s.size === 2 && s.has(2)"); + truth("function* g() { yield ['a', 1]; yield ['b', 2]; } new Map(g()).get('b') === 2"); + truth("function* g() { yield 3; yield 4; } new Uint8Array(g()).join() === '3,4' && Int16Array.from(g()).join() === '3,4'"); + truth(&format!("{CLOSING} var s = new Set(closing(['x', 'y'])); s.size === 2 && s.has('y') && closed === 0")); + truth(&format!( + "{CLOSING} var k = {{}}; var w = new WeakMap(closing([[k, 5]])); var ws = new WeakSet(closing([k])); w.get(k) === 5 && ws.has(k)" + )); + truth(&format!("{CLOSING} new Float64Array(closing([1.5, 2])).join() === '1.5,2' && closed === 0")); + // A string is read by code point, as its iterator reads it. + truth("new Set('\\uD83D\\uDE00\\uD83D\\uDE00').size === 1 && new Set('\\uD83D\\uDE00x').has('\\uD83D\\uDE00')"); + truth("var m = new Map([[1, 'a']]); Array.prototype.join.call(Uint8Array.from(m.keys())) === '1'"); + // An array is read through its `@@iterator`, not by index. + truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; var s = new Set(a); s.has(9) && !s.has(1)"); + truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; new Uint8Array(a).join() === '9'"); + // An object without `@@iterator` is still read by index by the typed array constructors. + truth("new Uint8Array({length: 2, 0: 1, 1: 2}).join() === '1,2'"); + throws("new Set({ [Symbol.iterator]: 1 })", "TypeError"); + throws("new Uint8Array({ [Symbol.iterator]: 1 })", "TypeError"); +} + +#[test] +fn collections_and_typed_arrays_are_iterable() { + // Sections 23.1.3.12, 23.2.3.11 and 22.2.3.30. + truth("Map.prototype[Symbol.iterator] === Map.prototype.entries && Set.prototype[Symbol.iterator] === Set.prototype.values"); + truth("var p = Object.getPrototypeOf(Int8Array.prototype); p[Symbol.iterator] === p.values"); + truth("var m = new Map([[1, 'a'], [2, 'b']]); var out = []; for (var e of m) out.push(e.join(':')); out.join() === '1:a,2:b'"); + truth("var out = []; for (var v of new Set([3, 4])) out.push(v); for (var v of new Int8Array([5])) out.push(v); out.join() === '3,4,5'"); + truth("var m = new Map([[1, 2]]); new Map(m).get(1) === 2 && new Set(new Set([7])).has(7) && new Set(new Uint8Array([8])).has(8)"); + // The iterators inherit `%IteratorPrototype%[@@iterator]` (sections 23.1.5.2, 23.2.5.2 and 22.1.5.2). + truth("var it = new Map().keys(); it[Symbol.iterator]() === it && new Set([1]).values()[Symbol.iterator]().next().value === 1"); + truth("var it = new Int8Array([6]).values(); it[Symbol.iterator]() === it && [...new Set([1, 2]).keys()].join() === '1,2'"); +} + +#[test] +fn a_map_entry_that_is_not_an_object_closes_the_iterator() { + // Section 23.1.1.1, step 10.d. + truth(&format!("{CLOSING} var caught; try {{ new Map(closing([1])); }} catch (e) {{ caught = e instanceof TypeError; }} caught && closed === 1")); + truth(&format!( + "{CLOSING} var caught; try {{ new WeakMap(closing(['k'])); }} catch (e) {{ caught = e instanceof TypeError; }} caught && closed === 1" + )); +} + +#[test] +fn an_iterator_whose_next_throws_is_not_closed() { + let src = "var closed = 0; var it = { [Symbol.iterator]: function () { return this; }, \ + next: function () { throw new RangeError('next'); }, return: function () { closed++; return {}; } };"; + for make in ["new Set(it)", "new Map(it)", "new WeakSet(it)", "new Uint8Array(it)", "Uint8Array.from(it)"] { + truth(&format!( + "{src} var caught; try {{ {make}; }} catch (e) {{ caught = e instanceof RangeError && e.message === 'next'; }} caught && closed === 0" + )); + } +} + +#[test] +fn a_throwing_adder_closes_the_iterator() { + // IteratorClose (section 7.4.6) keeps the adder's exception, even when `return` throws too. + for (ctor, adder) in [("Set", "add"), ("Map", "set"), ("WeakSet", "add"), ("WeakMap", "set")] { + let src = format!( + "{CLOSING} var o = {{}}; {ctor}.prototype.{adder} = function () {{ throw new RangeError('adder'); }}; var caught; \ + try {{ new {ctor}(closing([[o, 1], [o, 2]])); }} catch (e) {{ caught = e instanceof RangeError && e.message === 'adder'; }}" + ); + truth(&format!("{src} caught && closed === 1")); + let throwing = src.replace("closed++; return {};", "closed++; throw new TypeError('return');"); + truth(&format!("{throwing} caught && closed === 1")); + } + // A Map entry whose `0` getter throws closes the iterator as well. + truth(&format!( + "{CLOSING} var bad = {{ get 0() {{ throw new RangeError('key'); }} }}; var caught; \ + try {{ new Map(closing([bad])); }} catch (e) {{ caught = e.message === 'key'; }} caught && closed === 1" + )); +} + // ---- WeakMap and WeakSet ---- #[test] @@ -220,7 +302,9 @@ fn collections_of_millions_end_at_the_limits() { assert_eq!(limit(&heap, "var m = new Map(); for (var i = 0; ; i++) m.set(i, i);"), LimitKind::Heap); assert_eq!(limit(&heap, "var s = new Set(); for (var i = 0; ; i++) s.add('k' + i);"), LimitKind::Heap); let fuel = Limits { fuel: 100_000, ..Limits::default() }; - assert_eq!(limit(&fuel, "new Set({length: 1e15})"), LimitKind::Fuel); + let endless = "{ [Symbol.iterator]: function () { return { next: function () { return { value: 1, done: false }; } }; } }"; + assert_eq!(limit(&fuel, &format!("new Set({endless})")), LimitKind::Fuel); + assert_eq!(limit(&fuel, &format!("new Uint8Array({endless})")), LimitKind::Fuel); let m = "var m = new Map(); for (var i = 0; i < 1000; i++) m.set(i, i); m.forEach(function () { for (;;) {} });"; assert_eq!(limit(&fuel, m), LimitKind::Fuel); } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index f4314f2e5e..ee3151cd2d 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -19,8 +19,8 @@ use std::collections::{HashMap, HashSet}; use std::rc::Rc; use crate::ast::{ - AssignOp, Ast, BinaryOp, Binding, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, Property, PropertyKey, - PropertyValue, Stmt, StmtId, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, + AssignOp, Ast, BinaryOp, Binding, ClassDef, ClassKey, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, + MethodKind, Property, PropertyKey, PropertyValue, Stmt, StmtId, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, }; use crate::bytecode::{BlockScope, Code, CodeKind, Handler, NamePrefix, Op, Source, Template, fallthrough_effect, verify}; use crate::error::{SyntaxError, TOO_DEEP}; @@ -100,6 +100,7 @@ struct FnCompiler<'a> { scopes: Vec, templates: Vec