diff --git a/.gitattributes b/.gitattributes index e3ff66fc1c..dc4403a4db 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,4 @@ # The DXF writer goldens are compared byte for byte with the writer's output (LF line endings). crates/cad/tests/data/*.dxf -text +# `cargo xtask ui-commands --check` compares this file byte for byte with rustfmt's output (LF line endings). +crates/mcp/src/ui_catalog.rs -text diff --git a/.github/scripts/release-rpm-smoke.py b/.github/scripts/release-rpm-smoke.py index 3d70cca7c1..27ba643b27 100644 --- a/.github/scripts/release-rpm-smoke.py +++ b/.github/scripts/release-rpm-smoke.py @@ -51,16 +51,28 @@ def run_smoke(results): time.sleep(1) channel.settimeout(30) with channel, channel.makefile("rwb") as stream: - for request_id, method, params in ( - (0, "auth", {"token": token}), - (1, "ui.inspect", {}), - ): + def request(request_id, method, params): stream.write((json.dumps(dict(id=request_id, method=method, params=params)) + "\n").encode()) stream.flush() response = json.loads(stream.readline()) (results / f"{method}.json").write_text(json.dumps(response, indent=2)) if response.get("id") != request_id or response.get("ok") is not True: raise RuntimeError(f"GUI request failed: {method}") + return response.get("result") or {} + + request(0, "auth", {"token": token}) + # The fixture opens off the UI thread: inspect until it is listed as an open document. + deadline = time.monotonic() + 90 + request_id = 1 + while True: + state = request(request_id, "ui.inspect", {}) + titles = [d.get("title", "") for d in state.get("documents", [])] + if not state.get("opening") and fixture.name in titles: + break + if time.monotonic() >= deadline: + raise RuntimeError(f"GUI did not open the fixture; open documents: {titles}") + request_id += 1 + time.sleep(1) finally: app.terminate() try: diff --git a/.github/scripts/tests/test_release_rpm_smoke.py b/.github/scripts/tests/test_release_rpm_smoke.py index 9d92237534..536702a69d 100644 --- a/.github/scripts/tests/test_release_rpm_smoke.py +++ b/.github/scripts/tests/test_release_rpm_smoke.py @@ -27,7 +27,7 @@ class SmokeLifecycleTests(unittest.TestCase): self.channel = MagicMock() self.stream = self.channel.makefile.return_value.__enter__.return_value self.stream.readline.side_effect = [ - b'{"id":0,"ok":true}\n', b'{"id":1,"ok":true,"result":{"window":"fixture"}}\n', + b'{"id":0,"ok":true}\n', self.inspection(1, ["original-smoke.svg"]), ] self.runtime = None @@ -41,6 +41,11 @@ class SmokeLifecycleTests(unittest.TestCase): self.connect = self.start_patch(smoke.socket, "create_connection", return_value=self.channel) self.start_patch(smoke.time, "sleep") + @staticmethod + def inspection(request_id, titles, opening=()): + result = {"documents": [{"title": title, "dirty": False} for title in titles], "opening": list(opening)} + return (json.dumps({"id": request_id, "ok": True, "result": result}) + "\n").encode() + def start_patch(self, owner, name, **kwargs): patcher = patch.object(owner, name, **kwargs) result = patcher.start() @@ -54,7 +59,7 @@ class SmokeLifecycleTests(unittest.TestCase): def test_success_records_inspection_and_removes_private_runtime(self): smoke.run_smoke(self.results) report = json.loads((self.results / "ui.inspect.json").read_text()) - self.assertEqual(report["result"], {"window": "fixture"}) + self.assertEqual(report["result"]["documents"][0]["title"], "original-smoke.svg") requests = [json.loads(call.args[0]) for call in self.stream.write.call_args_list] self.assertEqual(requests[0]["method"], "auth") self.assertEqual(requests[0]["params"]["token"], self.launch.call_args.kwargs["env"]["VECTORCRAFT_CONTROL_TOKEN"]) @@ -99,6 +104,25 @@ class SmokeLifecycleTests(unittest.TestCase): smoke.run_smoke(self.results) self.assert_cleaned_up() + def test_inspection_is_repeated_while_the_fixture_is_opening(self): + self.stream.readline.side_effect = [ + b'{"id":0,"ok":true}\n', + self.inspection(1, [], opening=["/results/original-smoke.svg"]), + self.inspection(2, ["original-smoke.svg"]), + ] + smoke.run_smoke(self.results) + requests = [json.loads(call.args[0]) for call in self.stream.write.call_args_list] + self.assertEqual([r["method"] for r in requests], ["auth", "ui.inspect", "ui.inspect"]) + self.assertEqual([r["id"] for r in requests], [0, 1, 2]) + self.assert_cleaned_up() + + def test_fixture_that_never_opens_is_a_failure(self): + self.stream.readline.side_effect = [b'{"id":0,"ok":true}\n', self.inspection(1, ["Untitled-1"])] + self.start_patch(smoke.time, "monotonic", side_effect=[0, 0, 91]) + with self.assertRaisesRegex(RuntimeError, "did not open the fixture"): + smoke.run_smoke(self.results) + self.assert_cleaned_up() + def test_malformed_response_still_stops_child(self): self.stream.readline.side_effect = [b'not json\n'] with self.assertRaises(json.JSONDecodeError): diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 47f46692aa..53a9be4e4a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,19 +9,23 @@ on: branches: [main] schedule: - cron: "37 3 * * *" + # `labeled` so adding the `full-ci` label starts a run of all six shards. pull_request: + types: [opened, synchronize, reopened, labeled] workflow_dispatch: permissions: contents: read -# A newer push to a PR branch cancels its older run; every push to main runs to the end. +# A newer push to a PR branch cancels its older run; every push to main runs to the end. Adding +# any label other than `full-ci` gets a group of its own, so it never cancels a real run. concurrency: - group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + group: ci-${{ github.event_name == 'pull_request' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: gate: + if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: @@ -47,6 +51,19 @@ jobs: test-shards: 6 shard-command: cargo xtask ci shard warm-command: cargo xtask ci warm + # A pull request runs only the test shards whose crates its changes reach: the crates that + # own a changed file or declare a read of it (`[package.metadata.craft] reads`), and every + # crate that depends on them. Shard 6 runs on every event. The `select legs` log lists the + # shards left out and why; pushes to main, the nightly run and the `full-ci` label run all + # six. `shard-members` names each shard's crates, as xtask/src/shards.rs › GROUPS does. + select-tests: true + shard-members: | + vectorcraft-ui-egui + vectorcraft-ui-egui + vectorcraft-engine + vectorcraft vectorcraft-web vectorcraft-cli vectorcraft-mcp xtask + (rest) + (always) # The warm build runs as one `cache warm /6` leg per shard, in parallel (each builds what # its shard builds), and `cache warm` puts their files into the one entry it saves. warm-split: true diff --git a/AGENTS.md b/AGENTS.md index bac119a742..2e02266c6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- For the crates you changed: `cargo fmt`, `cargo clippy -p --all-targets`, `cargo xtask test` or `cargo nextest run -p `. Repository-wide steps when they apply: `cargo xtask assets`, `cargo xtask brands`, `cargo xtask layers`, `cargo xtask wasm`. `cargo xtask ci` runs all of them. Workspace lints (`unsafe_code = "deny"`, no `unwrap`/`expect`/`panic!` outside tests) are in `Cargo.toml`. ### Paths and conventions -- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. +- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. Doc tests are built without the workspace lints, so every library root carries `#![doc(test(attr(forbid(unsafe_code))))]` (`deny` in a crate without `#![forbid(unsafe_code)]`), and `cargo xtask layers` reports a root without it. - Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns. - Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty. - Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`. diff --git a/Cargo.lock b/Cargo.lock index 383ccf4059..be4b734a08 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "accesskit" -version = "0.25.1" +version = "0.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" dependencies = [ "uuid", ] @@ -27,9 +27,9 @@ dependencies = [ [[package]] name = "accesskit_consumer" -version = "0.39.1" +version = "0.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" dependencies = [ "accesskit", "hashbrown 0.17.1", @@ -51,9 +51,9 @@ dependencies = [ [[package]] name = "accesskit_macos" -version = "0.27.1" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4" +checksum = "123828ceeec755b05255e3976cb0852993202de98a0626c97dd8d34246991f84" dependencies = [ "accesskit", "accesskit_consumer", @@ -1836,6 +1836,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-pbr" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +dependencies = [ + "craft-texture", + "thiserror 2.0.21", +] + [[package]] name = "craft-pcraft-format" version = "0.1.0" @@ -2079,6 +2088,14 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "craft-texture" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-theme" version = "0.1.0" @@ -2883,6 +2900,7 @@ dependencies = [ "raw-window-handle", "smithay-clipboard", "web-time", + "webbrowser", "windows-sys 0.61.2", "winit", ] @@ -8741,6 +8759,7 @@ dependencies = [ "skrifa 0.47.0", "thiserror 2.0.21", "tiff", + "unicode-normalization", "vectorcraft-affinity", "vectorcraft-apischema", "vectorcraft-brush", @@ -9101,6 +9120,7 @@ dependencies = [ name = "vectorcraft-three-d" version = "0.25.1" dependencies = [ + "craft-pbr", "proptest", "vectorcraft-geom 0.25.1", "vectorcraft-pathops 0.25.1", @@ -9623,6 +9643,22 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webbrowser" +version = "1.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b31216ad837f3f4062538be333d8431d37c11832ef86924a3d0ad50defdc2f" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + [[package]] name = "webpki-root-certs" version = "1.0.11" diff --git a/Cargo.toml b/Cargo.toml index 843f9cbb53..7dab0c8895 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,6 +45,8 @@ craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ec craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +# The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with. +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } diff --git a/README.md b/README.md index 366b0711a8..3280824dc8 100644 --- a/README.md +++ b/README.md @@ -257,7 +257,7 @@ All 57 approximated Photoshop-style raster filters are available. The Effect Gal **What's missing:** - reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art); - an interaction-fidelity pass covering every tool's modifiers and small behaviours; -- the rest of 3D and Materials (base and Adobe Substance materials, shadows from lights after the first, ray-traced rendering, Turntable; see [docs/three-d.md](docs/three-d.md)); +- the rest of 3D and Materials (Adobe Substance materials, adding or deleting materials, shadows from lights after the first, ray-traced rendering, Turntable; the base material's Roughness and Metallic are built; see [docs/three-d.md](docs/three-d.md)); - CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface); - scripting, and the rest of Variables (image and graph kinds, dataset import); - generative AI features. diff --git a/ROADMAP.md b/ROADMAP.md index 84e40bc444..8b29a40471 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,6 +1,6 @@ # VectorCraft Roadmap -**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away +**Stage: alpha** · next: beta, ~8 points (ready for real work ~67% → ~75%, and reliable `.ai` exchange) and ~170–270 h away > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-22 · **Change:** minor (Upcoming: G11 names what is left (#864's unit preference, #885), not the fixed Shape Builder regions and Asset Export borders, with docs/roadmap.md's 6–13 h, and the Essentials row names Shape Builder's remaining depth, #8314; previously: G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) @@ -95,7 +95,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta | Language | Code | Status | Translated | |---|---|---|---:| | English | `en` | full | 100% | -| Simplified Chinese | `zh-hans` | partial (messages translated, #2578) | 85% | +| Simplified Chinese | `zh-hans` | partial (most messages translated, #2578; some remain untranslated) | 85% | | Spanish | `es` | full | 100% | | Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner | | Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial | @@ -124,7 +124,12 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips (#10659). Headline numbers unchanged. + +- 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied. + - 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. +- 2026-11-29: 3D and Materials › Materials › Properties: Roughness and Metallic for Extrude & Bevel, Revolve, Inflate and Rotate, shaded with glTF 2.0's metallic-roughness BRDF and written into glTF and USD exports ([three-d.md](docs/three-d.md#material-properties)); scores and estimates unchanged. - 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. @@ -172,6 +177,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Flood Fill Artboards joins the Document Tools add-on (Object › Plug-ins › Document Tools): an editable rectangle exactly the size of the active artboard, or of every artboard, in the current fill or a chosen color with no stroke (a chosen RGB color goes into the document's color model, or stays RGB with `keepModel`), on a layer named Flood Fill (or another name typed), which is made at the bottom of the layers when no top-level layer has that name and otherwise keeps its lock and visibility (a layer that holds a clipping mask is refused). A dialog with Preview, one undo step (`addon.document.floodFillArtboards`). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index c01f84edd9..51d2aec7b6 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -3,9 +3,9 @@ //! ```text //! vectorcraft-cli --safe-mode SUBCOMMAND ... //! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... -//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] +//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] //! 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 convert IN OUT [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] [--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] @@ -98,12 +98,16 @@ USAGE: heavy budget does not install there. With VECTORCRAFT_NO_PREFS set there is no store either, and a grant accepted under this flag lasts for that session only. - vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] [--allow-plugin-grants] + vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] [--width N] [--height N] [--background V] [--allow-plugin-grants] Headless batch: open FILE (any readable format) or start a new document, run commands in order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE is a template, written as file.saveAsTemplate writes it). Raster exports use the document's raster effects resolution unless --scale (pixels per point) or --ppi (pixels per inch, wins - over --scale) is given; other formats leave them out. Prints one JSON result per step. + over --scale) is given. --width or --height sets the size of each raster file in pixels, the + other side in proportion (--width wins over --height, and both win over --ppi and --scale), + within 0.01 to 64 pixels per point. + --background is transparent, none, white, black or a color such as #ff8800. Other formats + leave these options out. Prints one JSON result per step. --commands reads steps from FILE, or from standard input for -, where it stands among the --cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for \"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps. @@ -114,10 +118,13 @@ USAGE: vectorcraft-cli commands Print the command catalogue as JSON. - vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--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 convert IN OUT [--scale N] [--ppi N] [--width N] [--height N] [--background V] [--artboard I | --range R] [--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] Open IN (any readable format) and export OUT in the format its extension picks (see Writable - formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects - resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard + formats). Raster size: --width, else --height (pixels, the other side in proportion, within + 0.01 to 64 pixels per point), else --ppi, else 72 times --scale, else the document's raster + effects resolution. --background + is transparent, none, white, black or a color such as #ff8800. Other formats leave these + options out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard unless one of them is given, EPS the bounds of the art, the other formats the first artboard. A .ait OUT is a template of every artboard, written as file.saveAsTemplate writes it (not with --artboard or --range). @@ -367,6 +374,9 @@ fn convert(args: &[String]) -> Result<(), String> { "--scale", "-s", "--ppi", + "--width", + "--height", + "--background", "--artboard", "-a", "--range", @@ -381,9 +391,9 @@ fn convert(args: &[String]) -> Result<(), String> { return help(); } let mut files = vec![]; - let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) = - (None::, None::, None::, false, false, false, false); - let mut ppi = None::; + let (mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) = + (None::, None::, false, false, false, false); + let mut size = RasterSize::default(); let mut decimals = None::; // The encoding of a legacy `.ai`'s names that aren't UTF-8, passed on as `document.open`'s // `legacyNameEncoding`; the engine checks it. @@ -394,15 +404,11 @@ fn convert(args: &[String]) -> Result<(), String> { let mut it = args.iter(); while let Some(a) = it.next() { match a.as_str() { - "--scale" | "-s" => scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?), - "--ppi" => { - ppi = Some( - it.next() - .and_then(|v| v.parse().ok()) - .filter(|n: &f64| n.is_finite() && *n > 0.0) - .ok_or("--ppi needs a positive finite number")?, - ); - } + "--scale" | "-s" => size.scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?), + "--ppi" => size.ppi = Some(positive("--ppi", it.next())?), + "--width" => size.width = Some(positive("--width", it.next())?), + "--height" => size.height = Some(positive("--height", it.next())?), + "--background" => size.background = Some(background_flag(it.next())?), "--artboard" | "-a" => artboard = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--artboard needs an index")?), "--range" | "-r" => range = Some(it.next().cloned().ok_or("--range needs artboards such as 1-3,5")?), "--outline-text" => outline_text = true, @@ -442,7 +448,7 @@ fn convert(args: &[String]) -> Result<(), String> { ("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy})) } else { let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy}); - let mut params = with_pixel_scale(params, &output, scale, ppi); + let mut params = with_pixel_scale(params, &output, &size); // An option the format doesn't read comes back in the warnings, so each goes out only // when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the // formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects, @@ -498,17 +504,58 @@ fn is_template(path: &str) -> bool { vectorcraft_engine::cmd::fileio::format_for_name(path).is_some_and(|f| f.id == "ait") } -/// The export `params` for `path`, with explicit raster resolution options only for raster formats. +/// The raster size and background options of `convert` and `run`: `--scale`, `--ppi`, `--width`, +/// `--height` and `--background`. The engine checks the background and applies the precedence +/// (width, then height, then ppi, then scale). +#[derive(Default)] +struct RasterSize { + scale: Option, + ppi: Option, + width: Option, + height: Option, + background: Option, +} + +/// A pixel size or resolution flag's value: a positive finite number. +fn positive(flag: &str, raw: Option<&String>) -> Result { + raw.and_then(|v| v.parse::().ok()) + .filter(|n| n.is_finite() && *n > 0.0) + .ok_or_else(|| format!("{flag} needs a positive finite number{}", raw.map(|r| format!(", not {r}")).unwrap_or_default())) +} + +/// A `--background` value, checked when the flag is read so that a bad or missing value is refused +/// for every output format: transparent, none, white, black or a color the engine reads. +fn background_flag(raw: Option<&String>) -> Result { + let ok = raw.filter(|v| { + ["transparent", "none", "white", "black"].iter().any(|k| v.eq_ignore_ascii_case(k)) + || vectorcraft_engine::cmd::color_value(&json!(v)).is_some() + }); + ok.cloned().ok_or_else(|| { + let got = raw.map(|r| format!(", not {r}")).unwrap_or_default(); + format!("--background needs transparent, none, white, black or a color such as #ff8800{got}") + }) +} + +/// The export `params` for `path`, with explicit raster size options only for raster formats. /// DXF has a `scale` of its own (drawing units per unit), which would resize the drawing and leave /// its units unset. -fn with_pixel_scale(mut params: Value, path: &str, scale: Option, ppi: Option) -> Value { +fn with_pixel_scale(mut params: Value, path: &str, size: &RasterSize) -> Value { if vectorcraft_engine::cmd::fileio::writable_format(None, Some(path)).is_ok_and(|f| f.raster) { - if let Some(scale) = scale { + if let Some(scale) = size.scale { params["scale"] = json!(scale); } - if let Some(ppi) = ppi { + if let Some(ppi) = size.ppi { params["ppi"] = json!(ppi); } + if let Some(width) = size.width { + params["width"] = json!(width); + } + if let Some(height) = size.height { + params["height"] = json!(height); + } + if let Some(background) = &size.background { + params["background"] = json!(background); + } } params } @@ -698,7 +745,23 @@ fn command_step(v: Value) -> Result { } fn run(args: &[String]) -> Result<(), String> { - let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s", "--ppi"]; + let valued = [ + "--in", + "-i", + "--cmd", + "-c", + "--params", + "-p", + "--commands", + "--export", + "-o", + "--scale", + "-s", + "--ppi", + "--width", + "--height", + "--background", + ]; if help_requested(args, &valued) { return help(); } @@ -707,8 +770,7 @@ fn run(args: &[String]) -> Result<(), String> { // The step of the `--cmd` just given, which a `--params` sets. let mut params_for: Option = None; let mut stdin_read = false; - let mut scale = None::; - let mut ppi = None::; + let mut size = RasterSize::default(); let mut allow_grants = false; let mut it = args.iter(); while let Some(a) = it.next() { @@ -747,17 +809,22 @@ fn run(args: &[String]) -> Result<(), String> { "--allow-plugin-grants" => allow_grants = true, "--scale" | "-s" => { let raw = val("a number")?; - scale = Some(raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?); + size.scale = Some(raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?); } - "--ppi" => { + "--ppi" | "--width" | "--height" => { let raw = val("a number")?; - ppi = Some( - raw.parse::() - .ok() - .filter(|n| n.is_finite() && *n > 0.0) - .ok_or_else(|| format!("--ppi {raw}: needs a positive finite number"))?, - ); + let n = raw + .parse::() + .ok() + .filter(|n| n.is_finite() && *n > 0.0) + .ok_or_else(|| format!("{a} {raw}: needs a positive finite number"))?; + match a.as_str() { + "--ppi" => size.ppi = Some(n), + "--width" => size.width = Some(n), + _ => size.height = Some(n), + } } + "--background" => size.background = Some(background_flag(Some(&val("a background")?))?), other => return Err(format!("unknown run option `{other}`")), } } @@ -801,7 +868,7 @@ fn run(args: &[String]) -> Result<(), String> { let r = if is_template(&path) { h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": path, "format": "ait"}})) } else { - h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale, ppi)) + h.call("app.export", with_pixel_scale(json!({"path": path}), &path, &size)) }; let r = r.map_err(|e| format!("step {n}: export {path}: {e}"))?; emit(json!({"step": "export", "result": r}))?; diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index cdb16d28d3..9593d2630e 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -135,6 +135,108 @@ fn raster_export_rejects_invalid_ppi() { } } +/// The pixel size in a PNG's IHDR. +fn png_size(path: &str) -> (u32, u32) { + let bytes = std::fs::read(path).unwrap(); + let be = |i: usize| u32::from_be_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]); + (be(16), be(20)) +} + +/// #10577: `convert` and `run --export` take `--width`, `--height` and `--background` for raster +/// outputs and leave them out of other formats. +#[test] +fn raster_export_takes_width_height_and_background() { + let source = tmp("size.vectorcraft"); + ok(&[ + "run", + "--cmd", + "file.new", + "--params", + r#"{"width":100,"height":50}"#, + "--cmd", + "document.setup", + "--params", + r#"{"backgroundContents":"white"}"#, + "--cmd", + "shape.rectangle", + "--params", + r#"{"x":40,"y":20,"width":20,"height":10}"#, + "--export", + &source, + ]); + let wide = tmp("wide.png"); + ok(&["convert", &source, &wide, "--width", "400"]); + assert_eq!(png_size(&wide), (400, 200)); + let high = tmp("high.png"); + ok(&["convert", &source, &high, "--height", "100", "--ppi", "300"]); + assert_eq!(png_size(&high), (200, 100)); + let both = tmp("both.png"); + ok(&["convert", &source, &both, "--width", "300", "--height", "10"]); + assert_eq!(png_size(&both), (300, 150), "--width wins over --height"); + let run = tmp("run.png"); + ok(&["run", "--in", &source, "--export", &run, "--width", "64"]); + assert_eq!(png_size(&run), (64, 32)); + + let clear = tmp("clear.png"); + ok(&["convert", &source, &clear, "--background", "transparent"]); + let img = vectorcraft_testkit::raster::Image::from_png(&std::fs::read(&clear).unwrap()).unwrap(); + assert_eq!(img.pixel(0, 0)[3], 0, "--background transparent wins over the document's white background"); + let orange = tmp("orange.png"); + ok(&["run", "--in", &source, "--export", &orange, "--background", "#ff8800"]); + let img = vectorcraft_testkit::raster::Image::from_png(&std::fs::read(&orange).unwrap()).unwrap(); + vectorcraft_testkit::raster::assert_pixel(&img, 0, 0, [255, 136, 0, 255], 1); + + // Other formats leave the options out. + let svg = tmp("size.svg"); + let plain = tmp("plain.svg"); + let r: Value = serde_json::from_str(&ok(&["convert", &source, &svg, "--width", "400", "--height", "9", "--background", "#ff8800"])).unwrap(); + let warnings = r["warnings"].as_array().cloned().unwrap_or_default(); + assert!(!warnings.iter().any(|w| w.as_str().is_some_and(|s| ["width", "height", "background"].iter().any(|k| s.contains(k)))), "{r}"); + ok(&["convert", &source, &plain]); + assert_eq!(std::fs::read(&svg).unwrap(), std::fs::read(&plain).unwrap()); +} + +#[test] +fn raster_export_warns_when_width_is_clamped() { + let source = tmp("clamped-size.vectorcraft"); + ok(&["run", "--cmd", "file.new", "--params", r#"{"width":16,"height":8}"#, "--export", &source]); + let output = tmp("clamped-width.png"); + let r: Value = serde_json::from_str(&ok(&["convert", &source, &output, "--width", "1920"])).unwrap(); + assert_eq!(png_size(&output).0, 1024); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|s| s.contains("1920"))), "{r}"); + for path in [source, output] { + let _ = std::fs::remove_file(path); + } +} + +#[test] +fn raster_export_rejects_invalid_width_height_and_background() { + for (flag, value, message) in [ + ("--width", "0", "positive finite number"), + ("--width", "abc", "positive finite number"), + ("--height", "-5", "positive finite number"), + ("--background", "chartreuse-ish", "background"), + ] { + let source = tmp("reject.vectorcraft"); + ok(&["run", "--export", &source]); + let png = tmp("reject.png"); + for args in [vec!["run", "--in", &source, "--export", &png, flag, value], vec!["convert", &source, &png, flag, value]] { + let out = Command::new(crate::bin()).args(&args).output().unwrap(); + assert!(!out.status.success(), "{args:?}"); + assert!(String::from_utf8_lossy(&out.stderr).contains(message), "{args:?}: {out:?}"); + } + } + // A bad or missing background is refused for formats that leave it out too, so it can't take + // the next flag as its value. + let source = tmp("reject.vectorcraft"); + let svg = tmp("reject.svg"); + for args in [vec!["convert", &source, &svg, "--background", "--outline-text"], vec!["convert", &source, &svg, "--background"]] { + let out = Command::new(crate::bin()).args(&args).output().unwrap(); + assert!(!out.status.success(), "{args:?}"); + assert!(String::from_utf8_lossy(&out.stderr).contains("--background needs"), "{args:?}: {out:?}"); + } +} + #[test] fn help_lists_readable_formats() { let out = ok(&["--help"]); diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 3ec7da1b75..d4d2659b3e 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -23,7 +23,10 @@ vectorcraft-text = { workspace = true } # the update client. craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] } craft-nightly = { workspace = true } -eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] } +# `links` makes egui's OpenUrl output (every link the app opens) start the system browser; without it egui-winit only +# logs the request. Remove it when the craft-libs pin includes storytold/craft-libs#5083, which opens links in the +# shared app setup. +eframe = { workspace = true, features = ["clipboard", "default_fonts", "links", "wayland", "x11"] } egui = { workspace = true } egui_extras = { workspace = true } serde_json = { workspace = true } @@ -130,3 +133,5 @@ winresource = "0.1" [dev-dependencies] tempfile = "3" +# The framework's test frames (`craft::ui::testing`), for the Alt-code hook's tests. +craft = { workspace = true, features = ["ui-testing"] } diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 2715e08125..fbe339937f 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -46,7 +46,7 @@ impl eframe::App for App { } // The keypad digits of Alt + keypad codes leave the frame (#5108). #[cfg(windows)] - super::windows_alt_codes::raw_input_hook(raw); + super::windows_alt_codes::raw_input_hook(ctx, raw); // Symbol-font characters a keyboard tool typed (NHM Writer legacy Tamil). #[cfg(windows)] super::windows_symbol_chars::raw_input_hook(raw); diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index e7f5db9a69..651be6f6a3 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -19,9 +19,15 @@ impl PrintService for SystemPrint { let note = system::print(job)?; Ok(sent(job.title, job.printer, ¬e)) } + fn shared_printers(&self) -> Option { + Some(std::sync::Arc::new(system::queues)) + } fn shared_print(&self) -> Option { Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e)))) } + fn applies_paper(&self) -> bool { + !cfg!(windows) + } fn turns_landscape(&self) -> bool { // macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright // paper. craft-print turns each sheet to its own orientation on Windows. @@ -37,32 +43,88 @@ impl PrintService for SystemPrint { true } fn papers(&mut self, printer: &str, fresh: bool) -> Papers { - self.papers.poll(printer, fresh, |printer| installed_papers(&printer)) + self.papers.poll(printer, fresh, std::time::Instant::now(), |printer| installed_papers(&printer)) } } -/// The paper-size lookup in flight: the printer it reads and its worker's channel. +/// A paper-size read that waits for the worker before it. +type PaperRead = Box Vec + Send>; + +/// How long the newest still-running worker runs before a waiting read may start beside it, and how long a read waits +/// when no worker may start before its printer is given no paper sizes. +const PAPER_WAIT: std::time::Duration = std::time::Duration::from_secs(15); + +/// The most paper-size workers alive at once, stalled ones included. +const PAPER_WORKERS: usize = 4; + +/// The paper-size lookup: the printer it reads with its worker's channel, the read waiting to start with the time it +/// began waiting, and the start times and completion flags of its workers. A read starts when no worker runs, or when +/// the newest still-running worker has run [`PAPER_WAIT`] and fewer than [`PAPER_WORKERS`] are alive. #[derive(Default)] -struct PaperLookup(Option<(String, std::sync::mpsc::Receiver>)>); +struct PaperLookup { + current: Option<(String, std::sync::mpsc::Receiver>)>, + waiting: Option<(String, PaperRead, std::time::Instant)>, + started: Vec<(std::time::Instant, std::sync::Arc)>, + workers: std::sync::Arc, +} + +/// Marks a worker finished and counts it down when it ends, including when it panics. +struct WorkerDone(std::sync::Arc, std::sync::Arc); + +impl Drop for WorkerDone { + fn drop(&mut self) { + self.1.store(false, std::sync::atomic::Ordering::SeqCst); + self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + } +} impl PaperLookup { - /// Poll the lookup of `printer`. A new lookup runs `read` on a worker when `fresh` is set, when the one in flight - /// reads another printer, or when none is in flight; the earlier one's answer is dropped. - fn poll(&mut self, printer: &str, fresh: bool, read: impl FnOnce(String) -> Vec + Send + 'static) -> Papers { - if fresh || self.0.as_ref().is_none_or(|(p, _)| p != printer) { - let (send, receive) = std::sync::mpsc::channel(); - let name = printer.to_string(); - let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || { - let _ = send.send(read(name)); - }); - self.0 = Some((printer.to_string(), receive)); + /// Poll the lookup of `printer`. A new lookup of `read` is wanted when `fresh` is set, when the one in flight or + /// waiting reads another printer, or when none is in flight; the earlier one's answer is dropped. Only the newest + /// waiting read starts, when the workers allow it at `now`. Each new or replacement read begins waiting at `now`. + /// Finished workers do not delay a waiting read. A read that has waited [`PAPER_WAIT`] while + /// [`PAPER_WORKERS`] workers stall is dropped, and the printer gets no paper sizes. + fn poll(&mut self, printer: &str, fresh: bool, now: std::time::Instant, read: impl FnOnce(String) -> Vec + Send + 'static) -> Papers { + let wanted = self.waiting.as_ref().map(|(p, ..)| p).or(self.current.as_ref().map(|(p, _)| p)); + if fresh || wanted.is_none_or(|p| p != printer) { + self.current = None; + self.waiting = Some((printer.to_string(), Box::new(read), now)); } - let result = match self.0.as_ref().map(|(_, receive)| receive.try_recv()) { + self.started.retain(|(_, running)| running.load(std::sync::atomic::Ordering::SeqCst)); + let alive = self.workers.load(std::sync::atomic::Ordering::SeqCst); + let may_start = alive == 0 + || (alive < PAPER_WORKERS && self.started.last().is_none_or(|(started, _)| now.saturating_duration_since(*started) >= PAPER_WAIT)); + if may_start && let Some((name, read, _)) = self.waiting.take() { + let (send, receive) = std::sync::mpsc::channel(); + self.workers.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let running = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + let done = WorkerDone(self.workers.clone(), running.clone()); + let printer = name.clone(); + let spawned = std::thread::Builder::new().name("printer-papers".into()).spawn(move || { + let worker = done; + let papers = read(printer); + worker.1.store(false, std::sync::atomic::Ordering::SeqCst); + let _ = send.send(papers); + }); + if spawned.is_err() { + return Papers::Ready(Vec::new()); + } + self.started.push((now, running)); + self.current = Some((name, receive)); + } + if let Some((.., since)) = &self.waiting { + if now.saturating_duration_since(*since) < PAPER_WAIT { + return Papers::Pending; + } + self.waiting = None; + return Papers::Ready(Vec::new()); + } + let result = match self.current.as_ref().map(|(_, receive)| receive.try_recv()) { Some(Ok(papers)) => Papers::Ready(papers), Some(Err(std::sync::mpsc::TryRecvError::Empty)) => return Papers::Pending, Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) | None => Papers::Ready(Vec::new()), }; - self.0 = None; + self.current = None; result } } @@ -89,6 +151,10 @@ mod system { pub fn printers() -> Vec { craft::print::printers().into_iter().map(Printer::from).collect() } + /// The installed queues and the default one, without asking each driver for its capabilities. + pub fn queues() -> Vec { + craft::print::printer_queues().into_iter().map(Printer::from).collect() + } /// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings. pub fn papers(printer: &str) -> Vec { #[cfg(windows)] @@ -110,17 +176,177 @@ mod system { if printer.contains(['/', '\\']) || printer.starts_with('.') { return Vec::new(); } - const PPD_CAP: u64 = 16 << 20; - let mut bytes = Vec::new(); - let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); - if read.is_err() { - return Vec::new(); + let named = cups_server(); + let sockets = local_sockets(); + // A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue, + // so its sizes come from the server. + if scheduler_is_local(named.as_deref(), &sockets, real_path) { + const PPD_CAP: u64 = 16 << 20; + let mut bytes = Vec::new(); + let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); + let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() }; + if !papers.is_empty() { + return papers; + } } - vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) + // A driverless or remote queue has no PPD here: `lpoptions` asks the queue's server for its sizes. + let mut command = Command::new("lpoptions"); + command.args(["-p", printer, "-l"]); + let papers = paper_output(&mut command) + .map(|out| vectorcraft_ui_egui::print::lpoptions_papers(&String::from_utf8_lossy(&out))) + .unwrap_or_default(); + if !papers.is_empty() { + return papers; + } + // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. + let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); + let server = ipp_server(named, |s| std::path::Path::new(s).exists(), real_path); + let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; + use std::io::Write as _; + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + let test_path = + std::env::temp_dir().join(format!("vectorcraft-printer-papers-{}-{}.test", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let Ok(mut test) = std::fs::File::options().write(true).create_new(true).open(&test_path) else { return papers }; + let written = test.write_all( + b"{\n\ + VERSION 1.1\n\ + OPERATION Get-Printer-Attributes\n\ + GROUP operation-attributes-tag\n\ + ATTR charset attributes-charset utf-8\n\ + ATTR language attributes-natural-language en\n\ + ATTR uri printer-uri $uri\n\ + ATTR keyword requested-attributes media-supported\n\ + STATUS successful-ok\n\ + }\n", + ); + drop(test); + if written.is_err() { + let _ = std::fs::remove_file(&test_path); + return papers; + } + let mut command = Command::new("ipptool"); + command.args(["-T", "10", "-tv", &uri]).arg(&test_path); + let output = paper_output(&mut command); + let _ = std::fs::remove_file(&test_path); + output.map(|out| vectorcraft_ui_egui::print::ipp_papers(&String::from_utf8_lossy(&out))).unwrap_or_default() } } + /// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`. + #[cfg(not(windows))] + const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; + /// The real path of a socket path, through symbolic links (`/var/run/cupsd` is `/private/var/run/cupsd` on macOS). + #[cfg(not(windows))] + pub(super) fn real_path(path: &str) -> Option { + std::fs::canonicalize(path).ok().map(|p| p.to_string_lossy().into_owned()) + } + /// The domain sockets of the local scheduler: CUPS's own, and those the `Listen` lines of `/etc/cups/cupsd.conf` add. + #[cfg(not(windows))] + pub(super) fn local_sockets() -> Vec { + use std::io::Read as _; + let mut text = String::new(); + let read = std::fs::File::open("/etc/cups/cupsd.conf").and_then(|f| f.take(1 << 20).read_to_string(&mut text)); + cupsd_listen_sockets(if read.is_ok() { &text } else { "" }) + } + /// CUPS's own domain sockets and the socket paths of the `Listen` lines of a `cupsd.conf`. + #[cfg(not(windows))] + pub(super) fn cupsd_listen_sockets(text: &str) -> Vec { + let listed = text.lines().filter_map(|line| { + let line = cups_conf_line(line); + let (key, value) = line.trim().split_once(char::is_whitespace)?; + let value = value.trim(); + (key.eq_ignore_ascii_case("Listen") && value.starts_with('/')).then(|| value.to_string()) + }); + CUPS_SOCKETS.iter().map(|s| (*s).to_string()).chain(listed).collect() + } + /// Whether the socket path `path` is one of the local scheduler's `sockets`, as written or as `resolve` gives the + /// real paths of both. + #[cfg(not(windows))] + fn is_local_socket(path: &str, sockets: &[impl AsRef], resolve: impl Fn(&str) -> Option) -> bool { + let path = path.trim(); + let real = resolve(path); + sockets.iter().any(|s| { + let s = s.as_ref(); + s == path || real.as_ref().is_some_and(|real| real == s || resolve(s).as_ref() == Some(real)) + }) + } + /// The server for the IPP lookup, given the one `cups_server` names, whether a path exists and a socket path's real path. + /// With no server named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` + /// on the IPP default port), and `localhost` on `IPP_PORT` otherwise. A + /// named socket in `CUPS_SOCKETS`, or a link to one, also returns `None`. Any other socket path stays as named, + /// and the lookup is skipped. + /// + /// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri + #[cfg(not(windows))] + pub(super) fn ipp_server(named: Option, exists: impl Fn(&str) -> bool, resolve: impl Fn(&str) -> Option) -> Option { + match named { + Some(server) if server.trim().starts_with('/') && is_local_socket(&server, &CUPS_SOCKETS, resolve) => None, + Some(server) => Some(server), + None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()), + } + } + /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or + /// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName` + /// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts. + #[cfg(not(windows))] + fn cups_server() -> Option { + if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) { + return Some(server.trim().to_string()); + } + if cfg!(target_os = "macos") { + return None; + } + let home = std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".cups/client.conf")); + home.into_iter().chain([std::path::PathBuf::from("/etc/cups/client.conf")]).find_map(|path| { + use std::io::Read as _; + let mut text = String::new(); + std::fs::File::open(path).and_then(|f| f.take(1 << 16).read_to_string(&mut text)).ok()?; + client_conf_server_name(&text) + }) + } + /// Whether a scheduler named by `cups_server` runs on this machine: none named, one of the local scheduler's domain + /// `sockets`, or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. + /// A loopback name on another port, or another socket path, is a second scheduler, whose queues the local PPD folder + /// does not describe. `resolve` gives a socket path's real path, so a link to one of `sockets` counts as that socket. + #[cfg(not(windows))] + pub(super) fn scheduler_is_local(server: Option<&str>, sockets: &[String], resolve: impl Fn(&str) -> Option) -> bool { + let Some(server) = server.map(str::trim) else { return true }; + if server.starts_with('/') { + return is_local_socket(server, sockets, resolve); + } + // A network name may end in `/version=1.1`. + let server = server.split_once('/').map_or(server, |(server, _)| server); + let (host, port) = if let Some(rest) = server.strip_prefix('[') { + rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':'))) + } else if server.matches(':').count() == 1 { + server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port))) + } else { + (server, None) + }; + let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1"; + loopback && port.is_none_or(|port| port.trim() == "631") + } + /// A line of a CUPS configuration file without its comment. CUPS (`cupsFileGetConf`) looks only at the first `#` on a + /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is + /// dropped and the rest of the line is kept as written. + #[cfg(not(windows))] + fn cups_conf_line(line: &str) -> String { + match line.find('#') { + Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]), + Some(at) => line[..at].to_string(), + None => line.to_string(), + } + } + /// The last `ServerName` in a `client.conf`. + #[cfg(not(windows))] + pub(super) fn client_conf_server_name(text: &str) -> Option { + text.lines().rev().find_map(|line| { + let kept = cups_conf_line(line); + let (key, value) = kept.trim().split_once(char::is_whitespace)?; + (key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string()) + }) + } /// Drain output while polling the child, and stop discovery after ten seconds. - #[cfg(windows)] fn paper_output(command: &mut Command) -> Option> { use std::io::Read as _; use std::process::Stdio; @@ -163,10 +389,14 @@ mod system { if job.direct_pdf { return super::direct_pdf::print(job); } - // Copies, layout, marks and colour management are already in the PDF. Preserve its - // physical sheet size and the queue's duplex default without printing copies twice. - let settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() }; - craft::print::submit(job.pdf, &settings).map_err(|e| e.to_string()) + craft::print::submit(job.pdf, &settings(job)).map_err(|e| e.to_string()) + } + /// The spooler's settings for `job`. Copies, layout, marks and colour management are already in the PDF. Preserve + /// its physical sheet size and the queue's duplex default without printing copies twice. The driver's paper + /// keyword goes to CUPS as `media`, so the queue feeds the paper the job was laid out for. + pub(crate) fn settings(job: &PrintJob) -> craft::print::Job { + let options = job.paper.map(|paper| ("media".to_string(), paper.to_string())).into_iter().collect(); + craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), options, ..Default::default() } } #[cfg(windows)] pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command { @@ -254,15 +484,27 @@ mod paper_lookup_tests { vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }] } - /// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers. - fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec { - let mut polled = lookup.poll(printer, true, move |_| paper(key)); + /// The test clock: `secs` seconds after a fixed start. + fn at(secs: u64) -> std::time::Instant { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + *START.get_or_init(std::time::Instant::now) + std::time::Duration::from_secs(secs) + } + + /// Poll the lookup of `printer` at `now` until it answers. + fn settle(lookup: &mut PaperLookup, printer: &str, now: std::time::Instant) -> Vec { loop { - match polled { + match lookup.poll(printer, false, now, |_| panic!("polling starts no lookup")) { Papers::Ready(papers) => return papers, Papers::Pending => std::thread::yield_now(), } - polled = lookup.poll(printer, false, |_| panic!("polling starts no lookup")); + } + } + + /// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers. + fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec { + match lookup.poll(printer, true, at(0), move |_| paper(key)) { + Papers::Ready(papers) => papers, + Papers::Pending => settle(lookup, printer, at(0)), } } @@ -279,19 +521,110 @@ mod paper_lookup_tests { fn a_fresh_lookup_drops_the_answer_of_an_earlier_one() { let mut lookup = PaperLookup::default(); let (open, read) = gated("Old"); - assert!(matches!(lookup.poll("Card", true, read), Papers::Pending)); + assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending)); let (other, read) = gated("Office"); - assert!(matches!(lookup.poll("Office", true, read), Papers::Pending)); + assert!(matches!(lookup.poll("Office", true, at(0), read), Papers::Pending)); let _ = open.send(()); let _ = other.send(()); // Back on the card printer. assert_eq!(answer(&mut lookup, "Card", "New"), paper("New")); // The dialog opens again on the card printer while a lookup of it is still running. let (open, read) = gated("Stale"); - assert!(matches!(lookup.poll("Card", true, read), Papers::Pending)); + assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending)); let _ = open.send(()); assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer")); } + + #[test] + fn a_stalled_lookup_holds_the_only_worker_while_the_printer_changes() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut lookup = PaperLookup::default(); + let (open, read) = gated("Stalled"); + assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending)); + let started = std::sync::Arc::new(AtomicUsize::new(0)); + for (i, printer) in ["Office", "Card", "Office", "Plotter"].into_iter().cycle().take(40).enumerate() { + let count = started.clone(); + let polled = lookup.poll(printer, i % 3 == 0, at(1), move |_| { + count.fetch_add(1, Ordering::SeqCst); + paper("Changed") + }); + assert!(matches!(polled, Papers::Pending), "{printer}"); + assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "only the stalled worker runs"); + } + let _ = open.send(()); + // Only the newest choice is read, once the stalled worker ends. + assert_eq!(settle(&mut lookup, "Plotter", at(2)), paper("Changed")); + assert_eq!(started.load(Ordering::SeqCst), 1); + } + + #[test] + fn a_waiting_read_starts_beside_a_worker_stalled_for_the_wait() { + use std::sync::atomic::Ordering; + let mut lookup = PaperLookup::default(); + let (card, read) = gated("Stalled"); + assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending)); + let (office, read) = gated("Office"); + assert!(matches!(lookup.poll("Office", false, at(1), read), Papers::Pending)); + assert!(matches!(lookup.poll("Office", false, at(14), |_| panic!("polling starts no lookup")), Papers::Pending)); + assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "the read waits while the worker is new"); + // The worker has stalled for the whole wait: the waiting read starts beside it. + assert!(matches!(lookup.poll("Office", false, at(15), |_| panic!("polling starts no lookup")), Papers::Pending)); + assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the waiting read starts beside the stalled worker"); + let _ = office.send(()); + assert_eq!(settle(&mut lookup, "Office", at(15)), paper("Office")); + // The worker that answered counts itself down once its thread ends. + while lookup.workers.load(Ordering::SeqCst) > 1 { + std::thread::yield_now(); + } + // The older worker has stalled long enough for another read to start immediately. + let (next, began) = std::sync::mpsc::channel(); + let (open, read) = gated("Next"); + assert!(matches!( + lookup.poll("Next", false, at(16), move |printer| { + let _ = next.send(()); + read(printer) + }), + Papers::Pending + )); + assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the next read starts without another wait"); + began.recv().expect("the next read started"); + let _ = open.send(()); + assert_eq!(settle(&mut lookup, "Next", at(16)), paper("Next")); + drop(card); + } + + #[test] + fn a_printer_waiting_on_stalled_workers_gets_no_sizes_after_the_wait() { + use std::sync::atomic::Ordering; + let mut lookup = PaperLookup::default(); + let (card, read) = gated("Stalled"); + assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending)); + // More stalls fill the workers up to the limit, one wait apart. + let mut stalls = vec![card]; + for (i, printer) in ["Plotter", "Scanner", "Fax"].into_iter().enumerate() { + let (gate, read) = gated("Stalled"); + stalls.push(gate); + assert!(matches!(lookup.poll(printer, true, at(30 + 15 * i as u64), read), Papers::Pending), "{printer}"); + } + assert!(matches!(lookup.poll("Label", true, at(61), |_| panic!("no worker may start")), Papers::Pending)); + assert!(matches!(lookup.poll("Label", false, at(75), |_| panic!("polling starts no lookup")), Papers::Pending)); + // Reopening the same printer and choosing another printer each starts a new wait. + assert!(matches!(lookup.poll("Label", true, at(76), |_| panic!("no worker may start")), Papers::Pending)); + assert!(matches!(lookup.poll("Photo", false, at(91), |_| panic!("no worker may start")), Papers::Pending)); + assert!(matches!(lookup.poll("Photo", false, at(105), |_| panic!("polling starts no lookup")), Papers::Pending)); + match lookup.poll("Photo", false, at(106), |_| panic!("polling starts no lookup")) { + Papers::Ready(papers) => assert_eq!(papers, []), + Papers::Pending => panic!("the wait for the stalled workers did not end"), + } + assert!(lookup.workers.load(Ordering::SeqCst) <= super::PAPER_WORKERS); + // Once the stalled workers end, the next choice is read again. + drop(stalls); + let papers = match lookup.poll("Photo", true, at(107), |_| paper("Ready")) { + Papers::Ready(papers) => papers, + Papers::Pending => settle(&mut lookup, "Photo", at(107)), + }; + assert_eq!(papers, paper("Ready")); + } } #[cfg(test)] @@ -310,3 +643,123 @@ mod turn_tests { ); } } + +#[cfg(all(test, not(windows)))] +mod client_conf_tests { + use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, scheduler_is_local}; + + #[test] + fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() { + let none = |_: &str| false; + let socket = |s: &str| s == "/run/cups/cups.sock"; + let real = |_: &str| None; + assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none, real), None, "CUPS's socket is asked as localhost:631"); + assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none, real), None); + assert_eq!(ipp_server(Some("/var/run/cupsd".into()), none, linked), None, "a link to CUPS's socket is that socket"); + let other = ipp_server(Some("/tmp/other.sock".into()), socket, linked); + assert_eq!(other.as_deref(), Some("/tmp/other.sock"), "another socket is not asked"); + assert_eq!(ipp_server(Some("localhost:8631".into()), socket, real).as_deref(), Some("localhost:8631")); + assert_eq!(ipp_server(None, socket, real), None); + assert_eq!(ipp_server(None, none, real).as_deref(), Some("localhost")); + } + + #[test] + fn a_socket_the_local_cupsd_listens_on_counts_as_local() { + let real = |_: &str| None; + let sockets = cupsd_listen_sockets( + "Listen localhost:631\nListen /srv/cups/print.sock # office\n# Listen /tmp/off.sock\nListen /run/cups/office\\#2.sock\n", + ); + assert!(scheduler_is_local(Some("/srv/cups/print.sock"), &sockets, real), "its PPD folder describes the queue"); + assert!(!scheduler_is_local(Some("/tmp/off.sock"), &sockets, real), "a commented-out Listen line adds nothing"); + assert!(sockets.iter().any(|s| s == "/run/cups/office#2.sock")); + assert_eq!(ipp_server(Some("/srv/cups/print.sock".into()), |_| false, real).as_deref(), Some("/srv/cups/print.sock")); + } + + /// The real path of a socket path on a macOS-like system, where `/var` is a link to `/private/var`. + fn linked(path: &str) -> Option { + path.strip_prefix("/var/").map(|rest| format!("/private/var/{rest}")) + } + + #[test] + fn a_socket_path_counts_as_local_only_when_it_is_cups_own() { + let real = |_: &str| None; + let own = cupsd_listen_sockets(""); + assert!(scheduler_is_local(Some("/var/run/cupsd"), &own, linked), "a link to CUPS's socket reads the local PPD folder"); + assert!(!scheduler_is_local(Some("/var/run/cupsd"), &own, real), "an unresolved unknown path is another scheduler"); + assert!(!scheduler_is_local(Some("/var/run/other.sock"), &own, linked)); + } + + #[test] + fn only_a_scheduler_on_this_machine_counts_as_local() { + for local in [ + None, + Some("/run/cups/cups.sock"), + Some(" /var/run/cups/cups.sock "), + Some("/private/var/run/cupsd"), + Some("localhost"), + Some("LocalHost:631"), + Some("localhost:631"), + Some("127.0.0.1:631"), + Some("::1"), + Some("[::1]:631"), + Some("[::1]"), + Some("localhost/version=1.1"), + Some("localhost:631/version=1.1"), + ] { + assert!(scheduler_is_local(local, &cupsd_listen_sockets(""), |_| None), "{local:?}"); + } + for remote in [ + "print.example.com", + "print.example.com:631", + "192.0.2.7", + "[2001:db8::1]:631", + "2001:db8::1", + "localhost.example.com", + "print.example.com:631/version=1.1", + "localhost:8631", + "127.0.0.1:8631", + "[::1]:8631", + "localhost:8631/version=1.1", + "/tmp/other.sock", + "/home/me/.cups/second.sock", + ] { + assert!(!scheduler_is_local(Some(remote), &cupsd_listen_sockets(""), linked), "{remote}"); + } + } + + #[test] + fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() { + assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com")); + assert_eq!(client_conf_server_name("ServerName print.example.com # office\n").as_deref(), Some("print.example.com")); + assert_eq!(client_conf_server_name("ServerName print.example.com#office\n").as_deref(), Some("print.example.com")); + assert_eq!(client_conf_server_name("ServerName /run/cups\\#1.sock\n").as_deref(), Some("/run/cups#1.sock")); + // After an escaped first `#`, a later `#` stays as written. + assert_eq!(client_conf_server_name("ServerName a\\#b#c\n").as_deref(), Some("a#b#c")); + // A later line that is only a comment, or a directive whose value is all comment, leaves the earlier one. + assert_eq!(client_conf_server_name("ServerName a.example\n# ServerName b.example\nServerName # none\n").as_deref(), Some("a.example")); + assert_eq!(client_conf_server_name("ServerName a.example\nServerName b.example\n").as_deref(), Some("b.example")); + } +} + +#[cfg(test)] +mod job_settings_tests { + use super::system::settings; + use vectorcraft_ui_egui::print::PrintJob; + + fn job(paper: Option<&str>) -> PrintJob<'_> { + PrintJob { printer: Some("Card"), title: "Badge", pdf: b"%PDF", paper, direct_pdf: false } + } + + #[test] + fn the_chosen_paper_goes_to_cups_as_media() { + let args = craft::print::lp_args(&settings(&job(Some("CR80")))); + assert!(args.windows(2).any(|w| w == ["-o", "media=CR80"]), "{args:?}"); + assert!(args.windows(2).any(|w| w == ["-d", "Card"]), "{args:?}"); + } + + #[test] + fn without_a_paper_the_queue_keeps_its_own() { + let args = craft::print::lp_args(&settings(&job(None))); + assert!(!args.iter().any(|a| a.starts_with("media=")), "{args:?}"); + } +} diff --git a/apps/vectorcraft/src/windows_alt_codes.rs b/apps/vectorcraft/src/windows_alt_codes.rs index c358a65653..bd7110a48c 100644 --- a/apps/vectorcraft/src/windows_alt_codes.rs +++ b/apps/vectorcraft/src/windows_alt_codes.rs @@ -5,11 +5,15 @@ //! `WM_CHAR` holding the character the code stands for (in the system's ANSI code page for a code //! with a leading 0, else its OEM code page), the convention every Windows text field follows //! (). winit reports -//! that character as a key press of its own with the character as its text (storytold/winit W36), -//! so egui types it like any other character. Each keypad digit typed with Alt held also arrives -//! as Alt and a digit, which would run a shortcut bound to Alt and that digit: winit's message -//! hook ([`msg_hook`]) sees each message before winit handles it, [`AltCodes`] notes the keypad -//! digits typed with Alt held, and [`raw_input_hook`] takes them out of the frame. +//! that character as a key press of its own after Alt's release, and egui hands it to the frame as +//! typed text, so the Type tool (or a panel's text field) types it like any other character, in the +//! same undo step as the typing round it. winit's message hook ([`msg_hook`]) sees each keyboard +//! message before winit handles it: [`AltCodes`] notes the keypad digits typed with Alt held, and +//! [`raw_input_hook`] takes them out of the frame, so they don't run a shortcut bound to Alt and a +//! digit and the framework does not compose the same code a second time. [`raw_input_hook`] also +//! tells the framework that the Alt hold had digits typed in it (`alt_code_digits_taken`), so it +//! does not read Alt's release as a lone Alt (an alert in a field that holds drafts, or the menu bar +//! taking the focus). //! //! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right, //! Home, Up and Page Up, and Windows still composes the code from them. They are told from the @@ -18,8 +22,10 @@ //! so with Alt held they count as digits and are taken out of the frame too, rather than moving //! the caret before the character arrives. //! -//! egui reports a keypad digit as the same key as the digit above the letters, so the other -//! platforms, whose systems have no such convention, can't tell them apart either. +//! egui reports a keypad digit as the same key as the digit above the letters and tells them apart +//! only by the physical key. On the other platforms the framework types keypad codes itself, and on +//! every platform Alt with a top-row digit stays a key press (`AltCodeKeys::Keypad`, set in the +//! app's root values). #![cfg_attr(not(windows), allow(dead_code))] @@ -39,11 +45,9 @@ const VK_NUMPAD9: usize = 0x69; /// The keypad's virtual keys with NumLock off, by digit (`winuser.h`): `VK_INSERT`, `VK_END`, /// `VK_DOWN`, `VK_NEXT`, `VK_LEFT`, `VK_CLEAR`, `VK_RIGHT`, `VK_HOME`, `VK_UP` and `VK_PRIOR`. const NUMLOCK_OFF_KEYS: [usize; 10] = [0x2D, 0x23, 0x28, 0x22, 0x25, 0x0C, 0x27, 0x24, 0x26, 0x21]; -/// The keys egui reports for the keypad with NumLock off, by digit (Clear has no egui key, so it -/// comes as the top-row digit key, `Num5`). -const NUMLOCK_OFF_EGUI_KEYS: [Key; 10] = - [Key::Insert, Key::End, Key::ArrowDown, Key::PageDown, Key::ArrowLeft, Key::Num5, Key::ArrowRight, Key::Home, Key::ArrowUp, Key::PageUp]; -const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9]; +/// The physical keys egui reports for the keypad's keys, by digit, with NumLock on or off. +const KEYPAD_KEYS: [Key; 10] = + [Key::Numpad0, Key::Numpad1, Key::Numpad2, Key::Numpad3, Key::Numpad4, Key::Numpad5, Key::Numpad6, Key::Numpad7, Key::Numpad8, Key::Numpad9]; /// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the /// keypad (the keypad's own keys clear it). const EXTENDED_KEY: isize = 1 << 24; @@ -53,7 +57,7 @@ thread_local! { static CODES: RefCell = RefCell::new(AltCodes::default()); } -/// The keypad digits typed with Alt held, from the keyboard messages of the thread's queue. +/// The keypad digits of Alt + keypad codes, from the keyboard messages of the thread's queue. #[derive(Default)] struct AltCodes { /// The digits of the keypad presses and releases with Alt held since the last frame, which @@ -86,23 +90,27 @@ impl AltCodes { } } - /// Take out of the frame `events` the keypad digits typed with Alt held since the last frame. - /// The character a code types comes from winit, as typed text. - fn drain(&mut self, events: &mut Vec) { + /// Take the keypad digits typed with Alt held since the last frame out of the frame `events`. + /// The characters the codes type stay in `events` as winit reported them. Returns whether it + /// took any digit out. + fn drain(&mut self, events: &mut Vec) -> bool { let mut keypad = std::mem::take(&mut self.keypad_events); if keypad.is_empty() { - return; + return false; } + let before = events.len(); events.retain(|e| { - let Event::Key { key, modifiers, .. } = e else { + let Event::Key { physical_key, modifiers, .. } = e else { return true; }; if !modifiers.alt { return true; } - // The first keypad key still to take out that egui reports as `key`. - let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key); - match keypad.iter().position(stands_for) { + // The first keypad key still to take out on the physical key `physical_key`. egui reports a + // keypad digit as the same logical key as the top-row digit, so a top-row Alt and digit in + // the same frame is left in the frame. + let on_key = |d: &usize| KEYPAD_KEYS.get(*d).is_some_and(|k| *physical_key == Some(*k)); + match keypad.iter().position(on_key) { Some(i) => { keypad.remove(i); false @@ -110,6 +118,7 @@ impl AltCodes { None => true, } }); + events.len() < before } } @@ -135,13 +144,14 @@ pub fn msg_hook(msg: *const std::ffi::c_void) { } } -/// Before egui reads the main window's frame: the keypad digits typed with Alt held are taken out. -pub fn raw_input_hook(raw: &mut egui::RawInput) { - CODES.with(|c| { - if let Ok(mut c) = c.try_borrow_mut() { - c.drain(&mut raw.events); - } - }); +/// Before egui reads the main window's frame: takes the keypad digits typed with Alt held out of +/// it. When it takes any out, it tells the framework in `ctx` that the Alt hold had digits typed in +/// it. +pub fn raw_input_hook(ctx: &egui::Context, raw: &mut egui::RawInput) { + let taken = CODES.with(|c| c.try_borrow_mut().is_ok_and(|mut c| c.drain(&mut raw.events))); + if taken { + craft::ui::runtime::egui::input::alt_code_digits_taken(ctx, raw.viewport_id); + } } #[cfg(test)] @@ -165,43 +175,76 @@ mod tests { c.message(WM_CHAR, usize::from(posted), 0); } + /// The top-row digit keys, by digit: the logical keys egui reports for the keypad digits with + /// NumLock on. + const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9]; + + /// A key that is not on the keypad: egui reports `key` as both its logical and its physical key. fn key(key: Key, alt: bool, pressed: bool) -> Event { let modifiers = egui::Modifiers { alt, ..Default::default() }; Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers } } - #[test] - fn an_alt_codes_keypad_digits_leave_the_frame_and_its_character_is_typed_once() { - let mut c = AltCodes::default(); - alt_code(&mut c, "0176", 0xB0); - alt_code(&mut c, "0151", 0x2014); - // winit reports each code's character as typed text. - let mut events = vec![ - key(Key::Num0, true, true), - key(Key::Num0, true, false), - key(Key::Num1, false, true), - Event::Text("°".into()), - Event::Text("—".into()), - ]; - c.drain(&mut events); - // The keypad digits typed with Alt are gone (eight presses and eight releases, two here); - // the digit typed without Alt stays, and each character stays once. - assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°".into()), Event::Text("—".into())]); - let mut events = vec![key(Key::Num0, true, true)]; - c.drain(&mut events); - assert_eq!(events.len(), 1, "counts don't carry over to a later frame"); + /// The keypad's key for digit `d`, which egui reports as the logical key `key`. + fn keypad_key(key: Key, d: usize, alt: bool, pressed: bool) -> Event { + let modifiers = egui::Modifiers { alt, ..Default::default() }; + Event::Key { key, physical_key: Some(KEYPAD_KEYS[d]), pressed, repeat: false, modifiers } + } + + /// The keypad digit `d` with NumLock on. + fn keypad(d: usize, alt: bool, pressed: bool) -> Event { + keypad_key(DIGIT_KEYS[d], d, alt, pressed) } #[test] - fn characters_are_left_to_winit() { + fn an_alt_codes_keypad_digits_are_taken_out_and_its_character_stays() { let mut c = AltCodes::default(); - // A plain key press's character, Alt pressed and released alone, and a code's character. + alt_code(&mut c, "0176", 0xB0); + alt_code(&mut c, "0151", 0x2014); + // The characters as winit reports them after each Alt release. + let mut events = + vec![keypad(0, true, true), keypad(0, true, false), keypad(1, false, true), Event::Text("°".into()), Event::Text("—".into())]; + assert!(c.drain(&mut events)); + // The keypad digits typed with Alt are gone (eight presses and eight releases, two here); + // the digit typed without Alt and the characters stay, each once. + assert_eq!(events, vec![keypad(1, false, true), Event::Text("°".into()), Event::Text("—".into())]); + let mut events = vec![keypad(0, true, true)]; + assert!(!c.drain(&mut events)); + assert_eq!(events.len(), 1, "counts don't carry over to a later frame"); + } + + /// egui reports keypad 2 and the top-row 2 as the same logical key. When both come with Alt in + /// one frame, the keypad 2 is taken out and the top-row 2 stays for the shortcuts, whichever + /// comes first. + #[test] + fn a_top_row_alt_digit_in_the_same_frame_stays() { + let mut c = AltCodes::default(); + c.message(WM_SYSKEYDOWN, ALT, 0); + c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 2, 0); + let mut events = vec![key(Key::Num2, true, true), keypad(2, true, true)]; + assert!(c.drain(&mut events)); + assert_eq!(events, vec![key(Key::Num2, true, true)]); + + c.message(WM_SYSKEYUP, VK_NUMPAD0 + 2, 0); + let mut events = vec![keypad(2, true, false), key(Key::Num2, true, false)]; + assert!(c.drain(&mut events)); + assert_eq!(events, vec![key(Key::Num2, true, false)]); + } + + /// winit reports the character a code types, so the hook adds none of its own: a code's + /// `WM_CHAR`, the two halves of a code above the basic plane, and a character without a code + /// before it give the frame no text. + #[test] + fn the_hook_types_no_character_of_its_own() { + let mut c = AltCodes::default(); + alt_code(&mut c, "0176", 0xB0); + c.message(WM_SYSKEYDOWN, ALT, 0); + c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0); + c.message(WM_KEYUP, ALT, 0); + c.message(WM_CHAR, 0xD83D, 0); + c.message(WM_CHAR, 0xDE00, 0); c.message(WM_KEYDOWN, 0x41, 0); c.message(WM_CHAR, usize::from(b'a'), 0); - c.message(WM_SYSKEYDOWN, ALT, 0); - c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, usize::from(b'b'), 0); - alt_code(&mut c, "0176", 0xB0); let mut events = vec![]; c.drain(&mut events); assert!(events.is_empty(), "{events:?}"); @@ -215,7 +258,7 @@ mod tests { // Alt+F: a shortcut, not a code. c.message(WM_SYSKEYDOWN, 0x46, 0); c.message(WM_KEYUP, ALT, 0); - let mut events = vec![key(Key::Num1, true, true), key(Key::F, true, true)]; + let mut events = vec![keypad(1, true, true), key(Key::F, true, true)]; c.drain(&mut events); assert_eq!(events, vec![key(Key::F, true, true)]); } @@ -238,15 +281,16 @@ mod tests { let mut c = AltCodes::default(); alt_code_numlock_off(&mut c, "0176", 0xB0); // What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a - // release each, then a plain Home typed after Alt came up. + // release each, then the character winit reports and a plain Home typed after Alt came up. let mut events = vec![]; - for k in [Key::Insert, Key::End, Key::Home, Key::ArrowRight] { - events.push(key(k, true, true)); - events.push(key(k, true, false)); + for (k, d) in [(Key::Insert, 0), (Key::End, 1), (Key::Home, 7), (Key::ArrowRight, 6)] { + events.push(keypad_key(k, d, true, true)); + events.push(keypad_key(k, d, true, false)); } + events.push(Event::Text("°".into())); events.push(key(Key::Home, false, true)); c.drain(&mut events); - assert_eq!(events, vec![key(Key::Home, false, true)]); + assert_eq!(events, vec![Event::Text("°".into()), key(Key::Home, false, true)]); } #[test] @@ -256,10 +300,16 @@ mod tests { // 0234 uses Insert, Down, Page Down and Left. alt_code_numlock_off(&mut c, "0151", 0x2014); alt_code_numlock_off(&mut c, "0234", 0xEA); - let mut events = - vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)]; + let mut events = vec![ + keypad_key(Key::Num5, 5, true, true), + Event::Text("—".into()), + keypad_key(Key::ArrowDown, 2, true, true), + keypad_key(Key::PageDown, 3, true, true), + keypad_key(Key::ArrowLeft, 4, true, true), + Event::Text("ê".into()), + ]; c.drain(&mut events); - assert!(events.is_empty(), "{events:?}"); + assert_eq!(events, vec![Event::Text("—".into()), Event::Text("ê".into())]); } #[test] @@ -272,11 +322,82 @@ mod tests { c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_KEYUP, ALT, 0); - let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)]; + let mut events = + vec![keypad_key(Key::End, 1, true, true), keypad_key(Key::End, 1, true, false), key(Key::Home, true, true), key(Key::Home, true, false)]; c.drain(&mut events); assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]); } + /// One frame of the framework's test window: Windows' key `messages` reach [`msg_hook`]'s + /// state, then `events` pass through [`raw_input_hook`] before the frame reads them. + fn hooked_frame(frames: &mut craft::ui::testing::Frames, show: &mut dyn FnMut(&mut egui::Ui), messages: &[(u32, usize)], events: Vec) { + CODES.with(|c| { + let mut c = c.borrow_mut(); + for &(message, wparam) in messages { + c.message(message, wparam, 0); + } + }); + let mut raw = egui::RawInput { events, ..Default::default() }; + raw_input_hook(&frames.ctx, &mut raw); + frames.frame(raw.events, &mut *show); + } + + /// After a code Windows composed, the framework does not read Alt's release as a lone Alt: a + /// tool that claims the Alt tap gets none, and the code's character, which winit reports after + /// the release, is typed once. A lone Alt after it is a tap again. + #[test] + fn the_alt_release_after_a_composed_code_is_no_lone_alt() { + use craft::ui::runtime::env::{AltCodeKeys, RootEnv}; + use craft::ui::runtime::keys::{claim_alt_tap, take_alt_tap}; + use std::cell::Cell; + use std::rc::Rc; + + let mut frames = craft::ui::testing::Frames::new(); + craft::ui::testing::windows::set_os(&frames.ctx, craft::host::target::Os::Windows); + frames.root(RootEnv::default().alt_code_keys(AltCodeKeys::Keypad)); + let tool = craft::ui::testing::focus::named_id("alt tap tool"); + let (taps, text) = (Rc::new(Cell::new(0)), Rc::new(RefCell::new(String::new()))); + let mut show = { + let (taps, text) = (Rc::clone(&taps), Rc::clone(&text)); + move |ui: &mut egui::Ui| { + taps.set(taps.get() + usize::from(take_alt_tap(ui.ctx(), tool))); + claim_alt_tap(ui.ctx(), tool); + ui.input(|input| { + for event in &input.events { + if let Event::Text(t) = event { + text.borrow_mut().push_str(t); + } + } + }); + } + }; + frames.frame(vec![], &mut show); + frames.frame(vec![], &mut show); + + let alt = |down: bool| Event::ModifiersChanged(if down { egui::Modifiers::ALT } else { egui::Modifiers::NONE }); + let keypad = |d: usize, pressed: bool| Event::Key { + key: DIGIT_KEYS[d], + physical_key: Some(KEYPAD_KEYS[d]), + pressed, + repeat: false, + modifiers: egui::Modifiers::ALT, + }; + hooked_frame(&mut frames, &mut show, &[(WM_SYSKEYDOWN, ALT)], vec![alt(true)]); + for d in [0, 2, 3, 3] { + let vk = VK_NUMPAD0 + d; + hooked_frame(&mut frames, &mut show, &[(WM_SYSKEYDOWN, vk), (WM_SYSKEYUP, vk)], vec![keypad(d, true), keypad(d, false)]); + } + // Alt's release, then the character winit reports for the `WM_CHAR` that follows it. + hooked_frame(&mut frames, &mut show, &[(WM_KEYUP, ALT), (WM_CHAR, 0xE9)], vec![alt(false), Event::Text("é".into())]); + frames.frame(vec![], &mut show); + assert_eq!((taps.get(), text.take()), (0, "é".to_owned()), "the code's Alt release is no Alt tap, and its character is typed once"); + + hooked_frame(&mut frames, &mut show, &[(WM_SYSKEYDOWN, ALT)], vec![alt(true)]); + hooked_frame(&mut frames, &mut show, &[(WM_KEYUP, ALT)], vec![alt(false)]); + frames.frame(vec![], &mut show); + assert_eq!(taps.get(), 1, "a lone Alt after the code is a tap"); + } + #[test] fn numlock_off_keys_without_alt_are_left_alone() { let mut c = AltCodes::default(); diff --git a/assets/cursors/cursor-pen-convert.svg b/assets/cursors/cursor-pen-convert.svg index fa78f562ef..79e29af75d 100644 --- a/assets/cursors/cursor-pen-convert.svg +++ b/assets/cursors/cursor-pen-convert.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-curvature.svg b/assets/cursors/cursor-pen-curvature.svg index 94ba1708b5..b8d4bd3650 100644 --- a/assets/cursors/cursor-pen-curvature.svg +++ b/assets/cursors/cursor-pen-curvature.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-join.svg b/assets/cursors/cursor-pen-join.svg index 3dd7ce7f6e..05a020bb12 100644 --- a/assets/cursors/cursor-pen-join.svg +++ b/assets/cursors/cursor-pen-join.svg @@ -1 +1,6 @@ - + + + + + + diff --git a/assets/cursors/cursor-pen-new.svg b/assets/cursors/cursor-pen-new.svg index 6690b1ffd6..a27dc0ddae 100644 --- a/assets/cursors/cursor-pen-new.svg +++ b/assets/cursors/cursor-pen-new.svg @@ -1 +1,8 @@ - + + + + + + + + diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs index e14c1439a7..1a69aeed48 100644 --- a/crates/affinity/src/lib.rs +++ b/crates/affinity/src/lib.rs @@ -1,6 +1,7 @@ //! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so //! the corpus tests and fuzz targets under it, and the CI job that runs them, still build. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub use craft_affinity::*; diff --git a/crates/apischema/src/lib.rs b/crates/apischema/src/lib.rs index cff749e84f..e78cde4ecb 100644 --- a/crates/apischema/src/lib.rs +++ b/crates/apischema/src/lib.rs @@ -18,6 +18,7 @@ //! //! The crate knows no command and depends on no other VectorCraft crate. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use std::fmt; diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 85dfc8e084..fffdd4f797 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -9,6 +9,7 @@ //! [`stroke_pieces`] is the single source of brush geometry: the renderer paints the pieces it //! returns (caching them per node) and `object.expandBrush` inserts them as real objects. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod calli; mod colorize; diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index ae5b2d5804..5faad39835 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -140,6 +140,12 @@ fn units_choose_the_default_scale() { assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name)); assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale); } + // Miles and kilometers have no unit of their own, so they read as millimeters at their scale. + for (code, name, pt) in [("3", "Miles", 72.0 * 63_360.0), ("7", "Kilometers", 72.0 / 0.0254 * 1e3)] { + let i = info(&drawing(&[(9, "$INSUNITS"), (70, code)], &[], &[], LINE)).unwrap(); + assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name)); + assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale); + } let survey_in = open(&drawing(&[(9, "$INSUNITS"), (70, "22")], &[], &[], LINE), &ImportOptions::default()).document; assert!((survey_in.artboards[0].rect.width() - 7200.0144000288).abs() < 1e-6, "{:?}", survey_in.artboards[0].rect); let imperial = info(&drawing(&[(9, "$MEASUREMENT"), (70, "0")], &[], &[], LINE)).unwrap(); diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index b54d9022bf..5f2d41d538 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -21,6 +21,7 @@ //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. +#![doc(test(attr(deny(unsafe_code))))] mod aci; #[cfg(test)] diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 75a5fdc2a5..e7c613bf56 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -197,6 +197,11 @@ mod tests { assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary"); assert_eq!(Harmony::HighContrast3.id(), "highContrast3"); assert_eq!(parse("square"), None); + // The labels are written here and the ids come from the framework: a few shown labels read + // back as their rules. + for h in [Harmony::LeftComplement, Harmony::Monochromatic, Harmony::Compound2, Harmony::Pentagram] { + assert_eq!(parse(label(h)), Some(h), "{}", label(h)); + } } #[test] diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 5bb4c88985..03aa259281 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -3,6 +3,7 @@ //! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB), //! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`]. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod blend; pub mod cms; diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 7c40d9d133..fe7ef7a6be 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -21,11 +21,12 @@ use std::sync::Arc; use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint}; use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv}; +use vectorcraft_geom::shapes::CornerKind; use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile}; use crate::live::{BlendOrientation, BlendSpacing, BlendSpec}; -use crate::node::{Node, NodeId, NodeKind}; +use crate::node::{LiveShape, Node, NodeId, NodeKind}; use crate::text::TextObject; // ===================================================================================== @@ -1032,6 +1033,9 @@ enum Shape { /// Paths and compound paths; `members`: the subpath count of each member when both keys are /// compound paths. Path { pair: PathPair, rules: (FillRule, FillRule), members: Option<(Vec, Vec)> }, + /// Two live rectangles: each step is a live rectangle whose size, transform and corner radii + /// lie between the keys', so their rounded corners stay circular arcs. + LiveRect(Box<(LiveRectParts, LiveRectParts)>), /// Text, symbols and images: their transforms interpolate. Placed, /// Anything else: a copy of the nearer key moved and scaled into the interpolated box. @@ -1046,6 +1050,43 @@ pub struct Lerp { shape: Shape, } +/// A live rectangle's size, transform, corner kinds and corner radii in document units. +#[derive(Clone, Debug)] +struct LiveRectParts { + w: f64, + h: f64, + radii: [f64; 4], + kinds: [CornerKind; 4], + xf: Affine, +} + +/// The parts of `s` when it is a live rectangle, with its radii as the lengths it draws. +fn live_rect(s: &LiveShape) -> Option { + let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = s else { return None }; + let base = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)); + let resolved = crate::corners::resolve_stored_radii(&base, radii, *radii_relative); + let corners = vectorcraft_geom::corners::path_corners(&base); + let mut drawn = [0.0; 4]; + for (c, r) in corners.iter().zip(vectorcraft_geom::corners::fitted_radii(&corners, &resolved)) { + if let Some(d) = drawn.get_mut(c.index) { + *d = r; + } + } + Some(LiveRectParts { w: *w, h: *h, radii: drawn, kinds: *kinds, xf: *xf }) +} + +/// The parts of `a` and `b` when steps between them can be live rectangles: both are live +/// rectangles with the same corner kinds, turned and reflected alike, and with no scale or shear +/// left in their transforms, so each step only moves and resizes and its corners stay circular. +fn live_rect_pair(a: &LiveShape, b: &LiveShape) -> Option<(LiveRectParts, LiveRectParts)> { + let (x, y) = (live_rect(a)?, live_rect(b)?); + let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs()); + // A rotation or a reflection: unit columns at right angles. + let rigid = + |c: [f64; 6]| (c[0].hypot(c[1]) - 1.0).abs() < 1e-9 && (c[2].hypot(c[3]) - 1.0).abs() < 1e-9 && (c[0] * c[2] + c[1] * c[3]).abs() < 1e-9; + (x.kinds == y.kinds && rigid(p) && rigid(q) && p[..4].iter().zip(&q[..4]).all(|(a, b)| (a - b).abs() < 1e-9)).then_some((x, y)) +} + /// `n` shrunk to a point at `c`: the counterpart of an object only one of two groups has. fn collapsed(n: &Node, c: Point) -> Node { let mut x = n.clone(); @@ -1083,6 +1124,12 @@ impl Lerp { | (NodeKind::SymbolInstance { .. }, NodeKind::SymbolInstance { .. }) | (NodeKind::Image(_), NodeKind::Image(_)) | (NodeKind::PlacedDocument(_), NodeKind::PlacedDocument(_)) => Shape::Placed, + // A clicked start point asks for anchors to be paired; the path route does that. + (NodeKind::Path { live: Some(la), .. }, NodeKind::Path { live: Some(lb), .. }) + if let Some(parts) = live_rect_pair(la, lb).filter(|_| starts == (None, None)) => + { + Shape::LiveRect(Box::new(parts)) + } _ => match (node_path(a), node_path(b)) { (Some((pa, ra, ma)), Some((pb, rb, mb))) => { Shape::Path { pair: PathPair::new(&pa, &pb, starts), rules: (ra, rb), members: ma.zip(mb) } @@ -1145,6 +1192,28 @@ impl Lerp { } } } + Shape::LiveRect(parts) => { + let (x, y) = &**parts; + let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs()); + let live = LiveShape::Rectangle { + w: lerp_f64(x.w, y.w, t), + h: lerp_f64(x.h, y.h, t), + radii: std::array::from_fn(|i| lerp_f64(x.radii[i], y.radii[i], t)), + kinds: x.kinds, + radii_relative: false, + xf: Affine::new([p[0], p[1], p[2], p[3], lerp_f64(p[4], q[4], t), lerp_f64(p[5], q[5], t)]), + }; + let rule = match &base.kind { + NodeKind::Path { rule, .. } => *rule, + _ => FillRule::default(), + }; + let mut n = Node::path(NodeId(0), live.to_path(), Appearance::default()); + if let NodeKind::Path { rule: r, live: l, .. } = &mut n.kind { + *r = rule; + *l = Some(Box::new(live)); + } + n + } Shape::Placed => { let mut n = base.clone(); match (&mut n.kind, &a.kind, &b.kind) { @@ -2321,6 +2390,110 @@ mod tests { assert_eq!(m.subpaths[0].anchors[0].p, Point::new(55.0, 0.0)); } + /// A live rectangle `w` by `h` at `(x, 0)` with every corner radius `r`. + fn rounded(x: f64, w: f64, h: f64, r: f64) -> Node { + let live = + LiveShape::Rectangle { w, h, radii: [r; 4], kinds: [CornerKind::Round; 4], radii_relative: false, xf: Affine::translate((x, 0.0)) }; + let mut n = Node::path(NodeId(1), live.to_path(), Appearance::default()); + if let NodeKind::Path { live: l, .. } = &mut n.kind { + *l = Some(Box::new(live)); + } + n + } + + /// The step's live radii, after checking that every curve of its outline is a circular arc of + /// that radius about the matching corner center. + fn round_step_radii(step: &Node) -> [f64; 4] { + let Some(LiveShape::Rectangle { radii, .. }) = step.live_shape() else { panic!("a live rectangle step: {step:?}") }; + let r = radii[0]; + let b = step.path_data().and_then(|p| p.bounds()).unwrap_or_default(); + let centers = [(b.x0 + r, b.y0 + r), (b.x1 - r, b.y0 + r), (b.x1 - r, b.y1 - r), (b.x0 + r, b.y1 - r)].map(|(x, y)| Point::new(x, y)); + let path = step.path_data().map(|p| p.to_bezpath()).unwrap_or_default(); + let curves = path.segments().filter(|s| matches!(s, vectorcraft_geom::kurbo::PathSeg::Cubic(_))).count(); + assert_eq!(curves, if r > 1e-9 { 4 } else { 0 }, "one arc per corner: {path:?}"); + for seg in path.segments() { + if let vectorcraft_geom::kurbo::PathSeg::Cubic(c) = seg { + for u in [0.0, 0.25, 0.5, 0.75, 1.0] { + let p = c.eval(u); + let d = centers.iter().map(|q| (p - *q).hypot()).fold(f64::INFINITY, f64::min); + assert!((d - r).abs() < 0.01 * r.max(1.0), "{p:?} is {d} from its corner center, not {r}"); + } + } + } + *radii + } + + /// Steps between live rectangles are live rectangles whose corner radii lie between the keys'. + #[test] + fn steps_between_rounded_rectangles_keep_round_corners() { + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + for r in round_step_radii(&blend.at(0.5)) { + assert!((r - 20.0).abs() < 1e-9, "{r}"); + } + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 0.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + for t in [0.25, 0.5, 0.75] { + for r in round_step_radii(&blend.at(t)) { + assert!((r - 30.0 * t).abs() < 1e-9, "{t}: {r}"); + } + } + // A radius too large for its rectangle counts as the radius it draws. + let blend = Lerp::new(&rounded(0.0, 20.0, 20.0, 100.0), &rounded(300.0, 200.0, 200.0, 10.0), (None, None)); + for r in round_step_radii(&blend.at(0.5)) { + assert!((r - 10.0).abs() < 1e-9, "{r}"); + } + // Keys turned differently keep the anchor-by-anchor route. + let mut turned = rounded(300.0, 200.0, 60.0, 30.0); + turned.transform(Affine::rotate(0.5), false); + assert!(matches!(Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &turned, (None, None)).shape, Shape::Path { .. })); + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + let mut b = rounded(300.0, 100.0, 100.0, 30.0); + a.transform(Affine::rotate(30.0_f64.to_radians()), false); + b.transform(Affine::rotate(390.0_f64.to_radians()), false); + let blend = Lerp::new(&a, &b, (None, None)); + assert!(matches!(&blend.shape, Shape::LiveRect(_))); + let step = blend.at(0.5); + let Some(LiveShape::Rectangle { xf, .. }) = step.live_shape() else { panic!("a live rectangle step") }; + let Some(LiveShape::Rectangle { xf: first, .. }) = a.live_shape() else { panic!("a live rectangle key") }; + assert_eq!(xf.as_coeffs()[..4], first.as_coeffs()[..4]); + for starts in [(Some(0), None), (None, Some(0))] { + assert!(matches!(Lerp::new(&a, &b, starts).shape, Shape::Path { .. })); + } + b.transform(Affine::scale_non_uniform(-1.0, 1.0), false); + assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. })); + for scale in [1.0, 1e-200] { + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + let mut b = rounded(300.0, 100.0, 100.0, 30.0); + a.transform(Affine::scale_non_uniform(scale, scale * 1e-12), false); + b.transform(Affine::scale_non_uniform(scale, -scale * 1e-12), false); + assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. })); + } + // Keys whose corner kinds differ keep the anchor-by-anchor route. + let mut kinds = [CornerKind::Round; 4]; + kinds[2] = CornerKind::InvertedRound; + let live = LiveShape::Rectangle { w: 200.0, h: 60.0, radii: [30.0; 4], kinds, radii_relative: false, xf: Affine::translate((300.0, 0.0)) }; + let mut inverted = Node::path(NodeId(1), live.to_path(), Appearance::default()); + if let NodeKind::Path { live: l, .. } = &mut inverted.kind { + *l = Some(Box::new(live)); + } + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &inverted, (None, None)); + assert!(matches!(blend.shape, Shape::Path { .. })); + // The last step is the inverted key's outline. + assert_eq!(blend.at(1.0).path_data().and_then(|p| p.bounds()), inverted.path_data().and_then(|p| p.bounds())); + // Each step keeps the fill rule of the key it is nearer. + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + if let NodeKind::Path { rule, .. } = &mut a.kind { + *rule = FillRule::EvenOdd; + } + let blend = Lerp::new(&a, &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + assert!(matches!(&blend.shape, Shape::LiveRect(_))); + let rule = |n: &Node| match &n.kind { + NodeKind::Path { rule, .. } => *rule, + _ => panic!("a path step: {n:?}"), + }; + assert_eq!(rule(&blend.at(0.25)), FillRule::EvenOdd); + assert_eq!(rule(&blend.at(0.75)), FillRule::NonZero); + } + /// A step between two distorted images has its corners between the keys' corners. #[test] fn steps_between_distorted_images_have_corners_between_theirs() { diff --git a/crates/doc/src/decode.rs b/crates/doc/src/decode.rs index 11d1b2d72b..f06ea81b00 100644 --- a/crates/doc/src/decode.rs +++ b/crates/doc/src/decode.rs @@ -2,6 +2,17 @@ //! File › Open and Place, SVG import, and embedded and linked images read their pixels with //! [`decode_image`] and [`decode_within`], and size them from their header with [`decoded_layout`]. +thread_local! { + /// Images [`decode_image`] has decoded, or tried, on this thread ([`decodes`]). + static DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many images [`decode_image`] has decoded on this thread so far, failed decodes included. +/// Images other threads decode are not counted. +pub fn decodes() -> u64 { + DECODES.with(std::cell::Cell::get) +} + /// Decoded pixels, as stored and as the image crate gave them, and the ICC profile the file embeds. pub type DecodedImage = (image::DynamicImage, Option>); @@ -10,6 +21,7 @@ pub type DecodedImage = (image::DynamicImage, Option>); /// The renderer, File › Open and Place, SVG import, and embedded and linked images read images /// with it. pub fn decode_image(format: craft_image_codecs::Format, bytes: &[u8], allowance: u64) -> Result { + DECODES.with(|n| n.set(n.get() + 1)); let opts = craft_image_codecs::DecodeOptions { limits: craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: u64::MAX, max_alloc: allowance }, keep_orientation: true, diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 7c96cc6104..77b9a4c747 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -757,6 +757,16 @@ impl Document { { on_path.rename(&renamed); } + // An Image Trace object names the objects its trace made by id: the copy names the copies of + // those objects, and no other object. + if let Some(made) = node.trace_made() { + let mut old = vec![]; + node.walk(&mut |d| old.push(d.id)); + let mut new = vec![]; + n.walk(&mut |d| new.push(d.id)); + let copies = old.into_iter().zip(new).skip(1).filter(|(o, _)| made.contains(*o)).map(|(_, c)| c); + n.set_trace_made(&crate::TraceMade::of(copies)); + } n } } diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 2a92cfb160..0c01fe03d6 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -669,9 +669,7 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: & { return false; } - // How a click reaches it, if one does. let start = opt; - let Some(opt) = path_options(&nodes, &chain, opt) else { return false }; // Hidden by a mask: one of the containers around it clips, and not to `p`. A container // tests its clipping path in outline from the first layer with Preview off down to it, as // a click going down to it does ([`path_options`]). @@ -680,13 +678,19 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: & let outline = start.outline || nodes.get(below..=k).is_some_and(|ns| ns.iter().any(|n| previews_off(n))); n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p, outline)) }); + // Art no mask hides doesn't count, so how a click reaches it is not looked up. + if !masked { + return false; + } + // How a click reaches it, if one does. + let Some(opt) = path_options(&nodes, &chain, start) else { return false }; // A click may reach it there ([`may_hit`]: not a guide while guides are locked or // hidden, nor a Shaper group's hidden part), and its own art is what a click would hit // in it: a group's hidden, locked or masked contents don't count. let [.., parent, n] = nodes.as_slice() else { return false }; let reachable = parent.children().and_then(|c| c.iter().position(|c| c.id == id)).is_some_and(|i| may_hit(parent, i, n, p, opt, &symbols, true)); - masked && reachable && object_hit(n, p, opt, &symbols, true) + reachable && object_hit(n, p, opt, &symbols, true) }) } @@ -695,6 +699,8 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: & /// below a layer whose Preview is off. `None` when a Shaper group's part it can't reach lies on /// the way ([`shaper_hides`]). fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option { + #[cfg(test)] + PATHS_CHECKED.with(|c| c.set(c.get() + 1)); let scope_at = opt.scope.and_then(|s| chain.iter().position(|a| *a == s)); let child_index = |parent: &Node, child: &Node| parent.children().and_then(|c| c.iter().position(|c| c.id == child.id)); let hidden = nodes.windows(2).skip(scope_at.unwrap_or(0)).any(|w| match w { @@ -710,6 +716,12 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option = const { std::cell::Cell::new(0) }; +} + /// The objects under `p` that [`Hit::top_object`] picks in `scope` (isolation mode), topmost /// first: what clicks there select, one below the other (Cmd/Ctrl-click selects behind). pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option) -> Vec { diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index a678797ff5..dc1e28cc6c 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1059,6 +1059,63 @@ fn a_selected_objects_art_hidden_by_a_mask_is_found_under_the_pointer() { assert_eq!(selected_hidden_at(&d, hidden, opt, &[art_id]), Some(art_id)); } +/// How a click reaches a selected object, which searches its parents' children, is looked up +/// only when a mask around it hides its art under the pointer: a press beside thousands of +/// selected objects under no clip looks up none of them. Art that one of several nested clip +/// groups hides is still found, also below thousands of selected objects no mask hides. +#[test] +fn only_selected_objects_a_mask_hides_are_checked_for_a_click_reaching_them() { + let count = |d: &Document, p: Point, selected: &[NodeId]| { + PATHS_CHECKED.with(|c| c.set(0)); + let found = selected_hidden_at(d, p, HitOptions::default(), selected); + (found, PATHS_CHECKED.with(std::cell::Cell::get)) + }; + // `art` (0..200 × 0..100) in five nested clip groups, each clipping to 0..200 but the one at + // `narrow` (counted from the inside), which clips to 0..100 and so hides the art at (150, 50). + let nested = |narrow: Option| { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Appearance::default_art()); + let art_id = art.id; + let mut inner = art; + for depth in 0..5 { + let right = if narrow == Some(depth) { 100.0 } else { 200.0 }; + let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, right, 100.0)), Appearance::default()); + let mut g = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(inner)]); + g.set_clips(true); + inner = g; + } + d.insert(Some(l), 0, inner).unwrap(); + (d, l, art_id) + }; + // 3,000 selected squares (0..10 × 0..10) on the layer, after whatever it holds. + let squares = |d: &mut Document, l: NodeId| { + let at = d.node(l).and_then(|n| n.children()).map_or(0, Vec::len); + (0..3000) + .map(|i| { + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + d.insert(Some(l), at + i, square).unwrap() + }) + .collect::>() + }; + let p = Point::new(150.0, 50.0); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let flat = squares(&mut d, l); + assert_eq!(count(&d, p, &flat), (None, 0), "a press beside them"); + assert_eq!(count(&d, Point::new(5.0, 5.0), &flat), (None, 0), "a press on them"); + let (d, _, art_id) = nested(None); + assert_eq!(count(&d, p, &[art_id]), (None, 0), "no clip hides it"); + for depth in 0..5 { + let (d, _, art_id) = nested(Some(depth)); + assert_eq!(count(&d, p, &[art_id]), (Some(art_id), 1), "hidden by the clip group {depth} levels out"); + } + let (mut d, l, art_id) = nested(Some(2)); + let mut selected = vec![art_id]; + selected.extend(squares(&mut d, l)); + assert_eq!(count(&d, p, &selected), (Some(art_id), 1), "below the squares"); +} + /// A selected group's own art is what a click would hit in it: not a hidden or locked child, nor /// art its own clipping mask hides, all under the pointer where an outer mask hides them. #[test] diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6a331c6b77..8fe1cef218 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -4,6 +4,7 @@ //! [`Document::node_mut`], which clones only the nodes on the path from the root to the edited node. //! Keeping the previous `Document` value around is therefore a cheap undo snapshot. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod appearance; pub mod assets; @@ -142,7 +143,7 @@ pub use text::{ TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape, }; pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet}; -pub use trace::TraceView; +pub use trace::{TraceMade, TraceView}; pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables}; pub use vectorcraft_color as color; pub use vectorcraft_geom as geom; diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a39260ee91..c83f43fe56 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -822,6 +822,28 @@ fn reid_gives_fresh_ids() { assert!(!ids.contains(&a) && !ids.contains(&b)); } +/// A copy of an Image Trace object records the copies of the objects its trace made, nested ones +/// included, and not the copy of an object added to it later. +#[test] +fn reid_remaps_what_a_tracing_records_it_made() { + let (mut d, a, b) = doc_with_rects(); + let na = (*d.remove(a).unwrap()).clone(); + let nb = (*d.remove(b).unwrap()).clone(); + let inner = d.alloc_id(); + let inner = Node::group(inner, vec![Arc::new(na)]); + let mut tracing = Node::group(d.alloc_id(), vec![Arc::new(inner.clone()), Arc::new(nb)]); + tracing.extras_mut().trace = Some(Box::new(serde_json::json!({"preset": "Default"}))); + tracing.set_trace_made(&crate::TraceMade::of([inner.id, a])); + let copy = d.reid(&tracing); + let made = copy.trace_made().unwrap(); + let ch = copy.children().unwrap(); + let (inner_copy, added_copy) = (&ch[0], &ch[1]); + let a_copy = inner_copy.children().unwrap()[0].id; + assert!(made.contains(inner_copy.id) && made.contains(a_copy)); + assert!(!made.contains(added_copy.id) && !made.contains(inner.id) && !made.contains(a) && !made.contains(b)); + assert_eq!(made, crate::TraceMade::of([inner_copy.id, a_copy])); +} + /// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from /// another document with the same id does not. #[test] diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index f462e18300..f5826634d7 100644 --- a/crates/doc/src/trace.rs +++ b/crates/doc/src/trace.rs @@ -1,11 +1,64 @@ //! Image Trace objects' View: how a live trace draws on screen. //! -//! An Image Trace object is a group whose `trace` holds `{preset, params, view}` (see +//! An Image Trace object is a group whose `trace` holds `{preset, params, view, made}` (see //! `imageTrace.make`). The view is a viewing aid only: exports, printing and Expand always use the -//! tracing result, whatever it is set to. +//! tracing result, whatever it is set to. `made` names the objects the trace made ([`TraceMade`]). +use crate::NodeId; use crate::node::Node; +/// The key of an Image Trace object's `trace` settings that names the objects its trace made. +pub const TRACE_MADE: &str = "made"; + +/// The objects the trace of an Image Trace object made, by id: the ranges `[first, last]` of their +/// ids, ascending and apart. A trace gives out its ids one after the other, so a trace of any size +/// is a few ranges. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TraceMade(Vec<(u64, u64)>); + +impl TraceMade { + /// The objects `ids` name. + pub fn of(ids: impl IntoIterator) -> Self { + let mut ids: Vec = ids.into_iter().map(|i| i.0).collect(); + ids.sort_unstable(); + ids.dedup(); + let mut ranges: Vec<(u64, u64)> = vec![]; + for id in ids { + match ranges.last_mut() { + Some((_, last)) if last.checked_add(1) == Some(id) => *last = id, + _ => ranges.push((id, id)), + } + } + Self(ranges) + } + + /// Whether the trace made the object `id`. + pub fn contains(&self, id: NodeId) -> bool { + let i = self.0.partition_point(|(_, last)| *last < id.0); + self.0.get(i).is_some_and(|(first, _)| *first <= id.0) + } + + /// The ranges as the `trace` settings save them: `[[first, last], ...]`. + pub fn to_json(&self) -> serde_json::Value { + serde_json::Value::Array(self.0.iter().map(|(a, b)| serde_json::json!([a, b])).collect()) + } + + /// The ranges `v` saves, or `None` when it is not a list of `[first, last]` pairs of whole + /// numbers, ascending and apart. + pub fn from_json(v: &serde_json::Value) -> Option { + let mut ranges: Vec<(u64, u64)> = vec![]; + for r in v.as_array()? { + let [a, b] = r.as_array()?.as_slice() else { return None }; + let (a, b) = (a.as_u64()?, b.as_u64()?); + if a > b || ranges.last().is_some_and(|(_, last)| *last >= a) { + return None; + } + ranges.push((a, b)); + } + Some(Self(ranges)) + } +} + /// Image Trace › View. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum TraceView { @@ -90,6 +143,21 @@ impl Node { pub fn trace_split(&self) -> f64 { self.extras().trace.as_deref().map_or(DEFAULT_TRACE_SPLIT, TraceView::split_of) } + + /// The objects the trace of this Image Trace object made ([`TRACE_MADE`]), or `None` when its + /// `trace` settings name none, as in a tracing saved before they did, or name them in any other + /// form than [`TraceMade::to_json`]'s. + pub fn trace_made(&self) -> Option { + self.extras().trace.as_deref().and_then(|t| t.get(TRACE_MADE)).and_then(TraceMade::from_json) + } + + /// Records `made` as the objects the trace of this Image Trace object made, when its `trace` + /// settings are an object. + pub fn set_trace_made(&mut self, made: &TraceMade) { + if let Some(t) = self.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(serde_json::Value::as_object_mut) { + t.insert(TRACE_MADE.into(), made.to_json()); + } + } } #[cfg(test)] @@ -110,6 +178,39 @@ mod tests { assert_eq!(g.trace_view(), TraceView::Result); } + #[test] + fn trace_made_keeps_ranges_and_reads_only_well_formed_ones() { + let ids = [7, 3, 4, 5, 9, 3, u64::MAX].map(crate::NodeId); + let made = TraceMade::of(ids); + assert_eq!(made.to_json(), serde_json::json!([[3, 5], [7, 7], [9, 9], [u64::MAX, u64::MAX]])); + for id in 0..12 { + assert_eq!(made.contains(crate::NodeId(id)), ids.contains(&crate::NodeId(id)), "{id}"); + } + assert!(made.contains(crate::NodeId(u64::MAX))); + assert_eq!(TraceMade::from_json(&made.to_json()), Some(made.clone())); + assert_eq!(TraceMade::from_json(&serde_json::json!([])), Some(TraceMade::default())); + for bad in [ + serde_json::json!({}), + serde_json::json!([[5, 3]]), + serde_json::json!([[1, 4], [4, 6]]), + serde_json::json!([[6, 7], [1, 2]]), + serde_json::json!([[1]]), + serde_json::json!([[1, 2, 3]]), + serde_json::json!([[-1, 2]]), + serde_json::json!([[1.5, 2]]), + serde_json::json!(["1", "2"]), + ] { + assert_eq!(TraceMade::from_json(&bad), None, "{bad}"); + } + let mut g = Node::group(crate::NodeId(1), vec![]); + g.set_trace_made(&made); + assert_eq!(g.trace_made(), None, "a group with no trace settings records nothing"); + g.extras_mut().trace = Some(Box::new(serde_json::json!({"preset": "Default"}))); + assert_eq!(g.trace_made(), None); + g.set_trace_made(&made); + assert_eq!(g.trace_made(), Some(made)); + } + #[test] fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() { let mut g = Node::group(crate::NodeId(1), vec![]); diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index d371bfb363..73321a7e09 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -43,8 +43,8 @@ pub(crate) fn catalog() -> Vec { id: HALFTONE, label: "Vector Halftone…", menu: &["Effect", "Color Effects"], - params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", - defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}), + params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; at partial tones circle, ellipse and diamond dots stay inside their cell, sized to preserve the tone's coverage; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes; at full tone every shape but line is the cell's square), style: \"custom\"|\"grid\"|\"gridAngle\"|\"gridDots\"|\"gridDotsAngle\" (custom; a named style sets the shape and angle over the stored ones: grid euclidean at 0°, gridAngle euclidean at 45°, gridDots circle at 0°, gridDotsAngle circle at 45°; effect.apply and effect.setParams refuse an unknown style), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", + defaults: json!({"shape": "circle", "style": "custom", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}), raster: false, lengths: Lengths::default(), }] @@ -71,6 +71,23 @@ pub enum DotShape { Elliptical, } +/// The named styles: each sets a dot shape and a screen angle. +pub const STYLES: [(&str, DotShape, f64); 4] = [ + ("grid", DotShape::Euclidean, 0.0), + ("gridAngle", DotShape::Euclidean, 45.0), + ("gridDots", DotShape::Circle, 0.0), + ("gridDotsAngle", DotShape::Circle, 45.0), +]; + +/// The shape and angle of style `s`: `Some(None)` for `custom` (the shape and angle as given), +/// `None` for an unknown style. +pub fn style(s: &str) -> Option> { + if s.eq_ignore_ascii_case("custom") { + return Some(None); + } + STYLES.iter().find(|(name, ..)| name.eq_ignore_ascii_case(s)).map(|&(_, shape, angle)| Some((shape, angle))) +} + impl DotShape { pub fn parse(s: &str) -> Option { Some(match s.to_ascii_lowercase().as_str() { @@ -89,6 +106,10 @@ impl DotShape { /// running along x. fn path(self, t: f64, s: f64) -> PathData { let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side))); + // A full-tone dot is the cell itself; Line keeps its overlap along the row. + if t >= 1.0 && self != DotShape::Line { + return square(s); + } match self { DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle), DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse), @@ -173,13 +194,14 @@ fn curves_area(curves: &[CubicBez]) -> f64 { curves.iter().map(|c| c.signed_area()).sum() } -/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`. +/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`, one for each +/// quarter turn or part of one. fn ellipse_arc(out: &mut Vec, a: f64, b: f64, t0: f64, t1: f64) { if t1 <= t0 { return; } let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); - let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0); + let n = ((t1 - t0) / std::f64::consts::FRAC_PI_2).ceil().max(1.0); let d = (t1 - t0) / n; let k = 4.0 / 3.0 * (d / 4.0).tan(); for i in 0..n as usize { @@ -294,20 +316,27 @@ fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath { return four_quadrants(&spot_quadrant(t, h, kind)); } let mut bp = BezPath::new(); - let mut add = |curves: Vec, first: bool| { + let mut end: Option = None; + // Corners that meet at a point on the cell's side are joined without an anchor of their own. + let mut add = |curves: Vec| { for (k, c) in curves.iter().enumerate() { if k == 0 { - if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + match end { + None => bp.move_to(c.p0), + Some(e) if e.distance(c.p0) < 1e-9 => {} + Some(_) => bp.line_to(c.p0), + } } bp.curve_to(c.p1, c.p2, c.p3); + end = Some(c.p3); } }; // Round the corners counterclockwise, each one's hole the dot of the opposite tone. let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind); - add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true); - add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false); - add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false); - add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false); + add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y)))); + add(mapped(&q1, |p| Point::new(p.x - h, h - p.y))); + add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h)))); + add(mapped(&q1, |p| Point::new(h - p.x, p.y - h))); bp.close_path(); bp } @@ -405,27 +434,47 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData { let i = (x.floor() as usize).min(SIZE_STEPS - 1); let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0)); let r = lo + (hi - lo) * (x - i as f64); + if matches!(kind, CellKind::Circle | CellKind::Ellipse) { + let (a, b) = if matches!(kind, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) }; + if t > 0.0 && a <= 1.0 && b <= 1.0 { + return shapes::ellipse(Rect::new(-a * h, -b * h, a * h, b * h)); + } + } let q1 = mapped(&kind.quadrant(r), |p| Point::new(p.x * h, p.y * h)); PathData::from_bezpath(&four_quadrants(&q1)) } /// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other -/// three quadrants, counterclockwise. +/// three quadrants, counterclockwise. Quadrants that meet on an axis are joined without an anchor +/// of their own at the join. fn four_quadrants(q1: &[CubicBez]) -> BezPath { let mut bp = BezPath::new(); - let mut add = |curves: Vec, first: bool| { - for (k, c) in curves.iter().enumerate() { + let mut end: Option = None; + // A piece lying on an axis would be drawn back over by its mirror image, so it is left out. + let on_axis = |c: &CubicBez| { + let pts = [c.p0, c.p1, c.p2, c.p3]; + pts.iter().all(|p| p.x.abs() < 1e-9) || pts.iter().all(|p| p.y.abs() < 1e-9) + }; + let mut add = |curves: Vec| { + for (k, c) in curves.iter().filter(|c| !on_axis(c)).enumerate() { if k == 0 { - if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + match end { + None => bp.move_to(c.p0), + Some(e) if e.distance(c.p0) < 1e-9 => {} + Some(_) => bp.line_to(c.p0), + } } bp.curve_to(c.p1, c.p2, c.p3); + end = Some(c.p3); } }; - add(q1.to_vec(), true); - add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false); - add(mapped(q1, |p| Point::new(-p.x, -p.y)), false); - add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false); - bp.close_path(); + add(q1.to_vec()); + add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y)))); + add(mapped(q1, |p| Point::new(-p.x, -p.y))); + add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y)))); + if end.is_some() { + bp.close_path(); + } bp } @@ -525,10 +574,12 @@ impl Halftone { } fn from_params(p: &Value) -> Self { + // A named style sets the shape and angle over the stored ones (which hold the defaults). + let styled = style(text(p, "style", "custom")).flatten(); Self { - shape: DotShape::parse(text(p, "shape", "circle")).unwrap_or(DotShape::Circle), + shape: styled.map_or_else(|| DotShape::parse(text(p, "shape", "circle")).unwrap_or(DotShape::Circle), |s| s.0), frequency: num(p, "frequency", 20.0).clamp(1.0, 300.0), - angle: num(p, "angle", 45.0), + angle: styled.map_or_else(|| num(p, "angle", 45.0), |s| s.1), mono: !text(p, "mode", "mono").eq_ignore_ascii_case("cmyk"), color: crate::raster::color_param(p, Color::BLACK), from_art: flag(p, "fromArt", false), @@ -731,6 +782,7 @@ mod tests { use super::*; use vectorcraft_doc::Effect; use vectorcraft_geom::Shape; + use vectorcraft_geom::kurbo::PathEl; /// A black square's samples: `side` points of black from (10, 10), white around it. fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) { @@ -765,6 +817,46 @@ mod tests { assert_eq!(h.color, Color::BLACK); } + #[test] + fn round_dots_inside_the_cell_have_four_anchors() { + for (shape, tone) in [(DotShape::Circle, 0.5), (DotShape::Ellipse, 0.3)] { + let dot = shape.path(tone, 10.0); + assert_eq!(dot.subpaths.len(), 1, "{shape:?}"); + let sp = &dot.subpaths[0]; + assert!(sp.closed, "{shape:?}"); + assert_eq!(sp.anchors.len(), 4, "{shape:?}: {:?}", sp.anchors); + } + } + + /// Dots whose quadrants meet on the axes have no extra anchors at the joins: a Circle dot small + /// enough to stay inside its cell has the anchors of its arcs only, all distinct. + #[test] + fn dot_quadrants_join_without_extra_anchors() { + let dot = DotShape::Circle.path(0.2, 10.0); + let anchors: Vec = dot.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect(); + for (i, a) in anchors.iter().enumerate() { + assert!(anchors[i + 1..].iter().all(|b| a.distance(*b) > 1e-6), "{anchors:?}"); + } + for shape in [DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + for t in [0.2, 0.6, 0.9] { + for sp in &shape.path(t, 10.0).subpaths { + let n = sp.anchors.len(); + for i in 0..n { + let (a, b) = (sp.anchors[i].p, sp.anchors[(i + 1) % n].p); + assert!(n < 2 || a.distance(b) > 1e-6, "{shape:?} at {t}: {:?}", sp.anchors); + } + } + } + } + } + + #[test] + fn zero_tone_quadrant_dots_have_empty_paths() { + for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + assert!(shape.path(0.0, 10.0).is_empty(), "{shape:?}"); + } + } + #[test] fn values_out_of_range_are_brought_in() { let h = Halftone::of(&effect(json!({"frequency": 1e308, "angle": "NaN", "shape": 7, "mode": "CMYK", "color": "nope"}))).unwrap(); @@ -801,6 +893,51 @@ mod tests { fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1)) } + #[test] + fn grid_dots_fill_the_cell_at_full_tone() { + for name in ["gridDots", "gridDotsAngle"] { + let Some(Some((shape, _))) = style(name) else { panic!("{name} is not a style") }; + // At 100% the cell's corners are covered, so neighboring cells leave no holes. + assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{name}"); + // Below it the corners stay light. + assert!(!covers(shape, 0.9, (0.49, 0.49)), "{name}"); + } + } + + #[test] + fn full_tone_dots_have_exactly_the_cell_corners() { + let Some(Some((grid_dots, _))) = style("gridDots") else { panic!("gridDots is not a style") }; + let corners = [Point::new(-5.0, -5.0), Point::new(5.0, -5.0), Point::new(5.0, 5.0), Point::new(-5.0, 5.0)]; + for shape in [grid_dots, DotShape::Ellipse, DotShape::Square, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + let dot = shape.path(1.0, 10.0); + assert_eq!(dot.subpaths.len(), 1, "{shape:?}"); + let sp = &dot.subpaths[0]; + assert!(sp.closed, "{shape:?}"); + let anchors: Vec = sp.anchors.iter().map(|a| a.p).collect(); + assert_eq!(anchors.len(), 4, "{shape:?}: {anchors:?}"); + for corner in corners { + assert!(anchors.contains(&corner), "{shape:?}: {anchors:?}"); + } + } + } + + #[test] + fn styles_set_the_shape_and_angle() { + let defaults = crate::effect_info(HALFTONE).unwrap().defaults; + let with = |style: &str| { + let mut p = defaults.clone(); + p["style"] = json!(style); + let h = Halftone::of(&effect(p)).unwrap(); + (h.shape, h.angle) + }; + assert_eq!(with("grid"), (DotShape::Euclidean, 0.0)); + assert_eq!(with("gridAngle"), (DotShape::Euclidean, 45.0)); + assert_eq!(with("gridDots"), (DotShape::Circle, 0.0)); + assert_eq!(with("custom"), (DotShape::Circle, 45.0)); + assert_eq!(with("checker"), (DotShape::Circle, 45.0)); + assert_eq!((style("GRIDDOTS"), style("custom"), style("checker")), (Some(Some((DotShape::Circle, 0.0))), Some(None), None)); + } + #[test] fn spot_dots_cover_the_tone() { for shape in [DotShape::Euclidean, DotShape::Elliptical] { @@ -833,6 +970,31 @@ mod tests { } } + #[test] + fn a_dot_inside_its_cell_is_four_curves() { + for shape in [DotShape::Circle, DotShape::Ellipse] { + let bp = shape.path(0.2, 10.0).to_bezpath(); + let curves = bp.elements().iter().filter(|el| matches!(el, PathEl::CurveTo(..))).count(); + let lines = bp.elements().iter().filter(|el| matches!(el, PathEl::LineTo(..))).count(); + assert_eq!((curves, lines), (4, 0), "{shape:?}: {:?}", bp.elements()); + } + } + + #[test] + fn dot_quadrants_join_without_a_repeated_anchor() { + for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + for t in [0.2, 0.45, 0.55, 0.6, 0.85] { + for sp in &shape.path(t, 10.0).subpaths { + let n = sp.anchors.len(); + for i in 0..n { + let (a, b) = (sp.anchors[i].p, sp.anchors[(i + 1) % n].p); + assert!(a.distance(b) > 1e-6, "{shape:?} at {t}: {:?}", sp.anchors); + } + } + } + } + } + #[test] fn euclidean_dots_meet_corner_to_corner_at_half() { let s = DotShape::Euclidean; diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 474a6c0a0c..c07f3b0413 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -241,29 +241,29 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", - json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}), + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", - json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( INFLATE, "Inflate…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).", - json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), + "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).", + json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( ROTATE, "Rotate…", &["Effect", "3D and Materials"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", - json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", + json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( CLASSIC_EXTRUDE, diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index f4d05db96f..c2be1804db 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -33,6 +33,7 @@ //! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells, //! anchored at the object's centre. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod adjust; @@ -98,13 +99,13 @@ pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, }; pub use solids::{ - BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, - RENDER, RENDER_MODES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, - classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, - mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, - solid_art, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, - three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, - validate_three_d_params, view_options, with_graphic, + BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MATERIAL, MAX_GRAPHICS, MappedGraphic, + MeshGraphics, RENDER, RENDER_MODES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, + classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, + is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, + rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, + three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, + validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic, }; pub use solids::{ GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale, diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 697a217da9..9ce14bbf47 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -136,6 +136,82 @@ pub(crate) fn facet_art( composed_art(id, path, paint, Ramp::Rgb(light), seam) } +/// The fills that screen `highlight`, the light a material reflects over a face's paint, over that +/// paint: one gray ramp when its three channels match, else one ramp per channel in that channel's +/// primary (Screen of disjoint primaries adds each channel on its own), or one flat color without +/// a ramp. A channel with no light anywhere on the face takes no fill. +fn highlight_fills(highlight: vectorcraft_three_d::Highlight) -> Vec { + use vectorcraft_doc::color::BlendMode; + let screen = |paint: Paint| { + let mut fill = FillLayer::new(paint); + fill.blend = BlendMode::Screen; + AppearanceItem::Fill(fill) + }; + let lit = |g: &vectorcraft_three_d::ShadeGradient| g.brightness.iter().any(|b| *b > 0.0); + let Some(ramp) = highlight.ramp else { + let [r, g, b] = highlight.flat.map(|v| v.clamp(0.0, 1.0) as f32); + return if r > 0.0 || g > 0.0 || b > 0.0 { vec![screen(Paint::solid(Color::rgb(r, g, b)))] } else { vec![] }; + }; + let [r, g, b] = ramp.channels; + if r == g && g == b { + let light = vectorcraft_three_d::LightGradient { diffuse: r, ambient: 0.0, color: [1.0; 3] }; + return if lit(&r) { vec![screen(smooth_paint(light, Color::WHITE))] } else { vec![] }; + } + ramp.channels + .iter() + .enumerate() + .filter(|(_, g)| lit(g)) + .map(|(channel, g)| { + let mut color = [0.0; 3]; + if let Some(value) = color.get_mut(channel) { + *value = 1.0; + } + screen(smooth_paint(vectorcraft_three_d::LightGradient { diffuse: *g, ambient: 0.0, color }, Color::WHITE)) + }) + .collect() +} + +/// The path that screens `highlight` over a face of outline `path` closed by a seam `seam` wide: +/// the highlight's fills ([`highlight_fills`]) on the face and its seam ([`seamed_fill`], else the +/// outline alone). `None` without a highlight or when it holds no light. +pub(crate) fn highlight_over( + id: vectorcraft_doc::NodeId, + path: &vectorcraft_geom::PathData, + seam: f64, + highlight: Option, +) -> Option { + let items = highlight.map(highlight_fills).unwrap_or_default(); + if items.is_empty() { + return None; + } + let shape = seamed_fill(path, seam).unwrap_or_else(|| path.clone()); + Some(vectorcraft_doc::Node::path(id, shape, vectorcraft_doc::Appearance { items, ..Default::default() })) +} + +/// `face`, the art of a face of outline `path` closed by a seam `seam` wide, with `highlight` +/// screened over it: a group of the face and the highlight's path on the face and its seam +/// ([`highlight_over`]). An opacity mask on the face moves to the group, so it covers the +/// highlight too. `face` may hold the parts of graphics drawn on it: the highlight then lies over +/// them too. `face` as it is without a highlight or when it holds no light. The face is drawn +/// opaque: a transparent paint's coverage is a mask over the whole surface +/// ([`opaque_surface_paint`]), so the highlight and the face take it once. +pub(crate) fn highlighted( + id: vectorcraft_doc::NodeId, + mut face: vectorcraft_doc::Node, + path: &vectorcraft_geom::PathData, + seam: f64, + highlight: Option, +) -> vectorcraft_doc::Node { + use std::sync::Arc; + let Some(over) = highlight_over(id, path, seam, highlight) else { return face }; + let mask = if face.extras().mask.is_some() { face.extras_mut().mask.take() } else { None }; + let mut group = vectorcraft_doc::Node::group(id, vec![Arc::new(face), Arc::new(over)]); + if mask.is_some() { + group.extras_mut().mask = mask; + } + group +} + /// The width of the seam stroke of a facet's underlay: a round stroke that reaches 1 pt past each /// edge, over the pixels that the antialiased edges of two neighboring facets each cover only in /// part at 1:1. A clip to the surface's outline removes what it paints past the surface. @@ -231,17 +307,22 @@ pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Optio /// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed /// in a clip of its footprint, neither with an opacity mask. A face drawn with the parts of Inflate's /// graphics on it, a group of the facet and those parts, takes its facet's underlay and stays in the -/// order with its parts, which are cut to the facet's outline, so the clip keeps them. +/// order with its parts, which are cut to the facet's outline, so the clip keeps them. So does a +/// facet with a material's highlight screened over it ([`highlighted`]), which lies on the facet +/// and its seam. pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc]) -> Option { use std::sync::Arc; use vectorcraft_doc::{Node, NodeKind}; - let facets: Vec> = faces - .iter() - .map(|face| match &face.kind { - NodeKind::Group { children, clip: false } if face.extras().mask.is_none() => children.first().cloned(), - _ => Some(face.clone()), - }) - .collect::>()?; + let facet = |face: &Arc| { + let mut facet = face.clone(); + while let NodeKind::Group { children, clip: false } = &facet.kind + && facet.extras().mask.is_none() + { + facet = children.first()?.clone(); + } + Some(facet) + }; + let facets: Vec> = faces.iter().map(facet).collect::>()?; let (clip, mut underlay) = underlay(id, &facets)?; underlay.extend(faces.iter().cloned()); Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true })) diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index dfaf8c35e6..5d49c52de2 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -103,6 +103,7 @@ pub fn revolve_options(p: &Value) -> Revolve { light_softness: num(p, "lightSoftness", 0.0) / 100.0, ambient: num(p, "ambient", 25.0) / 100.0, shade: flag(p, "shade", true), + material: crate::solids::material::read(p), smooth_shading: true, cap_ends: flag(p, "cap", true), fill_rule: FillRule::NonZero, @@ -316,9 +317,10 @@ fn paint_copies(faces: usize, paint: &Paint) -> usize { faces.saturating_mul(4).saturating_mul(paint_bytes(paint)) } -/// Do Revolve's `options` light its surface with colored lights? +/// Do Revolve's `options` light its surface with colored lights, or with a material other than the +/// default, which also shades in RGB? fn colored(options: &Revolve) -> bool { - options.light_color != [1.0; 3] || options.lights.is_some() + options.light_color != [1.0; 3] || options.lights.is_some() || (options.shade && !options.material.is_default()) } /// Do Revolve's `faces` in `paint` lie over an underlay of themselves ([`sealed_run`])? Under @@ -382,6 +384,7 @@ pub(crate) fn validate_params_of(id: &str, p: &Value) -> Result<(), String> { validate_revolve_params(p)?; crate::solids::graphics::validate(id, p)?; crate::solids::wireframe::validate_render(id, p)?; + crate::solids::material::validate(id, p)?; if id == CLASSIC_REVOLVE { classic::validate(p)?; } @@ -487,6 +490,8 @@ fn group_shadow( /// Geometry does ([`crate::solids::classic::surface`]). The last two values are whether the faces /// go over an underlay of themselves ([`seals`]): the caller seals them ([`sealed_surface`], /// [`sealed_runs`]) in the order it draws them; and whether the faces were left out. +/// A surface painted with a pattern takes no material highlight: a white coverage paint does not +/// keep the transparency of the pattern's tiles. #[allow(clippy::too_many_arguments, clippy::type_complexity)] fn surface( doc: Option<&Document>, @@ -551,6 +556,16 @@ fn surface( if copies.surfaces > MAX_PAINT_COPIES { return None; } + // Under a material's highlight the faces are drawn opaque under one mask of a transparent + // paint's coverage ([`crate::lighting::opaque_surface_paint`]), so the faces and their + // highlights take that coverage once. + let (paint, mask) = if options.shade && !options.material.is_default() { + crate::lighting::opaque_surface_paint(&paint, || { + faces.iter().filter_map(|f| f.path().bounds()).reduce(|a, b| a.union(b)).unwrap_or(Rect::ZERO) + }) + } else { + (paint, None) + }; let order = crate::solids::surface_order(faces.iter().map(|f| (f.points.as_slice(), f.plane, f.depth))); let faces = in_order(faces, &order); let graphics = crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)); @@ -600,11 +615,14 @@ fn surface( illumination: f.illumination, light_gradient: f.light_gradient, rgb_gradient: f.rgb_gradient, + highlight: f.highlight, }) .collect(); (faces, keys) } }; + // A material's highlight goes over each face and the parts of graphics drawn on it. + let lights: Vec<_> = faces.iter().map(|face| (face.path.clone(), face.highlight)).collect(); let children = faces .into_iter() .map(|face| { @@ -667,9 +685,25 @@ fn surface( } else { children }; + let children = children + .into_iter() + .zip(lights) + .map(|(face, (path, highlight))| { + if highlight.is_none() || matches!(paint, Paint::Pattern { .. }) { + return face; + } + let face = Arc::unwrap_or_clone(face); + Arc::new(crate::lighting::highlighted(n.id, face, &path, SEAM_WIDTH, highlight)) + }) + .collect(); let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; + if let Some(mask) = mask { + let bounds = group.visual_bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0); + let coverage = Node::path(n.id, vectorcraft_geom::shapes::rectangle(bounds), Appearance::basic(mask, Paint::None, 0.0)); + group.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(coverage, true))); + } Some((keys, group, kept, seal, false)) } @@ -689,13 +723,14 @@ fn sealed_surface(id: NodeId, surface: Node, seal: bool) -> Node { /// order with its part; the part is cut to its face's outline ([`crate::solids::graphics::surface_parts`]), /// so the clip keeps it. `None` when [`crate::lighting::underlay`] does not take the faces. fn sealed_run(id: NodeId, run: &[Arc]) -> Option { - let faces: Vec> = run - .iter() - .map(|face| match &face.kind { - NodeKind::Group { children, clip: false } => children.first().cloned(), - _ => Some(face.clone()), - }) - .collect::>()?; + let facet = |face: &Arc| { + let mut facet = face.clone(); + while let NodeKind::Group { children, clip: false } = &facet.kind { + facet = children.first()?.clone(); + } + Some(facet) + }; + let faces: Vec> = run.iter().map(facet).collect::>()?; if faces.is_empty() { return None; } @@ -881,6 +916,21 @@ fn surface_meshes( options: Revolve, (paint, opacity, member): (&Paint, f32, f32), graphics: bool, +) -> Result, String> { + let material = crate::solids::material::of(&fx.id, &merged_params(&fx.id, &fx.params)); + surface_meshes_of(path, rule, b, fx, options, (paint, opacity, member), graphics) + .map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, ..m }).collect()) +} + +/// [`surface_meshes`] in the default material. +fn surface_meshes_of( + path: &PathData, + rule: FillRule, + b: Rect, + fx: &Effect, + options: Revolve, + (paint, opacity, member): (&Paint, f32, f32), + graphics: bool, ) -> Result, String> { let color = crate::solids::mesh_color(paint, opacity * member); let list: Vec = if graphics && fx.id == REVOLVE && options.map_surface { @@ -922,7 +972,7 @@ fn surface_meshes( if !side.is_empty() { let graphics = crate::MeshGraphics { face: crate::PlanarFace::Front, graphics: list, center: Point::ZERO, art, opacity, object: member.clamp(0.0, 1.0) }; - out.push(crate::SolidMesh { mesh: side, color, graphics: Some(graphics) }); + out.push(crate::SolidMesh { graphics: Some(graphics), ..crate::SolidMesh::plain(side, color) }); } Ok(out) } diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs index 97bfa67add..6afaf0f9bb 100644 --- a/crates/effects/src/revolve/classic.rs +++ b/crates/effects/src/revolve/classic.rs @@ -36,6 +36,7 @@ pub(crate) fn options(p: &Value) -> Revolve { smooth_shading: false, lights: None, light_color: [1.0; 3], + material: vectorcraft_three_d::Material::DEFAULT, map_surface: !map_art::surface_maps(p).is_empty(), ..super::revolve_options(p) } diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs index 9088b25554..8c5630e31c 100644 --- a/crates/effects/src/revolve/tests_graphics.rs +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -593,3 +593,66 @@ fn a_gradient_with_transparent_stops_takes_no_stroke_over_its_seams() { let clear = seams("Clear"); assert!(!clear.is_empty() && clear.iter().all(|s| !*s), "{clear:?}"); } + +/// Does node `n` screen its fills, as a material's highlight does? +fn screens(n: &Node) -> bool { + n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.blend == vectorcraft_doc::color::BlendMode::Screen)) +} + +/// A material's highlight on a face lies over the parts of the graphics drawn on that face: each +/// blue part is drawn before the last child of a group whose last child is a highlight. +#[test] +fn a_material_highlight_lies_over_the_graphics_on_its_face() { + let d = document(); + let n = revolved(&CYLINDER, json!({"shade": true, "graphics": [{"symbol": "Blue"}], "material": {"roughness": 0.5}})); + let art = revolve_art_in(Some(&d), &n).unwrap(); + let blue = |n: &Node| { + let mut count = 0; + n.walk(&mut |c| { + count += c + .appearance + .items + .iter() + .filter(|i| matches!(i, AppearanceItem::Fill(f) if !screens(c) && shade_of(&f.paint, true).is_some())) + .count(); + }); + count + }; + let mut under = 0; + art.walk(&mut |g| { + if let NodeKind::Group { children, clip: false } = &g.kind + && let [before @ .., over] = children.as_slice() + && screens(over) + { + under += before.iter().map(|c| blue(c)).sum::(); + } + }); + assert!(blue(&art) > 0 && under > 0, "{} blue parts, {under} under a highlight", blue(&art)); +} + +/// A face painted with a gradient with transparent stops screens its highlight only as far as the +/// paint covers the face, and takes that coverage once: every highlight lies under an opacity +/// mask, and no face is drawn with the transparent stops themselves. +#[test] +fn a_material_highlight_on_a_transparent_gradient_is_masked() { + fn unmasked(n: &Node, masked: bool, out: &mut usize) { + let masked = masked || n.extras().mask.is_some(); + if screens(n) && !masked { + *out += 1; + } + n.children().into_iter().flatten().for_each(|c| unmasked(c, masked, out)); + } + // Open by a quarter turn and held off the axis, the solid has flat caps at both ends. + let mut n = revolved(&CYLINDER, json!({"shade": true, "angle": 270.0, "offset": 20.0, "rotationY": 30.0, "material": {"roughness": 0.5}})); + n.appearance.items = vec![AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(ramp(2, 0.5)))]; + let art = revolve_art_in(None, &n).unwrap(); + let (mut highlights, mut bare, mut clear) = (0, 0, 0); + art.walk(&mut |c| { + highlights += usize::from(screens(c)); + clear += + c.appearance.items.iter().filter(|i| matches!(i, AppearanceItem::Fill(f) if crate::lighting::opaque_paint(&f.paint).1.is_some())).count(); + }); + unmasked(&art, false, &mut bare); + assert!(highlights > 0 && bare == 0, "{bare} of {highlights} highlights unmasked"); + assert_eq!(clear, 0, "faces drawn with transparent stops under their highlights"); +} diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 83bb1ca9f7..786d3954e4 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -43,6 +43,9 @@ pub(crate) mod shadow; pub(crate) mod wireframe; pub use wireframe::{RENDER, RENDER_MODES, renders_wireframe, three_d_wireframe_in}; +pub(crate) mod material; +pub use material::MATERIAL; + pub const EXTRUDE: &str = "threeD.extrude"; pub const INFLATE: &str = "threeD.inflate"; pub const ROTATE: &str = "threeD.rotate"; @@ -176,6 +179,7 @@ pub fn view_options(p: &Value) -> View { light_softness: num(p, "lightSoftness", 0.0) / 100.0, ambient: num(p, "ambient", 25.0) / 100.0, shade: flag(p, "shade", true), + material: material::read(p), } } @@ -414,6 +418,7 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { shadow::validate(p)?; graphics::validate(id, p)?; wireframe::validate_render(id, p)?; + material::validate(id, p)?; if let Some(v) = p.get("bevel") && !v.as_str().is_some_and(|s| s == "none" || s == "custom" || BevelShape::parse(s).is_some()) { @@ -832,6 +837,25 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> { /// opaque under one mask of its transparency, placed once on all the facets when it has no /// placement of its own ([`crate::lighting::opaque_surface_paint`]). fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node { + surface_with_parts(n, facets, paint, (opacity, blend), colored, faces, vec![]) +} + +/// [`surface`] with each face followed by the parts of the graphics that `parts` holds for its +/// facet (on Extrude & Bevel's side [`graphics::surface_parts`], on Inflate's front and back +/// [`membrane_parts`]): a face with parts becomes a group of the face and its parts, so nearer +/// faces drawn after it cover them too, and a material's highlight lies over both. A surface +/// painted with a pattern takes no material highlight: a white coverage paint does not keep the +/// transparency of the pattern's tiles. `parts` is left out unless it holds one list for each facet. +fn surface_with_parts( + n: &Node, + facets: Vec, + paint: &Paint, + (opacity, blend): (f32, BlendMode), + colored: bool, + faces: bool, + parts: Vec>>, +) -> Node { + let mut parts = if parts.len() == facets.len() { parts } else { vec![] }.into_iter(); if !faces && composites_facets(&facets, paint, colored) { let mut group = crate::lighting::solid_surface(n.id, &facets, paint); group.opacity = opacity; @@ -847,10 +871,19 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble // Adjacent facets, antialiased on their own, would leave hairline seams: a narrow // stroke of the same paint closes them ([`seam_width`]). let seam = seam_width(&face); + let path = face.path(); + let extra = parts.next().unwrap_or_default(); + let lit = |art: Node| { + let art = if extra.is_empty() { art } else { Node::group(n.id, std::iter::once(Arc::new(art)).chain(extra).collect()) }; + if matches!(paint, Paint::Pattern { .. }) { + return Arc::new(art); + } + Arc::new(crate::lighting::highlighted(n.id, art, &path, seam, face.highlight)) + }; if let Some(g) = face.rgb_gradient && (paint.color().is_some() || matches!(paint, Paint::Gradient(_))) { - return Arc::new(crate::lighting::facet_art(n.id, &face.path(), paint, g, seam)); + return lit(crate::lighting::facet_art(n.id, &path, paint, g, seam)); } let items = crate::lighting::fills(paint, face.illumination, face.brightness, colored); let items = items @@ -862,7 +895,7 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble vec![item, AppearanceItem::Stroke(edge)] }) .collect(); - Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })) + lit(Node::path(n.id, path.clone(), Appearance { items, ..Default::default() })) }) .collect(); let mut group = Node::group(n.id, children); @@ -901,31 +934,6 @@ fn membrane_parts( Some(out) } -/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by -/// the parts of the graphics that `parts` holds for its facet (on Extrude & Bevel's side -/// [`graphics::surface_parts`], on Inflate's front and back [`membrane_parts`]): a face with parts -/// becomes a group of the face and its parts, so nearer faces drawn after it cover them too. -/// `surface` is returned as it is when no facet has a part or it is not such a group. -fn with_surface_parts(id: NodeId, mut surface: Node, parts: Vec>>) -> Node { - if parts.iter().all(Vec::is_empty) { - return surface; - } - let NodeKind::Group { children, clip: false } = &mut surface.kind else { return surface }; - if children.len() != parts.len() { - return surface; - } - for (child, extra) in children.iter_mut().zip(parts) { - if extra.is_empty() { - continue; - } - let mut list = Vec::with_capacity(extra.len() + 1); - list.push(child.clone()); - list.extend(extra); - *child = Arc::new(Node::group(id, list)); - } - surface -} - /// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any). pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect { facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO) @@ -939,9 +947,9 @@ pub(crate) fn seam_width(face: &Facet) -> f64 { } /// Is a surface of `facets` in `paint` one composite of all its facets when [`surface`] draws it -/// whole: a solid color under colored lights with smooth shading? +/// whole: a solid color under colored lights with smooth shading, and no material highlight? fn composites_facets(facets: &[Facet], paint: &Paint, colored: bool) -> bool { - colored && paint.color().is_some() && facets.iter().any(|face| face.rgb_gradient.is_some()) + colored && paint.color().is_some() && facets.iter().any(|face| face.rgb_gradient.is_some()) && facets.iter().all(|f| f.highlight.is_none()) } /// `item`'s paint, its opacity times `member` (the opacity of the objects it is in) and its blend. @@ -2273,8 +2281,8 @@ fn placed_graphics(doc: Option<&Document>, id: NodeId, effect: (&str, &Value), b // Solids whose fills or strokes differ in opacity or blending mode get graphics of their // own, each drawn as its fill or stroke is. One member's solids share their graphics // whether or not their surfaces carry an opacity mask, and each graphic takes the mask of - // the surface it is drawn after ([`with_graphics`]). Solids of different members share - // them only when neither surface carries a mask. A solid joins only the group of the solid + // the surface it is drawn after ([`with_graphics`]). Solids of different members share them + // only when neither surface carries a mask. A solid joins only the group of the solid // before it, so a graphic is never drawn past a solid painted between. let joins = |g: &&Filled| { let member = g.member == f.member; @@ -2302,6 +2310,14 @@ fn placed_graphics(doc: Option<&Document>, id: NodeId, effect: (&str, &Value), b out } +/// The ends of `facets` that the viewer sees, as the graphics on them are drawn: a surface painted +/// with `paint`, a pattern, takes no material highlight ([`surface_with_parts`]), so neither do +/// its caps' graphics. +fn graphic_caps(facets: &[Facet], paint: &Paint) -> Vec { + let pattern = matches!(paint, Paint::Pattern { .. }); + seen_ends(facets).cloned().map(|cap| if pattern { Facet { highlight: None, ..cap } } else { cap }).collect() +} + /// One solid's surface as [`surfaces_for`] builds it: its faces' depths, its art, its member's /// scopes, and for each face the end of a solid it is, when the viewer sees it. type BuiltSurface<'s> = (Vec, Node, &'s [Scope], Vec>); @@ -2368,7 +2384,7 @@ fn surfaces_with( let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; - let colored = !classic && view_options(&p).has_colored_lights(); + let colored = !classic && (view_options(&p).has_colored_lights() || view_options(&p).shades_material()); let masks = has_masks(shapes); // The paint copies of every solid together: past the allowance the source path is drawn. let mut paint_bytes = 0usize; @@ -2392,7 +2408,7 @@ fn surfaces_with( return None; } if graphics_on { - let caps: Vec = seen_ends(&f).cloned().collect(); + let caps = graphic_caps(&f, &paint); if !caps.is_empty() { filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) }); } @@ -2512,8 +2528,8 @@ fn surfaces_with( .iter() .enumerate() .filter_map(|(at, (item, member, _, f, shape))| { - let caps: Vec = seen_ends(f).cloned().collect(); let (paint, opacity, blend) = paint_of(item, *member); + let caps = graphic_caps(f, &paint); let masked = masks_surface(&paint, colored); (!caps.is_empty()).then_some(Filled { at, member: *shape, caps, opacity, blend, masked }) }) @@ -2591,7 +2607,7 @@ fn surfaces_with( classic_arts.next().unwrap_or_else(|| Node::group(n.id, vec![])) } else { let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false)); - with_surface_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts) + surface_with_parts(n, f, &paint, (opacity, blend), colored, faces, parts) }; (depths, art, scopes, ends) }) @@ -3176,12 +3192,15 @@ pub struct SolidMesh { /// The graphics mapped onto the mesh when it is the part of a solid's planar face that carries /// some ([`split_graphics`]); `None` otherwise. pub graphics: Option, + /// The surface's Roughness and Metallic ([`MATERIAL`]); [`vectorcraft_three_d::Material::DEFAULT`] + /// for the 3D (Classic) effects. + pub material: vectorcraft_three_d::Material, } impl SolidMesh { - /// A mesh painted `color`, with no graphics. + /// A mesh painted `color`, with no graphics, in the default material. pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self { - Self { mesh, color, graphics: None } + Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT } } } @@ -3236,7 +3255,7 @@ fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity if !taken.is_empty() { let graphics = list.iter().filter(|g| g.face == face).cloned().collect(); let graphics = MeshGraphics { face, graphics, center: bounds.center(), art, opacity, object: 1.0 }; - out.push(SolidMesh { mesh: taken, color, graphics: Some(graphics) }); + out.push(SolidMesh { graphics: Some(graphics), ..SolidMesh::plain(taken, color) }); } } if !rest.is_empty() { @@ -3283,12 +3302,13 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; let p = crate::merged_params(&fx.id, &fx.params); let view = view_options(&p); + let material = material::of(&fx.id, &p); let mut out = vec![]; // A solid's parts with and without graphics count together against the limit. let mut keep = |out: &mut Vec, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| { split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity)) .into_iter() - .try_for_each(|part| keep_mesh(out, total, part, limit)) + .try_for_each(|part| keep_mesh(out, total, SolidMesh { material, ..part }, limit)) }; if is_plane(&fx.id) { for s in shapes { @@ -3446,3 +3466,6 @@ mod tests_shadow; #[cfg(test)] mod tests_revolve_order; + +#[cfg(test)] +mod tests_material; diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 302180fdbc..88e950fc19 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -450,7 +450,8 @@ fn piece_to(out: &mut BezPath, s: CubicBez, map: &FaceMap, splits: usize) -> Opt /// The graphics `graphics` lists for `face`, drawn on caps `caps` (the faces of that end of the /// object's solids that the viewer sees) through `map`, for an object whose bounds have -/// center `center`: one clipping group of every such graphic, shaded with the first cap's light. +/// center `center`: one clipping group of every such graphic, shaded with the first cap's light +/// and material highlight. /// Pattern tiles keep their colors: the document's pattern draws them. A graphic whose symbol /// `doc` does not have draws nothing. `elements` counts the path elements /// the effect's graphics have drawn so far, after a perspective cuts their curves, and is shared by @@ -467,6 +468,7 @@ pub(super) fn face_art( ) -> Option { let doc = doc?; let light = caps.first()?.illumination; + let highlight = caps.first()?.highlight.map(|h| h.flat.map(|v| v.clamp(0.0, 1.0) as f32)); let affine = map.local_affine(center).filter(|_| map.is_affine()); let mut children = vec![]; for g in graphics.iter().filter(|g| g.face == face) { @@ -526,7 +528,12 @@ pub(super) fn face_art( }; *elements = before.saturating_add(mapped.elements().len()); let mut paint = piece.paint; - vectorcraft_doc::recolor::map_paint(&mut paint, &|c| crate::lighting::shade(c, light)); + vectorcraft_doc::recolor::map_paint(&mut paint, &|c| { + let shaded = crate::lighting::shade(c, light); + let Some([hr, hg, hb]) = highlight else { return shaded }; + let [r, g, b] = shaded.to_rgb(); + vectorcraft_doc::color::Color::rgb(1.0 - (1.0 - r) * (1.0 - hr), 1.0 - (1.0 - g) * (1.0 - hg), 1.0 - (1.0 - b) * (1.0 - hb)) + }); // A pattern's tiles follow the graphic onto the face, as its gradients do below. if let Paint::Pattern { xf, .. } = &mut paint { *xf = gradient_map * *xf; diff --git a/crates/effects/src/solids/material.rs b/crates/effects/src/solids/material.rs new file mode 100644 index 0000000000..2d086eb610 --- /dev/null +++ b/crates/effects/src/solids/material.rs @@ -0,0 +1,54 @@ +//! The 3D and Materials panel's Materials › Properties: a 3D effect's Roughness and Metallic, the +//! `material` parameter. +use serde_json::Value; +use vectorcraft_three_d::Material; + +use super::{EXTRUDE, INFLATE, ROTATE}; + +/// The parameter that holds a 3D effect's material: an object of `roughness` and `metallic`, +/// each a number from 0 to 1. +pub const MATERIAL: &str = "material"; + +/// The 3D effects that take [`MATERIAL`]: the 3D and Materials panel's Extrude & Bevel, Revolve, +/// Inflate and Rotate. The 3D (Classic) effects have their own surfaces. +const TAKES_MATERIAL: [&str; 4] = [EXTRUDE, crate::REVOLVE, INFLATE, ROTATE]; + +const INVALID: &str = "`material` must be an object holding only `roughness` and `metallic`, each a number from 0 to 1"; + +/// The material `v` holds: each of `roughness` and `metallic` it gives, the default +/// ([`Material::DEFAULT`]) for each it leaves out. An error for anything else: a value that is not +/// an object, another key, or a value that is not a number from 0 to 1. +fn parse(v: &Value) -> Result { + let fields = v.as_object().ok_or(INVALID)?; + if fields.keys().any(|k| k != "roughness" && k != "metallic") { + return Err(INVALID.into()); + } + let number = |key: &str, default: f64| match fields.get(key) { + None => Ok(default), + Some(v) => v.as_f64().filter(|n| n.is_finite() && (0.0..=1.0).contains(n)).ok_or(INVALID), + }; + let d = Material::DEFAULT; + Material::new(number("roughness", d.roughness())?, number("metallic", d.metallic())?).ok_or_else(|| INVALID.into()) +} + +/// Check the material in 3D effect `id`'s parameters `p`: `material`, when given to one of the +/// effects in [`TAKES_MATERIAL`], is one [`parse`] takes. The 3D (Classic) effects refuse it as a +/// parameter they do not take. +pub(crate) fn validate(id: &str, p: &Value) -> Result<(), String> { + match p.get(MATERIAL).filter(|_| TAKES_MATERIAL.contains(&id)) { + Some(v) => parse(v).map(|_| ()), + None => Ok(()), + } +} + +/// The material parameters `p` hold, for the view every 3D effect shares: a loaded `material` +/// that [`validate`] would refuse is the default. The 3D (Classic) effects do not shade with it. +pub(crate) fn read(p: &Value) -> Material { + p.get(MATERIAL).and_then(|v| parse(v).ok()).unwrap_or_default() +} + +/// The material 3D effect `id` with parameters `p` exports with: [`read`] for the effects in +/// [`TAKES_MATERIAL`], the default for the others. +pub(crate) fn of(id: &str, p: &Value) -> Material { + if TAKES_MATERIAL.contains(&id) { read(p) } else { Material::DEFAULT } +} diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 504fe1d777..e5cc10de4f 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -794,6 +794,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { illumination: [1.0; 3], normal, rgb_gradient: None, + highlight: None, outline: None, side: true, away: false, diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index c03b8800cb..66af09b227 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -1029,6 +1029,157 @@ fn red_parts(art: &Node) -> Vec { out } +/// How many of `art`'s paths that [`red_parts`] counts lie under a material's highlight: before the +/// last child of a group whose last child screens its fills, or holds paths that do. +fn red_parts_under_highlight(art: &Node) -> usize { + let screens = + |n: &Node| n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.blend == vectorcraft_doc::color::BlendMode::Screen)); + let mut count = 0; + art.walk(&mut |n| { + if let NodeKind::Group { children, clip: false } = &n.kind + && let [under @ .., over] = children.as_slice() + && (screens(over) || over.children().is_some_and(|c| !c.is_empty() && c.iter().all(|c| screens(c)))) + { + count += under.iter().map(|c| red_parts(c).len()).sum::(); + } + }); + count +} + +/// Inflate's material highlight lies over the graphic pieces on its puffed front. +#[test] +fn a_material_highlight_lies_over_the_graphics_on_its_face() { + let d = document(); + let n = object(INFLATE, json!({"shade": true, "graphics": [{"symbol": "Mark", "scale": 400.0}], "material": {"roughness": 0.5}})); + let art = solid_art_in(Some(&d), &n).unwrap(); + assert!(!red_parts(&art).is_empty()); + assert!(red_parts_under_highlight(&art) > 0, "every highlight is drawn under the graphic"); +} + +/// The screened paths covering an interior point of the front cap in a straight-on view. +fn front_cap_highlights(art: &Node) -> usize { + let mut count = 0; + art.walk(&mut |n| { + if n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.blend == BlendMode::Screen)) + && n.path_data().is_some_and(|p| p.to_bezpath().contains(Point::new(47.0, 53.0))) + { + count += 1; + } + }); + count +} + +/// The fills of the mapped graphic pieces, independent of their shaded colors. +fn cap_graphic_fills(art: &Node) -> Vec { + let mut fills = vec![]; + art.walk(&mut |n| { + if let NodeKind::Group { children, clip: true } = &n.kind + && let [_, inner] = children.as_slice() + && let Some(paths) = inner.children() + { + fills.extend(paths.iter().filter(|p| p.path_data().is_some()).flat_map(|p| { + p.appearance.items.iter().filter_map(|i| match i { + AppearanceItem::Fill(f) if f.blend != BlendMode::Screen => Some(f.clone()), + _ => None, + }) + })); + } + }); + fills +} + +/// Cap graphics take the material's reflected light in their paint, keep their opacity, and +/// leave the surface's highlight paths in place, including on overlapping fill and stroke caps. +#[test] +fn cap_graphics_take_material_light_without_extra_highlight_paths() { + let mut d = document(); + if let AppearanceItem::Fill(fill) = &mut Arc::make_mut(&mut d.symbols[0].art).appearance.items[0] { + fill.opacity = 0.5; + } + for id in [EXTRUDE, ROTATE] { + for layers in ["fill", "two fills", "fill and stroke"] { + // Ambient light leaves room for the highlight in every channel of the red paint. + let params = json!({"shade": true, "lightIntensity": 0.0, "ambient": 50.0, "material": {"roughness": 0.5}}); + let mut bare = object(id, params.clone()); + if layers == "two fills" { + let fill = bare.appearance.items[0].clone(); + bare.appearance.items.push(fill); + } else if layers == "fill and stroke" { + bare.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 100.0))); + } + for item in &mut bare.appearance.items { + match item { + AppearanceItem::Fill(f) => f.opacity = 0.5, + AppearanceItem::Stroke(s) => s.opacity = 0.5, + } + } + let bare_art = solid_art_in(Some(&d), &bare).unwrap(); + let mut mapped = bare.clone(); + let mut mapped_params = params; + mapped_params["graphics"] = json!([{"symbol": "Mark", "face": "front"}]); + mapped.appearance.effects = vec![crate::new_effect(id, &mapped_params).unwrap()]; + let art = solid_art_in(Some(&d), &mapped).unwrap(); + mapped_params["material"] = json!({"roughness": 1.0, "metallic": 0.0}); + let mut default = mapped.clone(); + default.appearance.effects = vec![crate::new_effect(id, &mapped_params).unwrap()]; + let default_art = solid_art_in(Some(&d), &default).unwrap(); + let fills = cap_graphic_fills(&art); + let default_fills = cap_graphic_fills(&default_art); + let brighter = !fills.is_empty() + && fills.len() == default_fills.len() + && fills.iter().zip(&default_fills).all(|(f, before)| { + let (Some(c), Some(b)) = (f.paint.color(), before.paint.color()) else { return false }; + c.to_rgb().iter().zip(b.to_rgb()).all(|(a, b)| *a > b) && f.opacity == 0.5 && f.opacity == before.opacity + }); + let highlights = front_cap_highlights(&art); + let bare_highlights = front_cap_highlights(&bare_art); + // The graphic keeps its opacity and takes the highlight in its paint colors. + assert!( + brighter && highlights == bare_highlights && bare_highlights > 0, + "{id}, {layers}: highlights {highlights} vs {bare_highlights}, fills {fills:?} vs {default_fills:?}" + ); + } + } +} + +/// Missing and empty symbols leave the cap's highlight in place. A pattern surface gives +/// neither its cap nor its graphic a material highlight. +#[test] +fn missing_graphics_preserve_cap_highlights_and_patterns_take_none() { + let mut d = document(); + d.symbols.push(Symbol { dynamic: false, name: "Empty".into(), art: Arc::new(Node::group(NodeId(0), vec![])) }); + for id in [EXTRUDE, ROTATE] { + for symbol in ["Mark", "Missing", "Empty"] { + let n = object( + id, + json!({ + "shade": true, "lightIntensity": 0.0, "ambient": 50.0, + "material": {"roughness": 0.5}, "graphics": [{"symbol": symbol, "face": "front"}] + }), + ); + let art = solid_art_in(Some(&d), &n).unwrap(); + if symbol != "Mark" { + assert_eq!(front_cap_highlights(&art), 1, "{id}, {symbol}: the cap keeps its highlight"); + assert!(red_parts(&art).is_empty()); + } + let mut patterned = n.clone(); + patterned.appearance = Appearance::basic(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, Paint::None, 0.0).into(); + patterned.appearance.effects = n.appearance.effects.clone(); + let patterned_art = solid_art_in(Some(&d), &patterned).unwrap(); + assert_eq!(front_cap_highlights(&patterned_art), 0, "{id}, {symbol}: a pattern"); + let mut default = patterned.clone(); + default.appearance.effects[0].params["material"] = json!({"roughness": 1.0, "metallic": 0.0}); + let default_art = solid_art_in(Some(&d), &default).unwrap(); + let fills = cap_graphic_fills(&patterned_art); + let default_fills = cap_graphic_fills(&default_art); + assert_eq!(fills, default_fills, "{id}, {symbol}: pattern graphics keep their colors"); + if symbol == "Mark" { + assert!(!fills.is_empty()); + } + } + } +} + fn reach(parts: &[PathData]) -> Rect { parts.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap() } diff --git a/crates/effects/src/solids/tests_graphics_side.rs b/crates/effects/src/solids/tests_graphics_side.rs index 5afdadf30f..a4444da583 100644 --- a/crates/effects/src/solids/tests_graphics_side.rs +++ b/crates/effects/src/solids/tests_graphics_side.rs @@ -180,6 +180,7 @@ fn a_piece_cut_from_a_face_draws_its_own_part() { illumination: [1.0; 3], normal, rgb_gradient: None, + highlight: None, outline: None, side: true, away: false, diff --git a/crates/effects/src/solids/tests_map_art.rs b/crates/effects/src/solids/tests_map_art.rs index 9ffb264627..e62852acc4 100644 --- a/crates/effects/src/solids/tests_map_art.rs +++ b/crates/effects/src/solids/tests_map_art.rs @@ -201,6 +201,7 @@ fn art_on_a_facet_with_a_curved_edge_is_clipped_to_that_edge() { illumination: [1.0; 3], normal: [0.0, 0.0, 1.0], rgb_gradient: None, + highlight: None, outline: Some(PathData::from_bezpath(&curved)), side: true, away: false, @@ -246,6 +247,7 @@ fn art_on_a_facet_whose_curved_edge_bows_out_covers_the_whole_facet() { illumination: [1.0; 3], normal: [0.0, 0.0, 1.0], rgb_gradient: None, + highlight: None, outline: Some(PathData::from_bezpath(&curved)), side: true, away: false, @@ -286,6 +288,7 @@ fn the_bounds_tests_of_contours_away_from_a_cell_count_as_cuts() { illumination: [1.0; 3], normal: [0.0, 0.0, 1.0], rgb_gradient: None, + highlight: None, outline: None, side: true, away: false, diff --git a/crates/effects/src/solids/tests_material.rs b/crates/effects/src/solids/tests_material.rs new file mode 100644 index 0000000000..1c7141dc8d --- /dev/null +++ b/crates/effects/src/solids/tests_material.rs @@ -0,0 +1,402 @@ +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_doc::color::BlendMode; +use vectorcraft_geom::BezPath; + +use super::*; + +const RED: Color = Color::Rgb { r: 0.8, g: 0.2, b: 0.1 }; + +/// The 3D and Materials panel's effects, which take a material. +const TAKES: [&str; 4] = [EXTRUDE, crate::REVOLVE, INFLATE, ROTATE]; + +fn square_node() -> Node { + let mut b = BezPath::new(); + b.move_to((100.0, 100.0)); + b.line_to((200.0, 100.0)); + b.line_to((200.0, 200.0)); + b.line_to((100.0, 200.0)); + b.close_path(); + Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::solid(Color::BLACK), 4.0)) +} + +/// A square with effect `id` and `params`, drawn. +fn art(id: &str, params: Value) -> Node { + let mut n = square_node(); + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap_or_else(|| panic!("{id}"))); + let art = if id == crate::REVOLVE { crate::revolve_art(&n) } else { solid_art(&n) }; + art.unwrap_or_else(|| panic!("{id} draws")) +} + +/// How many fills of `n` and its children screen their paint. +fn screened(n: &Node) -> usize { + let own = n.appearance.items.iter().filter(|i| matches!(i, AppearanceItem::Fill(f) if f.blend == BlendMode::Screen)).count(); + own + n.children().map_or(0, |c| c.iter().map(|c| screened(c)).sum()) +} + +fn check(id: &str, material: Value) -> Result<(), String> { + validate_three_d_params(id, &crate::merged_params(id, &json!({ MATERIAL: material }))) +} + +fn three_lights() -> Value { + json!([ + {"color": "#ff8080", "rotation": 125.0, "height": 30.0, "intensity": 60.0}, + {"color": "#80ff80", "rotation": -40.0, "height": 50.0, "intensity": 30.0}, + {"color": "#8080ff", "rotation": 10.0, "height": 15.0, "intensity": 20.0} + ]) +} + +fn extrude_scene() -> Value { + json!({"bevel": "rounded"}) +} + +fn inflate_scene() -> Value { + json!({"lights": three_lights()}) +} + +/// The colors of `n`'s fills and their gradient stops, depth first, other than the square's own +/// paint and stroke colors, with runs of one color kept once. +fn fill_colors(n: &Node) -> Vec<[f32; 3]> { + let mut colors: Vec<_> = n + .appearance + .items + .iter() + .flat_map(|item| match item { + AppearanceItem::Fill(f) => match &f.paint { + Paint::Solid { color, .. } => vec![color.to_rgb()], + Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color.to_rgb()).collect(), + _ => vec![], + }, + AppearanceItem::Stroke(_) => vec![], + }) + .filter(|c| *c != RED.to_rgb() && *c != Color::BLACK.to_rgb()) + .collect(); + if let Some(children) = n.children() { + for child in children { + colors.extend(fill_colors(child)); + } + } + colors.dedup(); + colors +} + +/// [`fill_colors`] of [`extrude_scene`] and [`inflate_scene`] as `main` at `f1335a5f19` draws them, +/// before the 3D effects took a material: their count, and the first, second, middle and last. +const MAIN_EXTRUDE_LEN: usize = 24; +const MAIN_EXTRUDE_COLORS: [[f32; 3]; 4] = [ + [0.7347116, 0.1836779, 0.09183895], + [0.6111859, 0.15279648, 0.07639824], + [0.3282661, 0.08206653, 0.041033264], + [0.4674851, 0.116871275, 0.058435638], +]; +const MAIN_INFLATE_LEN: usize = 93524; +const MAIN_INFLATE_COLORS: [[f32; 3]; 4] = [[0.25, 0.0, 0.0], [0.40080008, 0.0, 0.0], [0.0, 0.5603895, 0.0], [0.0, 0.0, 0.5744827]]; + +fn sampled_colors(colors: &[[f32; 3]]) -> [[f32; 3]; 4] { + [colors[0], colors[1], colors[colors.len() / 2], colors[colors.len() - 1]] +} + +#[test] +fn a_material_takes_roughness_and_metallic_from_0_to_1() { + for id in TAKES { + for ok in [json!({}), json!({"roughness": 0.0}), json!({"metallic": 1}), json!({"roughness": 0.35, "metallic": 0.8})] { + assert_eq!(check(id, ok.clone()), Ok(()), "{id} {ok}"); + } + for bad in [ + json!({"roughness": 1.5}), + json!({"roughness": -0.01}), + json!({"metallic": 2}), + json!({"metallic": "0.5"}), + json!({"roughness": null}), + json!({"shine": 0.5}), + json!(0.5), + json!([0.5, 0.5]), + json!(null), + ] { + let Err(e) = check(id, bad.clone()) else { panic!("{id} takes {bad}") }; + assert!(e.contains("`material`"), "{id} {bad}: {e}"); + } + } +} + +#[test] +fn the_classic_effects_take_no_material() { + for id in [CLASSIC_EXTRUDE, CLASSIC_ROTATE, crate::CLASSIC_REVOLVE] { + let p = crate::merged_params(id, &json!({ MATERIAL: {"roughness": 0.5} })); + assert!(validate_three_d_params(id, &p).is_err(), "{id}"); + assert!(material::of(id, &p).is_default(), "{id}"); + } +} + +/// The default material, given or left out, draws exactly what the effects drew before materials. +#[test] +fn the_default_material_draws_as_before() { + for id in TAKES { + for lights in [None, Some(three_lights())] { + let mut params = if id == EXTRUDE { extrude_scene() } else { json!({}) }; + if let Some(lights) = lights { + params["lights"] = lights; + } + let plain = art(id, params.clone()); + for material in [json!({}), json!({"roughness": 1.0, "metallic": 0.0})] { + params[MATERIAL] = material; + assert_eq!(art(id, params.clone()), plain, "{id} {params}"); + } + assert_eq!(screened(&plain), 0, "{id}"); + } + } + for (id, params, len, expected) in + [(EXTRUDE, extrude_scene(), MAIN_EXTRUDE_LEN, MAIN_EXTRUDE_COLORS), (INFLATE, inflate_scene(), MAIN_INFLATE_LEN, MAIN_INFLATE_COLORS)] + { + let colors = fill_colors(&art(id, params)); + assert_eq!(colors.len(), len, "{id} fill count"); + for (got, want) in sampled_colors(&colors).iter().zip(expected) { + for c in 0..3 { + assert!((got[c] - want[c]).abs() <= 1e-6, "{id} channel {c}: {got:?} vs {want:?}"); + } + } + } +} + +#[test] +fn a_colored_inflate_with_no_stroke_keeps_its_highlight() { + let mut n = square_node(); + n.appearance = Appearance::basic(Paint::solid(RED), Paint::None, 0.0).into(); + let params = json!({"lights": [{"color": "#ff8080"}], "material": {"roughness": 0.3}}); + n.appearance.effects.push(crate::new_effect(INFLATE, ¶ms).unwrap_or_else(|| panic!("inflate"))); + let art = solid_art(&n).unwrap_or_else(|| panic!("inflate draws")); + assert!(screened(&art) > 0); +} + +fn loaded_art(id: &str, params: Value) -> Node { + let mut n = square_node(); + n.appearance.effects.push(Effect { id: id.into(), params, visible: true }); + let art = if id == crate::REVOLVE { crate::revolve_art(&n) } else { solid_art(&n) }; + art.unwrap_or_else(|| panic!("{id} draws")) +} + +#[test] +fn a_loaded_invalid_material_draws_the_default() { + for id in TAKES { + let default = art(id, json!({})); + for material in [ + json!({"roughness": 7}), + json!("shiny"), + json!({"metallic": -1}), + json!({"roughness": 7, "metallic": 0.6}), + json!({"roughness": 0.3, "metallic": -1}), + ] { + assert_eq!(loaded_art(id, json!({MATERIAL: material})), default, "{id} {material}"); + } + } +} + +#[test] +fn a_saved_effect_without_material_merges_to_the_default() { + for id in TAKES { + let effect = Effect { id: id.into(), params: json!({}), visible: true }; + assert_eq!(crate::merged_params(&effect.id, &effect.params)[MATERIAL], json!({"roughness": 1.0, "metallic": 0.0}), "{id}"); + assert_eq!(loaded_art(id, effect.params), art(id, json!({})), "{id}"); + } +} + +fn bevel_highlights_meet(facets: &[Facet]) { + let bevels: Vec<_> = facets.iter().filter(|f| f.side && !f.away).collect(); + let color = |f: &Facet, p: Point| { + let h = f.highlight.unwrap_or_else(|| panic!("a material highlight")); + h.ramp.map_or(h.flat.map(|c| c.clamp(0.0, 1.0)), |r| r.at(p)) + }; + let edges = + |f: &Facet| f.contours.iter().flat_map(|c| c.iter().zip(c.iter().cycle().skip(1)).take(c.len()).map(|(a, b)| (*a, *b))).collect::>(); + let mut shared = 0; + let mut diagonals = 0; + let mut bands = 0; + for (i, a) in bevels.iter().enumerate() { + for b in bevels.iter().skip(i + 1) { + for (p, q) in edges(a) { + if edges(b).iter().any(|(r, s)| (p.distance(*r) < 1e-7 && q.distance(*s) < 1e-7) || (p.distance(*s) < 1e-7 && q.distance(*r) < 1e-7)) + { + if let Some(cell) = &a.surface { + // Planar walls meet the bevel at a hard edge. + if a.rgb_gradient.is_none() || b.rgb_gradient.is_none() { + continue; + } + let uv = |p: Point| cell.page.iter().position(|v| v.distance(p) < 1e-7).map(|i| cell.uv[i]); + let (Some(u), Some(v)) = (uv(p), uv(q)) else { panic!("shared corners have side coordinates") }; + // Edges along the extrusion can cross a hard profile corner or a wall cut. + if (u.x - v.x).abs() < 1e-7 { + continue; + } + if (u.y - v.y).abs() < 1e-7 { + bands += 1; + } else { + diagonals += 1; + } + } + shared += 1; + for p in [p, p.lerp(q, 0.5), q] { + let (a, b) = (color(a, p), color(b, p)); + for c in 0..3 { + assert!((a[c] - b[c]).abs() <= 2.0 / 255.0, "shared corner {p:?} channel {c}: {a:?} vs {b:?}"); + } + } + } + } + } + } + assert!(shared >= 4, "neighboring bevel facets were compared: {shared}"); + if bevels.iter().any(|f| f.surface.is_some() && f.contours.first().is_some_and(|c| c.len() == 3)) { + assert!(diagonals > 0 && bands > 0, "triangle diagonals and neighboring bands were compared: {diagonals}, {bands}"); + } +} + +fn front_lit_bevel(shape: &str, roughness: f64) -> Value { + json!({ + "bevel": shape, "bevelWidth": 8.0, "bevelHeight": 8.0, + "rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, + "lightHeight": 90.0, "ambient": 0.0, "material": {"roughness": roughness} + }) +} + +#[test] +fn issue_1407_bevel_bands_meet() { + // #1407: the highlight agrees at the shared corners of neighboring rounded bevel bands. + let n = square_node(); + let path = n.path_data().unwrap_or_else(|| panic!("square path")); + let params = crate::merged_params(EXTRUDE, &front_lit_bevel("rounded", 0.4)); + let facets = + facets(EXTRUDE, path, FillRule::NonZero, path.bounds().unwrap_or(Rect::ZERO), ¶ms).unwrap_or_else(|e| panic!("rounded bevel: {e}")); + bevel_highlights_meet(&facets); +} + +#[test] +fn issue_1407_twisted_perspective_bevel_bands_meet() { + let n = square_node(); + let path = n.path_data().unwrap_or_else(|| panic!("square path")); + let mut params = front_lit_bevel("rounded", 0.4); + params["perspectiveAngle"] = json!(60.0); + params["twist"] = json!(30.0); + params["rotationX"] = json!(20.0); + params["rotationY"] = json!(-30.0); + let params = crate::merged_params(EXTRUDE, ¶ms); + let facets = side_facets(path, FillRule::NonZero, path.bounds().unwrap_or(Rect::ZERO), ¶ms) + .unwrap_or_else(|e| panic!("twisted perspective bevel: {e}")); + bevel_highlights_meet(&facets); +} + +/// Wireframe mode draws the same edges for every material: the bevel bands a material splits into +/// triangles for its highlight add no edges. +#[test] +fn a_material_leaves_the_wireframe_as_it_is() { + for id in TAKES { + let mut params = if id == EXTRUDE { extrude_scene() } else { json!({}) }; + params["render"] = json!({"mode": "wireframe"}); + let plain = art(id, params.clone()); + params[MATERIAL] = json!({"roughness": 0.4, "metallic": 0.5}); + assert_eq!(art(id, params), plain, "{id}"); + } +} + +fn finite_art_colors(n: &Node, counts: &mut [usize; 2]) { + let check = |color: Color| { + assert!(color.to_rgb().iter().all(|c| c.is_finite() && (0.0..=1.0).contains(c)), "finite unit color: {color:?}"); + }; + for item in &n.appearance.items { + let (paint, screen) = match item { + AppearanceItem::Fill(f) => (&f.paint, f.blend == BlendMode::Screen), + AppearanceItem::Stroke(s) => (&s.paint, s.blend == BlendMode::Screen), + }; + if let Paint::Gradient(g) = paint { + for stop in &g.gradient.stops { + check(stop.color); + counts[0] += 1; + } + } + if screen { + counts[1] += 1; + match paint { + Paint::Solid { color, .. } => check(*color), + Paint::Gradient(_) => {} + _ => panic!("a Screen layer has colors"), + } + } + } + if let Some(mask) = &n.extras().mask { + finite_art_colors(&mask.art, counts); + } + if let Some(children) = n.children() { + for child in children { + finite_art_colors(child, counts); + } + } +} + +#[test] +fn issue_2126_bevel_facets_are_finite_and_continuous() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + use vectorcraft_geom::{Shape, kurbo::RoundedRect}; + + // #2126: a curved outline with a Classic bevel shape keeps finite colors and joined highlights. + let path = PathData::from_bezpath(&RoundedRect::new(100.0, 100.0, 240.0, 200.0, 20.0).to_path(0.1)); + let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, RED), GradientStop::new(1.0, Color::WHITE)], + )))); + let mut n = Node::path(NodeId(1), path.clone(), Appearance::basic(paint, Paint::None, 0.0)); + let params = front_lit_bevel("classic", 0.5); + n.appearance.effects.push(crate::new_effect(EXTRUDE, ¶ms).unwrap_or_else(|| panic!("extrude"))); + let art = solid_art(&n).unwrap_or_else(|| panic!("gradient extrusion draws")); + let mut counts = [0; 2]; + finite_art_colors(&art, &mut counts); + assert!(counts[0] > 0 && counts[1] > 0, "gradient stops and Screen layers: {counts:?}"); + let params = crate::merged_params(EXTRUDE, ¶ms); + let facets = + facets(EXTRUDE, &path, FillRule::NonZero, path.bounds().unwrap_or(Rect::ZERO), ¶ms).unwrap_or_else(|e| panic!("classic bevel: {e}")); + bevel_highlights_meet(&facets); +} + +/// Any other material screens its highlight over each lit face, and the paint keeps its hue on a +/// dielectric. +#[test] +fn a_shiny_material_screens_a_highlight_over_its_faces() { + for id in TAKES { + let shiny = art(id, json!({ MATERIAL: {"roughness": 0.3, "metallic": 0.0} })); + assert!(screened(&shiny) > 0, "{id}"); + assert_ne!(shiny, art(id, json!({})), "{id}"); + let unshaded = art(id, json!({ "shade": false, MATERIAL: {"roughness": 0.3, "metallic": 0.0} })); + assert_eq!(screened(&unshaded), 0, "{id} unshaded"); + } +} + +/// A surface painted with a pattern draws no material highlight, so no highlight covers the gaps +/// between the pattern's tiles. +#[test] +fn a_pattern_takes_no_material_highlight() { + for id in TAKES { + let mut n = square_node(); + let paint = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + n.appearance = Appearance::basic(paint, Paint::None, 0.0).into(); + n.appearance.effects.push(crate::new_effect(id, &json!({ MATERIAL: {"roughness": 0.3, "metallic": 0.0} })).unwrap_or_else(|| panic!("{id}"))); + let art = if id == crate::REVOLVE { crate::revolve_art(&n) } else { solid_art(&n) }; + let art = art.unwrap_or_else(|| panic!("{id} draws")); + assert_eq!(screened(&art), 0, "{id}"); + } +} + +/// The meshes a 3D export writes carry the material: the effects that take one keep it, and every +/// other is the default. +#[test] +fn meshes_carry_the_material() { + for id in TAKES { + let mut n = square_node(); + let Some(fx) = crate::new_effect(id, &json!({ MATERIAL: {"roughness": 0.25, "metallic": 0.75} })) else { panic!("{id}") }; + n.appearance.effects.push(fx); + let meshes = three_d_meshes(&n).unwrap_or_else(|e| panic!("{id}: {e}")); + assert!(!meshes.is_empty(), "{id}"); + assert!(meshes.iter().all(|m| (m.material.roughness(), m.material.metallic()) == (0.25, 0.75)), "{id}"); + } + let mut n = square_node(); + let Some(fx) = crate::new_effect(EXTRUDE, &json!({})) else { panic!("extrude") }; + n.appearance.effects.push(fx); + assert!(three_d_meshes(&n).unwrap_or_default().iter().all(|m| m.material.is_default())); +} diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index 409a5c1dc3..3c1b3f1f2e 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -243,7 +243,11 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result Result, String> { let label = label_of(&fx.id); let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; - let p = crate::merged_params(&fx.id, &fx.params); + let mut p = crate::merged_params(&fx.id, &fx.params); + // The edges are those of the faces the default material builds, whatever the effect's material. + if let Some(material) = p.get_mut(super::MATERIAL) { + *material = Value::Object(serde_json::Map::new()); + } let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; let face = |f: &Facet| WireFace { path: f.path(), stroke: if classic { super::classic::stroke_width(f, &p) } else { super::seam_width(f) } }; let mut out = vec![]; diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 945e6c92be..0fe4f7d10e 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -71,6 +71,9 @@ serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } +# Whether two file names differ only in their Unicode normalization form, in a folder that ignores +# it (`script::dom::raster_capture`). Already in Cargo.lock, so this adds no new crate. +unicode-normalization = "0.1.26" # Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a # file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile, diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index d2dc185222..586deb604c 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -448,6 +448,12 @@ pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&' /// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in /// ([`plugin::run_command`]), which needs the command's id. pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result { + if matches!(spec.id, "shape.rectangle" | "shape.ellipse" | "shape.polygon" | "shape.star" | "path.create") { + return create::on_layer(s, p, spec.id, |s| (spec.run)(s, p)); + } + if matches!(spec.id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + return paint::object_only(s, p, spec.id, |s| (spec.run)(s, p)); + } if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) } } @@ -964,6 +970,10 @@ pub use retype::{RetypeFound, RetypeRun, RetypeSearch}; /// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). pub(crate) use buildcmds::TracePresetChanges; +/// Whether an object is an Image Trace object, the source image of one, or the seam fills group in +/// one. +pub(crate) use buildcmds::{TRACE_NAME, is_seam_fills, is_trace_group, is_trace_source}; + /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 25f950ef9a..ec18bbccd1 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -21,7 +21,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{Node, NodeId, NodeKind, OrientedBox}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use vectorcraft_render::effects; @@ -30,7 +30,11 @@ use super::super::colorcmds::edit_if_changed; use super::super::edit::selected_roots; use super::super::graph::{capture_series_object_opacity, series_groups_among}; use super::super::menucmds::whole_or; -use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns}; +use super::super::object::{ + aligned_symbol_transforms, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform, scaling, transform_node, + transform_patterns, +}; +use super::super::objects_on_path; use super::super::typecmd::refresh_bounds_of; use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_multi, has_selection, number_or, switch_or}; use crate::{EngineError, Result, Session}; @@ -62,7 +66,7 @@ pub fn specs() -> Vec { "Offset Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{direction?: \"row\" (left to right) | \"column\" (top to bottom) (\"row\"), gap?: pt −1000000..1000000 (10; negative: the objects overlap), order?: \"stacking\" (stacking order, from the back) | \"position\" (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (\"stacking\"), reverse?: false (true: the order runs the other way)} chain the selected objects (the top-level ones) one after another in that order, as one undo step: the first stays where it is, and each later one moves only along the direction, so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. Everything is measured by visual bounds (strokes and effects as drawn; a clipping group by its mask). A run that moves nothing makes no step → {count}", + "{direction?: \"row\" (left to right) | \"column\" (top to bottom) (\"row\"), gap?: pt −1000000..1000000 (10; negative: the objects overlap), order?: \"stacking\" (stacking order, from the back) | \"position\" (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (\"stacking\"), reverse?: false (true: the order runs the other way)} chain the selected objects (the top-level ones) one after another in that order, as one undo step: the first stays where it is, and each later one moves only along the direction, so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. An object aligned to the pixel grid snaps to it after it moves, so the gap before it can differ from `gap`, and the next one starts from where it snapped. An Objects on Path group is measured with its members put back on the path after it moves. Everything is measured by visual bounds (strokes and effects as drawn; a clipping group by its mask). A run that moves nothing makes no step → {count}", has_multi, offset ), @@ -295,15 +299,62 @@ fn offset(s: &mut Session, p: &Value) -> Result { } // The first stays; each later one starts `gap` past where the one before it now ends. let mut end: Option = None; - let xfs: Vec<(NodeId, Affine)> = items - .iter() - .map(|&(id, start, finish)| { + let mut moves = false; + for &(_, start, finish) in &items { + let shift = end.map_or(0.0, |e| e + gap - start); + moves |= shift.abs() > 1e-9; + end = Some(finish + shift); + } + if !moves { + return Ok(json!({ "count": items.len() })); + } + let p = json!({ "strokes": false }); + let ids: Vec = items.iter().map(|(id, _, _)| *id).collect(); + let mut sc = scaling(s, &p); + sc.patterns = transform_patterns(s, &p, &ids)?; + let last = items.len().saturating_sub(1); + let natural = aligned_symbol_transforms(&s.doc()?.doc); + edit_if_changed(s, "Offset Objects", |before, d| { + // Each one is moved (a pixel-aligned object snaps as it moves) and measured again, so the + // next one starts from where the one before it ends up. + let mut end: Option = None; + let mut changed = false; + // One copy of the document, made at the first Objects on Path group, to measure the groups on. + let mut scratch: Option = None; + for (i, &(id, start, finish)) in items.iter().enumerate() { let shift = end.map_or(0.0, |e| e + gap - start); - end = Some(finish + shift); - (id, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) })) - }) - .collect(); - transform_each(s, "Offset Objects", false, &xfs)?; + if shift.abs() <= 1e-9 { + end = Some(finish); + continue; + } + if let Some(n) = d.node_mut(id) { + transform_node(n, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) }), sc, true); + } + keep_symbol_instances_aligned(d, id, &natural); + changed |= before.node(id) != d.node(id); + if i < last { + // The edge of an Objects on Path group is measured as the edit leaves it, with its + // members back on the path and on the pixel grid, on a copy: the edit places them. + let groups = objects_on_path::groups_in(d, id); + let m: &Document = if groups.is_empty() { + d + } else { + let c = scratch.get_or_insert_with(|| d.clone()); + if let (Some(n), Some(slot)) = (d.node(id), c.node_mut(id)) { + *slot = n.clone(); + } + let placed = objects_on_path::place_groups(c, &groups); + if !placed.is_empty() { + keep_aligned_in_with(c, &placed, &natural); + } + c + }; + let now = effects::preview::bounds_of(m, &[id], true).map(|b| if row { b.x1 } else { b.y1 }); + end = Some(now.unwrap_or(finish + shift)); + } + } + Ok(((), changed)) + })?; Ok(json!({ "count": items.len() })) } diff --git a/crates/engine/src/cmd/addons/arrange/marks.rs b/crates/engine/src/cmd/addons/arrange/marks.rs index f9bfa01329..894b6138cd 100644 --- a/crates/engine/src/cmd/addons/arrange/marks.rs +++ b/crates/engine/src/cmd/addons/arrange/marks.rs @@ -6,12 +6,12 @@ #[cfg(test)] mod tests; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind}; use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes}; use vectorcraft_render::drawn_bounds_with; @@ -36,7 +36,22 @@ pub fn specs() -> Vec { "Mark Bounds of Each", ["Object", "Plug-ins", "Arrange Tools"], None, - "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", + "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \ + \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \ + \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 \ + (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), \ + color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object \ + (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, \ + stacked directly above its object (above the outermost clip group, clipping sublayer or live object that holds it: \ + a blend, compound path, compound shape, Shaper group, Objects on Path group, Live Paint group, dimension, graph, flare, envelope, \ + mesh, repeat, intertwine, Image Trace group, generated art group, graph series, graph design copy or \ + clipping pieces group, so the clip does not hide them and the live object does not take them in; in isolation mode, \ + marks that would go outside the isolated art are an error). Selected parts of compound paths, envelopes, meshes, repeats, \ + Shaper groups and blends with a stored spine or Align to Path, and hidden Image Trace sources, are measured as the outermost \ + such live object, with one set of marks per object. Other blend keys and compound shape operands keep their own bounds. \ + A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds \ + such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; \ + one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", has_selection, mark_bounds )] @@ -81,13 +96,18 @@ fn corner_paths(r: Rect, length: f64) -> Vec { .collect() } -/// Where the marks of object `id` go: directly above it, or above the outermost clip group or -/// clipping sublayer that holds it at any depth, which would otherwise clip them. A top-level layer -/// with a clipping mask holds its marks too, since nothing lies outside it. -fn anchor(d: &Document, id: NodeId) -> NodeId { +/// Where the marks of object `id` go: directly above it, or above the outermost clip group, +/// clipping sublayer or live object (a blend, compound path, compound shape, Shaper group, Objects on Path group, +/// Live Paint group, dimension, graph, flare, envelope, mesh, repeat, intertwine, Image Trace group, generated art group, +/// graph series, graph design copy or clipping pieces group) that holds it at any +/// depth, which would otherwise clip them or take them in as one of its parts. A top-level layer +/// with a clipping mask holds its marks too, since nothing lies outside it. `held` keeps each +/// container's answer, so that siblings selected together look each container up once. +fn anchor(d: &Document, id: NodeId, held: &mut HashMap) -> NodeId { let (mut at, mut outermost) = (id, id); while let Some(up) = d.parent_of(at) { - if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() { + let holds = *held.entry(up).or_insert_with(|| d.node(up).is_some_and(|n| n.clips() || !plain(n)) && d.parent_of(up).is_some()); + if holds { outermost = up; } at = up; @@ -95,6 +115,51 @@ fn anchor(d: &Document, id: NodeId) -> NodeId { outermost } +/// Whether `n` is a layer or a group with no live role, which keeps new art as an ordinary member. +fn plain(n: &Node) -> bool { + let e = n.extras(); + matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) + && !n.is_compound_shape() + && e.shaper.is_none() + && e.objects_on_path.is_none() + && e.dimension.is_none() + && e.graph.is_none() + && e.flare.is_none() + && e.trace.is_none() + && e.generated.is_none() + && e.series_index.is_none() + && !e.graph_design_art + && !e.clip_pieces + && e.live_paint_gaps.is_none() + && !vectorcraft_tools::builder::is_live_paint(n) +} + +/// The outermost live object that draws a selected part with different geometry or placement. +fn measured_object(d: &Document, id: NodeId) -> NodeId { + let (mut at, mut measured) = (id, id); + while let Some(up) = d.parent_of(at) { + if let Some(n) = d.node(up) { + let redraws = match &n.kind { + NodeKind::Compound { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => true, + NodeKind::Blend { spec, .. } => { + (spec.spine.is_some() && !spec.no_spine) || spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath + } + _ => { + n.extras().shaper.is_some() + || (n.extras().trace.is_some() + && n.children() + .is_some_and(|children| children.first().is_some_and(|c| c.id == at) && n.editing_children().len() < children.len())) + } + }; + if redraws { + measured = up; + } + } + at = up; + } + measured +} + fn mark_bounds(s: &mut Session, p: &Value) -> Result { const C: &str = COMMAND; let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle"); @@ -106,18 +171,39 @@ fn mark_bounds(s: &mut Session, p: &Value) -> Result { if roots.len() > MAX_OBJECTS { return Err(bad(C, "too many objects selected (at most 20000)")); } - let d = &s.doc()?.doc; + let st = s.doc()?; + let (d, isolation) = (&st.doc, st.isolation); let symbols = d.symbol_boxes(); let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len()); + let mut held: HashMap = HashMap::new(); + let mut measured = HashSet::new(); let mut too_small = false; for id in roots { + if d.node(id).is_none_or(|n| n.is_guide()) { + continue; + } + let id = measured_object(d, id); + if !measured.insert(id) { + continue; + } let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue }; + let placed = matches!(n.kind, NodeKind::Blend { .. }).then(|| { + let mut art = vectorcraft_render::effects::expand_live_deep(Some(d), n); + art.appearance = n.appearance.clone(); + art + }); + let n = placed.as_ref().unwrap_or(n); let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) }; let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) else { continue }; // Corner legs are at most half a side, so an object too small for any leg gets no marks. let (lx, ly) = legs(r, length); if rectangle || lx > FLAT || ly > FLAT { - marked.push((anchor(d, id), r)); + let at = anchor(d, id, &mut held); + // Marks placed outside the isolated art could not be selected or edited there. + if isolation.is_some_and(|iso| iso == at || !d.ancestry(at).is_some_and(|a| a.contains(&iso))) { + return Err(bad(C, "the marks would go outside the isolated art: exit isolation mode first")); + } + marked.push((at, r)); } else { too_small = true; } diff --git a/crates/engine/src/cmd/addons/arrange/marks/tests.rs b/crates/engine/src/cmd/addons/arrange/marks/tests.rs index 13c9401464..186c433505 100644 --- a/crates/engine/src/cmd/addons/arrange/marks/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/marks/tests.rs @@ -288,6 +288,228 @@ fn marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer() { assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == art).map(|i| i + 1), "{stack:?}"); } +#[test] +fn marks_on_envelope_sources_follow_the_drawn_bounds_once_per_live_object() { + for nested in [false, true] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 20.0, 0.0, 20.0, 20.0); + let top = rect(&mut s, 180.0, 120.0, 100.0, 60.0); + select(&mut s, &[a, b, top]); + let r = s.execute("object.envelope.makeWithTopObject", &json!({})).unwrap(); + let envelope = NodeId(r["id"].as_u64().unwrap()); + let outermost = if nested { + let r = s.execute("object.repeat.grid", &json!({"ids": [envelope.0], "rows": 2, "cols": 2})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) + } else { + envelope + }; + let layer = parent(&s, outermost); + let before = node(&s, outermost); + let d = &s.doc().unwrap().doc; + let drawn = vectorcraft_render::drawn_bounds(d, d.node(outermost).unwrap()).unwrap(); + assert!(drawn.x0 > marks_bounds(&s, b).x1, "the visible art is away from its sources"); + for selected in [vec![a], vec![a, b], vec![a, envelope]] { + for style in ["corners", "rectangle"] { + for bounds in ["geometric", "visual"] { + select(&mut s, &selected); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({"style": style, "bounds": bounds})).unwrap(); + let marks = ids_of(&r); + assert_eq!(r["count"], 1, "one set of marks for the live object"); + assert_eq!(marks.len(), 1); + assert_eq!(children(&s, layer), vec![outermost, marks[0]]); + assert_eq!(node(&s, outermost), before); + assert!(near(marks_bounds(&s, marks[0]), (drawn.x0, drawn.y0, drawn.x1, drawn.y1)), "{nested}, {style}, {bounds}"); + assert_eq!(steps(&s), n + 1); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), marks); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(children(&s, layer), vec![outermost]); + assert_eq!(node(&s, outermost), before); + } + } + } + } +} + +#[test] +fn marks_on_a_blend_key_or_compound_shape_operand_go_above_the_live_object() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("object.blend.make", &json!({})).unwrap(); + let blend = s.doc().unwrap().selection.objects[0]; + let layer = parent(&s, blend); + select(&mut s, &[a]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, blend), vec![a, b], "the blend keeps its keys"); + assert_eq!(children(&s, layer), vec![blend, mark]); + assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 20.0, 20.0)), "the key's own bounds"); + s.execute("edit.undo", &json!({})).unwrap(); + + for stored_spine in [false, true] { + s.execute("object.blend.options", &json!({"id": blend.0, "orientation": if stored_spine { "page" } else { "path" }})).unwrap(); + if stored_spine { + s.execute("object.blend.spine.reshapeSegment", &json!({"id": blend.0, "segment": 0, "t": 0.5, "dx": 0, "dy": 60})).unwrap(); + } + let before = node(&s, blend); + let vectorcraft_doc::NodeKind::Blend { children: keys, spec } = &before.kind else { panic!("a blend") }; + let drawn = vectorcraft_doc::live::blend_expand(keys, spec).iter().filter_map(Node::visual_bounds).reduce(|a, b| a.union(b)).unwrap(); + select(&mut s, &[a, b]); + let r = s.execute(COMMAND, &json!({"bounds": "visual"})).unwrap(); + let marks = ids_of(&r); + assert_eq!(r["count"], 1, "repositioned keys are measured as one live object"); + assert_eq!(marks.len(), 1); + assert_eq!(children(&s, layer), vec![blend, marks[0]]); + assert_eq!(node(&s, blend), before); + assert!(near(marks_bounds(&s, marks[0]), (drawn.x0, drawn.y0, drawn.x1, drawn.y1))); + s.execute("edit.undo", &json!({})).unwrap(); + } + + let c = rect(&mut s, 100.0, 100.0, 30.0, 30.0); + let d = rect(&mut s, 110.0, 100.0, 30.0, 30.0); + select(&mut s, &[c, d]); + s.execute("object.compoundShape.make", &json!({"mode": "subtract"})).unwrap(); + let shape = s.doc().unwrap().selection.objects[0]; + select(&mut s, &[d]); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, shape), vec![c, d], "the compound shape keeps its operands"); + assert!(near(marks_bounds(&s, mark), (110.0, 100.0, 140.0, 130.0)), "the operand's own bounds"); + let stack = children(&s, parent(&s, shape)); + assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == shape).map(|i| i + 1), "{stack:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + + // With the compound shape isolated, the marks could only go outside the isolated art: refused. + s.execute("object.isolate", &json!({"id": shape.0})).unwrap(); + select(&mut s, &[d]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(refused.contains("outside the isolated art"), "{refused}"); + assert_eq!(steps(&s), n, "no undo step"); + assert!(*s.doc().unwrap().doc == *before); +} + +#[test] +fn marks_on_an_outlined_glyph_stay_directly_above_it_inside_the_outlines_group() { + for isolated in [false, true] { + let mut s = session(); + let text = + s.execute("text.create", &json!({"x": 20, "y": 60, "text": "AB", "size": 24, "font": "Source Sans 3", "style": "Regular"})).unwrap(); + select(&mut s, &[NodeId(text["id"].as_u64().unwrap())]); + let outlines = ids_of(&s.execute("type.createOutlines", &json!({})).unwrap())[0]; + let glyphs = children(&s, outlines); + if isolated { + s.execute("object.isolate", &json!({"id": outlines.0})).unwrap(); + } + select(&mut s, &[glyphs[0]]); + let bounds = marks_bounds(&s, glyphs[0]); + let mark = ids_of(&s.execute(COMMAND, &json!({})).unwrap())[0]; + assert_eq!(parent(&s, mark), outlines); + let mut expected = glyphs; + expected.insert(1, mark); + assert_eq!(children(&s, outlines), expected); + assert!(near(marks_bounds(&s, mark), (bounds.x0, bounds.y0, bounds.x1, bounds.y1))); + } +} + +#[test] +fn marks_measure_blend_keys_and_steps_placed_on_a_diagonal_spine() { + let mut s = session(); + let a = rect(&mut s, 20.0, 30.0, 40.0, 10.0); + let b = rect(&mut s, 120.0, 130.0, 20.0, 40.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 8})).unwrap(); + s.execute("object.blend.make", &json!({"spacing": "steps", "steps": 3, "orientation": "path"})).unwrap(); + let blend = s.doc().unwrap().selection.objects[0]; + let before = node(&s, blend); + let vectorcraft_doc::NodeKind::Blend { children: keys, spec } = &before.kind else { panic!("a blend") }; + let placed = vectorcraft_doc::live::blend_expand(keys, spec); + assert!(placed.len() > keys.len()); + let geometry = placed.iter().map(|n| n.path_data().unwrap().bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap(); + let visual = placed.iter().map(|n| n.visual_bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap(); + let stored = before.geometric_bounds().unwrap(); + assert!(geometry.y0 < stored.y0 || geometry.y1 > stored.y1); + assert!(visual.x0 < geometry.x0 && visual.y0 < geometry.y0 && visual.x1 > geometry.x1 && visual.y1 > geometry.y1); + + for selected in [vec![a], vec![a, b], vec![blend]] { + for style in ["corners", "rectangle"] { + for (bounds, expected) in [("geometric", geometry), ("visual", visual)] { + select(&mut s, &selected); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({"style": style, "bounds": bounds})).unwrap(); + let marks = ids_of(&r); + assert_eq!(r["count"], 1); + assert_eq!(marks.len(), 1); + let actual = marks_bounds(&s, marks[0]); + assert!( + near(actual, (expected.x0, expected.y0, expected.x1, expected.y1)), + "{selected:?}, {style}, {bounds}: {actual:?}, {expected:?}" + ); + for shape in &placed { + let r = if bounds == "visual" { shape.visual_bounds().unwrap() } else { shape.path_data().unwrap().bounds().unwrap() }; + assert!(actual.x0 <= r.x0 + 1e-6 && actual.y0 <= r.y0 + 1e-6 && actual.x1 >= r.x1 - 1e-6 && actual.y1 >= r.y1 - 1e-6); + } + assert_eq!(node(&s, blend), before); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, blend), before); + } + } + } +} + +#[test] +fn marks_on_a_dimension_part_go_above_the_live_object() { + let mut s = session(); + let r = s.execute("dimension.create", &json!({"a": [0, 0], "b": [100, 0]})).unwrap(); + let dimension = NodeId(r["id"].as_u64().unwrap()); + let layer = parent(&s, dimension); + let parts = children(&s, dimension); + let before = node(&s, dimension); + select(&mut s, &[parts[0]]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, dimension), parts, "the dimension keeps its generated parts"); + assert_eq!(node(&s, dimension), before); + assert_eq!(children(&s, layer), vec![dimension, mark]); + + let before = node(&s, mark); + s.execute("dimension.update", &json!({"ids": [dimension.0], "offset": 40})).unwrap(); + assert_eq!(children(&s, layer), vec![dimension, mark]); + assert_eq!(node(&s, mark), before, "updating the dimension preserves the mark"); +} + +#[test] +fn marks_on_an_image_trace_part_go_above_the_live_object() { + let mut s = session(); + let art = rect(&mut s, 20.0, 30.0, 60.0, 40.0); + select(&mut s, &[art]); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + let r = s.execute("imageTrace.make", &json!({"params": {"ignoreWhite": true}})).unwrap(); + let trace = NodeId(r["id"].as_u64().unwrap()); + let layer = parent(&s, trace); + let parts = children(&s, trace); + let before = node(&s, trace); + let part = before.children().unwrap().iter().find(|n| n.path_data().is_some()).unwrap().id; + select(&mut s, &[part]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, trace), parts, "the trace keeps its generated parts"); + assert_eq!(node(&s, trace), before); + assert_eq!(children(&s, layer), vec![trace, mark]); + + let before = node(&s, mark); + let r = s.execute("imageTrace.make", &json!({"id": trace.0, "params": {"ignoreWhite": true, "threshold": 100}})).unwrap(); + let retraced = NodeId(r["id"].as_u64().unwrap()); + assert_eq!(children(&s, layer), vec![retraced, mark]); + assert_eq!(node(&s, mark), before, "retracing preserves the mark"); +} + #[test] fn flat_objects_get_lines_and_guides_and_empty_groups_none() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index a3c44bd9db..bb38e9437e 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -185,6 +185,67 @@ fn offset_measures_visual_bounds_and_clipping_groups_by_their_mask() { assert!(near(bounds(&s, c), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c)); } +#[test] +fn offset_chains_pixel_aligned_objects_from_where_they_snap() { + let mut s = session(); + let ids: Vec = (0..4).map(|i| rect(&mut s, 100.0 * f64::from(i), 0.0, 10.0, 10.0)).collect(); + select(&mut s, &ids); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + s.execute("addon.arrange.offset", &json!({"gap": 0.25})).unwrap(); + let b: Vec = ids.iter().map(|i| bounds(&s, *i)).collect(); + let gaps: Vec = b.windows(2).map(|w| w[1].x0 - w[0].x1).collect(); + assert!(gaps.iter().all(|g| *g < 2.0), "they moved together: {gaps:?}"); + // Each one starts from where the one before it snapped to, so every gap is the same. + assert!(gaps.iter().all(|g| (g - gaps[0]).abs() < 1e-6), "{gaps:?}"); + // Touching objects that all snap back where they were: no undo step. + let mut s = session(); + let ids: Vec = (0..4).map(|i| rect(&mut s, 10.0 * f64::from(i), 0.0, 10.0, 10.0)).collect(); + select(&mut s, &ids); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + let n = steps(&s); + s.execute("addon.arrange.offset", &json!({"gap": 0.25})).unwrap(); + assert_eq!(steps(&s), n); +} + +#[test] +fn offset_chains_from_where_a_pixel_aligned_symbol_instance_snaps() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + rect(&mut s, 100.0, 0.0, 10.0, 10.0); + let b = NodeId(s.execute("symbol.new", &json!({"name": "Pixel", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + select(&mut s, &[a, b, c]); + let gap = 0.25; + let n = steps(&s); + s.execute("addon.arrange.offset", &json!({"gap": gap})).unwrap(); + let (a, b, c) = (bounds(&s, a), bounds(&s, b), bounds(&s, c)); + assert!((b.x0 - a.x1 - gap).abs() > 1e-6, "the instance snapped: {a:?} {b:?}"); + assert!((c.x0 - b.x1 - gap).abs() < 1e-6, "the next gap is {gap}: {b:?} {c:?}"); + assert_eq!(steps(&s), n + 1); + s.execute("addon.arrange.offset", &json!({"gap": gap})).unwrap(); + assert_eq!(steps(&s), n + 1, "snapping back in place adds no undo step"); +} + +#[test] +fn offset_chains_from_the_edge_an_objects_on_path_group_ends_with() { + for gap in [0.6, 0.3, 1.45] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let aligned = rect(&mut s, 100.0, 100.0, 10.0, 10.0); + select(&mut s, &[aligned]); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + let loose = rect(&mut s, 100.0, 200.0, 10.0, 10.0); + let path = NodeId(s.execute("shape.line", &json!({"x1": 30.5, "y1": 50.0, "x2": 30.5, "y2": 150.0})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[aligned, loose]); + let g = NodeId(s.execute("object.objectsOnPath.attach", &json!({"path": path.0})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + select(&mut s, &[a, g, c]); + s.execute("addon.arrange.offset", &json!({"gap": gap})).unwrap(); + let (gb, cb) = (bounds(&s, g), bounds(&s, c)); + assert!((cb.x0 - gb.x1 - gap).abs() < 1e-6, "gap {gap}: the next one starts {gap} past the group's final edge: {gb:?} {cb:?}"); + } +} + #[test] fn offset_makes_no_step_when_nothing_moves_and_skips_locked_objects() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index a9f1b48166..8dff9593e9 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Randomize Fill Colors", ["Object", "Plug-ins", "Color Effects"], None, - "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", + "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. A user compound path or live compound shape directly inside a graph series group takes a color unless that series is set to draw a compound design: a marker design while it draws markers, or a column design while it draws columns. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", has_selection, random_fill::run ), diff --git a/crates/engine/src/cmd/addons/color/random_fill.rs b/crates/engine/src/cmd/addons/color/random_fill.rs index eaf78e5660..799da3c423 100644 --- a/crates/engine/src/cmd/addons/color/random_fill.rs +++ b/crates/engine/src/cmd/addons/color/random_fill.rs @@ -6,7 +6,7 @@ #[cfg(test)] mod tests; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; @@ -16,7 +16,7 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use super::super::super::colorcmds::{edit_if_changed, keeping_series_paint}; #[cfg(test)] use super::super::super::graph::is_design_art; -use super::super::super::graph::{is_series_group, paint_targets}; +use super::super::super::graph::{is_series_group, paint_targets, series_drawn_designs}; use super::super::super::menucmds::whole_or; use super::super::super::paint::swatch_solid; use super::super::super::{bad, checked_ids_or_selection, number_or, text_param}; @@ -210,6 +210,39 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { } let series_groups = cached_series_groups(before, &targets); let mut seen = std::collections::HashSet::new(); + let compound_groups: HashSet = targets + .iter() + .filter_map(|id| { + let n = before.node(*id)?; + if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art { + return None; + } + before.parent_of(*id).filter(|p| series_groups.contains(p)) + }) + .collect(); + let mut drawn_designs = HashMap::new(); + // The series groups whose compounds are marks: the series draws no compound design, so the graph made none of + // them from one. Only a design the series draws can have made a compound. Each series is checked once. + let compound_marks: HashSet = compound_groups + .iter() + .copied() + .filter(|group| { + let Some(index) = before.node(*group).and_then(|g| g.extras().series_index).and_then(|i| usize::try_from(i).ok()) else { + return false; + }; + let graph = before.parent_of(*group).and_then(|p| before.node(p)); + graph.is_some_and(|graph| { + let Some(spec) = graph.extras().graph.as_deref() else { return false }; + let drawn = drawn_designs.entry(graph.id).or_insert_with(|| series_drawn_designs(spec)); + let (marker, column) = drawn(index); + ![column, marker].into_iter().flatten().any(|name| { + before.graph_designs.iter().any(|design| { + design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape()) + }) + }) + }) + }) + .collect(); // A compound directly in a series group is one of the series' marks unless the graph drew it from a design; // the rest of the series' art below its top level is design art. let series_compound = |id: NodeId| { @@ -217,19 +250,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art { return false; } - let Some(group) = before.parent_of(id).filter(|p| series_groups.contains(p)).and_then(|p| before.node(p)) else { return false }; - let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false }; - let graph = before.parent_of(group.id).and_then(|p| before.node(p)).and_then(|p| p.extras().graph.as_deref()); - graph.is_some_and(|spec| { - let column = spec.series_columns.get(index).and_then(Option::as_ref).map(|c| c.design.as_str()); - let marker = spec.series_markers.get(index).and_then(Option::as_deref); - ![column, marker].into_iter().flatten().any(|name| { - before - .graph_designs - .iter() - .any(|design| design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape())) - }) - }) + before.parent_of(id).is_some_and(|p| compound_marks.contains(&p)) }; targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id) && (series_compound(*id) || !cached_is_design_art(before, *id, &series_groups))); let count = keeping_series_paint(d, &roots, |d| { diff --git a/crates/engine/src/cmd/addons/color/random_fill/tests.rs b/crates/engine/src/cmd/addons/color/random_fill/tests.rs index 11b4f989be..61655534d7 100644 --- a/crates/engine/src/cmd/addons/color/random_fill/tests.rs +++ b/crates/engine/src/cmd/addons/color/random_fill/tests.rs @@ -398,6 +398,54 @@ fn a_user_compound_in_a_series_with_a_plain_path_design_takes_a_color() { } } +#[test] +fn a_user_compound_in_a_column_series_naming_an_undrawn_compound_marker_takes_a_color() { + let mut s = session(); + let tile = rects(&mut s, 2); + select(&mut s, &tile); + let design = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[design]); + s.execute("graph.design", &json!({"new": "Tile"})).unwrap(); + assert!(matches!(s.doc().unwrap().doc.graph_designs[0].art.kind, NodeKind::Compound { .. })); + let graph = NodeId( + s.execute( + "graph.create", + &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + // A column series keeps a marker design it was given as a line series, and does not draw it. + s.edit("Name a marker design on a column series", |d, _| { + let mut extras = d.node_mut(graph).unwrap().extras_mut(); + let spec = extras.graph.as_deref_mut().unwrap(); + spec.series_markers = vec![Some("Tile".into()), Some("Tile".into())]; + Ok(()) + }) + .unwrap(); + let d = &s.doc().unwrap().doc; + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let marks: Vec = series + .children() + .into_iter() + .flatten() + .filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none()) + .map(|m| m.id) + .collect(); + assert!(marks.len() >= 2); + let marks = &marks[..2]; + select(&mut s, marks); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group)); + for ids in [vec![compound], vec![group], vec![graph]] { + s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.4)), "{ids:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + #[test] fn grouped_paths_in_a_graph_series_keep_their_fills_as_for_paint_set_fill() { for kind in ["column", "line", "scatter"] { diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 68681b50fa..167cc4a9d1 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -2,10 +2,12 @@ //! the document named with the date and time through File › Save a Copy's save; New Symbols from //! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a //! copy of every open document to one folder as Save a Copy does (#4920); Batch Trace Folder traces -//! each image of a folder and saves the results to another ([`batch_trace`], #4921). Its submenu +//! each image of a folder and saves the results to another ([`batch_trace`], #4921); Flood Fill +//! Artboards puts an artboard-sized rectangle on a layer of its own ([`flood_fill`]). Its submenu //! (Object › Plug-ins › Document Tools) is the UI's. mod batch_trace; +mod flood_fill; #[cfg(test)] mod tests; @@ -60,9 +62,36 @@ pub fn specs() -> Vec { has_doc, symbols_from_layers ), + cmd!( + "addon.document.floodFillArtboards", + "Flood Fill Artboards", + ["Object", "Plug-ins", "Document Tools"], + None, + "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), activeArtboard?: n (0-based index of an existing artboard; the journal records that default here, for a replay; takes precedence over the view's active artboard; ignored when artboards is given or all is true; omitted from recorded actions), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; explicit RGB colors convert to the document's color model as paint.setFill does; default: the current fill, using the live fill after earlier batch steps or the fill the preview began with in a Flood Fill preview, an error when that is None), keepModel?: bool (as paint.setFill: true keeps an explicit RGB color in RGB), layer?: name (default: \"Flood Fill\"; trimmed, nonempty, at most 255 characters after trimming)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked, hidden or a template, in which case the prior selection stays. The current layer stays as it was. One undo step. Params must be an object or null (omitted options). Every option used is checked: null and values of the wrong type are errors. Refused in isolation mode or while a symbol, pattern or opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", + flood_fill_enabled, + flood_fill::flood_fill_artboards + ), ] } +fn flood_fill_enabled(s: &Session) -> std::result::Result<(), String> { + super::super::maskedit::outside_mask_editing(s)?; + let st = s.active().ok_or("no document open")?; + if st.doc.artboards.is_empty() { + return Err("the document has no artboards".into()); + } + if st.doc.symbol_edit.is_some() { + return Err("finish editing the symbol before filling artboards".into()); + } + if st.doc.pattern_edit.is_some() { + return Err("finish editing the pattern before filling artboards".into()); + } + if st.isolation.is_some() { + return Err("exit isolation mode before filling artboards".into()); + } + Ok(()) +} + /// A document is open and the time can be told. fn has_clock(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; diff --git a/crates/engine/src/cmd/addons/document/flood_fill.rs b/crates/engine/src/cmd/addons/document/flood_fill.rs new file mode 100644 index 0000000000..349cb65455 --- /dev/null +++ b/crates/engine/src/cmd/addons/document/flood_fill.rs @@ -0,0 +1,147 @@ +//! Flood Fill Artboards (`addon.document.floodFillArtboards`): a rectangle exactly the size of each +//! chosen artboard, painted with the current fill or a given color and no stroke, on a layer kept +//! for these rectangles. The rectangles are editable art, unlike an artboard's background color +//! (`artboard.setProps {color}`), which is a property of the artboard. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; +use vectorcraft_geom::{Affine, FillRule}; + +use super::super::super::layer::make_layer; +use super::super::super::newart::NewArt; +use super::super::super::panelcmds::listed_artboards; +use super::super::super::{bad, color_value}; +use crate::{Result, Session}; + +const COMMAND: &str = "addon.document.floodFillArtboards"; +/// The layer the rectangles go on when `layer` is left out. +const LAYER: &str = "Flood Fill"; +/// The longest layer name taken, in characters. +const MAX_NAME: usize = 255; + +/// `{artboards?, all?, activeArtboard?, color?, keepModel?, layer?}`: see the command's params text in [`super::specs`]. +pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result { + if !p.is_null() && !p.is_object() { + return Err(bad(COMMAND, "params must be an object or null")); + } + let st = s.doc()?; + let d = &st.doc; + if d.symbol_edit.is_some() { + return Err(bad(COMMAND, "finish editing the symbol before filling artboards")); + } + if d.pattern_edit.is_some() { + return Err(bad(COMMAND, "finish editing the pattern before filling artboards")); + } + if st.isolation.is_some() { + return Err(bad(COMMAND, "exit isolation mode before filling artboards")); + } + if d.artboards.is_empty() { + return Err(bad(COMMAND, "the document has no artboards")); + } + if p.get("keepModel").is_some_and(Value::is_null) { + return Err(bad(COMMAND, "`keepModel` must be true or false")); + } + super::super::super::paint::check_keep_model(p, COMMAND)?; + let all = match p.get("all") { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad(COMMAND, "`all` must be true or false"))?, + }; + let boards = match p.get("artboards") { + Some(_) if all => return Err(bad(COMMAND, "give `artboards` or `all`, not both")), + Some(v) => listed_artboards(d, v, "artboards", COMMAND)?, + None if all => (0..d.artboards.len()).collect(), + None => vec![match p.get("activeArtboard") { + Some(v) => { + let i = v.as_u64().ok_or_else(|| bad(COMMAND, "`activeArtboard` must be a whole number"))?; + usize::try_from(i).ok().filter(|i| *i < d.artboards.len()).ok_or_else(|| bad(COMMAND, "no such artboard"))? + } + None => active_artboard(st), + }], + }; + // In Flood Fill's own preview the current fill is the one the interaction began with: a + // preview's selected rectangles may have given their color to the new-art paints since. A + // batch step takes the live fill, as the steps before it left it. + let current = st.interaction.as_ref().filter(|_| s.previewing && s.batch_stash.is_none()).map_or(&s.paint.fill, |it| &it.paint.fill); + let fill = match p.get("color") { + Some(v) => { + let color = color_value(v).filter(finite).ok_or_else(|| bad(COMMAND, format!("bad color {v}")))?; + Paint::solid(super::super::super::paint::new_color(s, p, color)) + } + None => match current { + Paint::None => return Err(bad(COMMAND, "the current fill is None: pick a fill or give `color`")), + paint => paint.clone(), + }, + }; + let name = match p.get("layer") { + None => LAYER.to_string(), + Some(v) => { + let name = v.as_str().map(str::trim).ok_or_else(|| bad(COMMAND, "`layer` must be a string"))?; + if name.is_empty() { + return Err(bad(COMMAND, "`layer` must not be empty")); + } + if name.chars().count() > MAX_NAME { + return Err(bad(COMMAND, format!("`layer` must be at most {MAX_NAME} characters"))); + } + name.to_string() + } + }; + let found = d.layers.iter().find(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())); + if found.is_some_and(|l| l.clips()) { + return Err(bad(COMMAND, "the destination layer holds a clipping mask")); + } + let found = found.map(|l| l.id); + let rects: Vec<_> = boards.iter().filter_map(|i| d.artboards.get(*i).map(|a| a.rect)).collect(); + let look = NewArt::plain(Appearance::basic(fill, Paint::None, 0.0)); + let (layer, created, ids) = s.edit("Flood Fill Artboards", |d, sel| { + let (layer, created) = match found { + Some(id) => (id, false), + // A new layer goes below every other, so the rectangles stay behind the art. + None => { + let n = make_layer(d, Some(&name)); + (d.insert(None, 0, n)?, true) + } + }; + let mut ids = Vec::with_capacity(rects.len()); + for r in &rects { + let live = LiveShape::Rectangle { + w: r.width(), + h: r.height(), + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate(r.origin().to_vec2()), + }; + let path = live.to_path(); + let kind = NodeKind::Path { path, rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false }; + let mut n = Node::new(d.alloc_id(), kind); + look.apply(d, &mut n); + ids.push(d.insert(Some(layer), usize::MAX, n)?); + } + // Rectangles on a locked, hidden or template layer are not selected. + if d.node(layer).is_some_and(|l| l.visible && !l.locked && !l.is_template()) { + sel.set(ids.iter().copied()); + } + Ok((layer, created, ids)) + })?; + if p.get("artboards").is_none() && !all { + s.note_journal("activeArtboard", json!(boards[0])); + } + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "layer": layer.0, "created": created })) +} + +/// Whether every component of `c` is finite: a component too large for `f32` reads as infinite. +fn finite(c: &Color) -> bool { + match *c { + Color::Rgb { r, g, b } | Color::Lab { l: r, a: g, b } => [r, g, b].iter().all(|v| v.is_finite()), + Color::Cmyk { c, m, y, k } => [c, m, y, k].iter().all(|v| v.is_finite()), + Color::Gray { k } => k.is_finite(), + } +} + +/// The index of the view's active artboard ([`crate::DocState::active_artboard`]): when the +/// document no longer has it, the artboard the document opened on, else the first. +fn active_artboard(st: &crate::DocState) -> usize { + let at = |id: Option| id.and_then(|id| st.doc.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(st.doc.opened_artboard)).unwrap_or(0) +} diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index d1bd77727d..66cda25344 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -195,6 +195,706 @@ fn the_layers_highlighted_in_the_layers_panel_are_the_default() { assert_eq!((r["symbols"].clone(), r["skipped"].as_array().unwrap().len()), (json!(["Icons"]), 1)); } +const FLOOD: &str = "addon.document.floodFillArtboards"; + +/// A document of three 100 × 80 artboards with one rectangle on `Layer 1`, and a red fill. +fn boards() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 80, "artboards": 3})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s +} + +/// The children of the layer `id`. +fn kids(s: &Session, id: u64) -> Vec> { + s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap().to_vec() +} + +#[test] +fn flood_fill_covers_the_active_artboard_on_a_new_layer_at_the_bottom() { + let mut s = boards(); + let (current, steps) = (s.doc().unwrap().active_layer, s.doc().unwrap().history.undo.len()); + let before = s.doc().unwrap().doc.clone(); + let second = before.artboards[1].clone(); + s.doc_mut().unwrap().active_artboard = Some(second.id); + let r = s.execute(FLOOD, &json!({})).unwrap(); + assert_eq!(r["created"], json!(true), "{r}"); + let st = s.doc().unwrap(); + let layer = &st.doc.layers[0]; + assert_eq!((layer.id.0, layer.name.as_deref()), (r["layer"].as_u64().unwrap(), Some("Flood Fill")), "a new layer below the others"); + assert_eq!(st.doc.layers.len(), 2); + let rects = kids(&s, layer.id.0); + assert_eq!(rects.len(), 1); + let rect = &rects[0]; + assert_eq!(r["ids"], json!([rect.id.0])); + assert_eq!(rect.geometric_bounds(), Some(second.rect), "exactly the active artboard"); + assert!(matches!(&rect.kind, NodeKind::Path { live: Some(live), .. } if matches!(**live, vectorcraft_doc::LiveShape::Rectangle { .. }))); + assert_eq!(rect.appearance.fill_paint(), s.paint.fill, "the current fill"); + assert_eq!(rect.appearance.stroke_paint(), vectorcraft_color::Paint::None, "no stroke"); + let st = s.doc().unwrap(); + assert_eq!((st.selection.objects.clone(), st.active_layer), (vec![rect.id], current), "the rectangle is selected; the current layer stays"); + assert_eq!(st.history.undo.len(), steps + 1, "one undo step"); + assert_eq!(st.history.undo.last().unwrap().label, "Flood Fill Artboards"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before, "undo removes the layer and the rectangle"); +} + +#[test] +fn flood_fill_journal_replays_the_resolved_active_artboard() { + for params in [Value::Null, json!({}), json!({"all": false})] { + let mut s = boards(); + let second = s.doc().unwrap().doc.artboards[1].clone(); + s.doc_mut().unwrap().active_artboard = Some(second.id); + s.execute(FLOOD, ¶ms).unwrap(); + let (command, params) = s.journal.last().unwrap().clone(); + assert_eq!(params["activeArtboard"], json!(1)); + assert!(params.get("artboards").is_none()); + let mut replay = boards(); + let first = replay.doc().unwrap().doc.artboards[0].id; + replay.doc_mut().unwrap().active_artboard = Some(first); + let r = replay.replay(&command, ¶ms).unwrap(); + let rects = kids(&replay, r["layer"].as_u64().unwrap()); + assert_eq!(rects.len(), 1); + assert_eq!(rects[0].geometric_bounds(), Some(second.rect)); + } +} + +#[test] +fn flood_fill_action_uses_the_active_artboard_when_played() { + for params in [Value::Null, json!({}), json!({"all": false})] { + let mut s = boards(); + let second = s.doc().unwrap().doc.artboards[1].id; + s.doc_mut().unwrap().active_artboard = Some(second); + let start = s.journal.len(); + s.execute(FLOOD, ¶ms).unwrap(); + let action = s.journal_for_action(start); + assert_eq!(action.len(), 1); + let (command, params) = &action[0]; + assert!(params.get("artboards").is_none()); + assert!(params.get("activeArtboard").is_none()); + let mut playback = boards(); + let third = playback.doc().unwrap().doc.artboards[2].clone(); + playback.doc_mut().unwrap().active_artboard = Some(third.id); + let r = playback.execute(command, params).unwrap(); + let rects = kids(&playback, r["layer"].as_u64().unwrap()); + assert_eq!(rects.len(), 1); + assert_eq!(rects[0].geometric_bounds(), Some(third.rect)); + } +} + +#[test] +fn flood_fill_explicit_targets_override_the_replay_artboard_and_stay_in_actions() { + for params in [json!({"artboards": [2], "activeArtboard": null}), json!({"all": true, "activeArtboard": 99})] { + let mut s = boards(); + let start = s.journal.len(); + let r = s.execute(FLOOD, ¶ms).unwrap(); + let rects = kids(&s, r["layer"].as_u64().unwrap()); + let indices = if params.get("artboards").is_some() { vec![2] } else { vec![0, 1, 2] }; + let expected: Vec<_> = indices.iter().map(|i| s.doc().unwrap().doc.artboards[*i].rect).collect(); + assert_eq!(rects.iter().map(|n| n.geometric_bounds().unwrap()).collect::>(), expected); + let action = s.journal_for_action(start); + assert_eq!(action[0].1.get("artboards"), params.get("artboards")); + assert_eq!(action[0].1.get("all"), params.get("all")); + assert!(action[0].1.get("activeArtboard").is_none()); + } +} + +#[test] +fn flood_fill_reuses_its_layer_and_keeps_its_lock_and_visibility() { + let mut s = boards(); + let layer = s.execute(FLOOD, &json!({})).unwrap()["layer"].as_u64().unwrap(); + let first = s.doc().unwrap().doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer 1")).unwrap().id.0; + let art = kids(&s, first)[0].id.0; + s.execute("select.set", &json!({"ids": [art]})).unwrap(); + s.execute("layer.setProps", &json!({"id": layer, "locked": true})).unwrap(); + let selected = s.doc().unwrap().selection.objects.clone(); + assert_eq!(selected.len(), 1); + let r = s.execute(FLOOD, &json!({"all": true, "color": "#00ff00"})).unwrap(); + assert_eq!((r["created"].clone(), r["layer"].as_u64()), (json!(false), Some(layer)), "{r}"); + let st = s.doc().unwrap(); + let node = st.doc.node(NodeId(layer)).unwrap(); + assert!(node.locked && node.visible, "the layer stays locked"); + assert_eq!(st.doc.layers.len(), 2, "no second layer"); + assert_eq!(st.selection.objects, selected, "art on a locked layer is not selected"); + let rects = kids(&s, layer); + let added: Vec<_> = rects[1..].iter().map(|n| n.geometric_bounds().unwrap()).collect(); + let artboards: Vec<_> = st.doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(added, artboards, "one rectangle per artboard, on top of the layer's art"); + let green = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#00ff00").unwrap()); + assert!(rects[1..].iter().all(|n| n.appearance.fill_paint() == green)); + // Hidden: the layer stays hidden, and listed artboards are filled once each, in order. + s.execute("layer.setProps", &json!({"id": layer, "locked": false, "visible": false})).unwrap(); + let r = s.execute(FLOOD, &json!({"artboards": [2, 0, 2]})).unwrap(); + let bounds = |id: &Value| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + let new: Vec<_> = r["ids"].as_array().unwrap().iter().map(bounds).collect(); + assert_eq!(new, [artboards[0], artboards[2]]); + assert!(!s.doc().unwrap().doc.node(NodeId(layer)).unwrap().visible); + assert_eq!(s.doc().unwrap().selection.objects, selected, "art on a hidden layer is not selected"); + // A layer named by `layer`, found or made. + let r = s.execute(FLOOD, &json!({"layer": "Layer 1", "color": {"c": 0, "m": 0, "y": 0, "k": 50}})).unwrap(); + assert_eq!((r["created"].clone(), r["layer"].as_u64()), (json!(false), Some(first))); + let r = s.execute(FLOOD, &json!({"layer": " Paper "})).unwrap(); + assert_eq!((r["created"].clone(), s.doc().unwrap().doc.layers[0].name.as_deref()), (json!(true), Some("Paper"))); +} + +#[test] +fn flood_fill_preserves_selection_on_an_unlocked_template_layer() { + let mut s = boards(); + let art = s.doc().unwrap().selection.objects[0]; + let layer = s.execute("layer.new", &json!({"name": "Paper"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({"id": layer, "template": true, "locked": false})).unwrap(); + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + let st = s.doc().unwrap(); + let selected = st.selection.clone(); + assert!(!selected.objects.is_empty()); + let r = s.execute(FLOOD, &json!({"layer": "Paper", "all": true})).unwrap(); + let st = s.doc().unwrap(); + let node = st.doc.node(NodeId(layer)).unwrap(); + assert!(node.is_template() && node.visible && !node.locked); + assert_eq!(r["created"], json!(false)); + assert_eq!(r["layer"].as_u64(), Some(layer)); + assert_eq!(kids(&s, layer).len(), st.doc.artboards.len()); + assert_eq!(st.selection, selected); +} + +#[test] +fn flood_fill_converts_explicit_rgb_to_cmyk_like_set_fill() { + let mut s = Session::new(); + s.execute("file.new", &json!({"colorMode": "cmyk"})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let expected = s.paint.fill.clone(); + assert!(matches!(expected.color(), Some(vectorcraft_color::Color::Cmyk { .. }))); + for color in [json!("#ff0000"), json!([1.0, 0.0, 0.0])] { + let r = s.execute(FLOOD, &json!({"color": color})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert_eq!(fill, expected); + } +} + +#[test] +fn flood_fill_keep_model_keeps_explicit_rgb_in_a_cmyk_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"colorMode": "cmyk"})).unwrap(); + let r = s.execute(FLOOD, &json!({"color": "#ff0000", "keepModel": true})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert!(matches!(fill.color(), Some(vectorcraft_color::Color::Rgb { .. })), "{fill:?}"); + let undo = s.doc().unwrap().history.undo.len(); + for bad in [json!("yes"), json!(null)] { + let error = s.execute(FLOOD, &json!({"color": "#ff0000", "keepModel": bad})).unwrap_err().to_string(); + assert!(error.contains("keepModel"), "{error}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + } +} + +#[test] +fn flood_fill_refuses_isolation_without_an_edit_and_is_disabled() { + let mut s = boards(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + let st = s.doc().unwrap(); + assert_eq!(st.isolation, Some(NodeId(group))); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + let info = crate::find_command(FLOOD).unwrap().info(&s); + assert!(!info.enabled); + assert!(info.disabled_reason.unwrap().contains("exit isolation mode")); + for params in [json!({}), json!({"layer": "Layer 1"}), json!({"layer": "Paper", "all": true})] { + let error = super::flood_fill::flood_fill_artboards(&mut s, ¶ms).unwrap_err().to_string(); + assert!(error.contains("exit isolation mode"), "{error}"); + let error = s.execute(FLOOD, ¶ms).unwrap_err().to_string(); + assert!(error.contains("exit isolation mode"), "{error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + assert_eq!(st.isolation, Some(NodeId(group))); + } +} + +#[test] +fn flood_fill_in_a_batch_uses_the_fill_set_by_an_earlier_step() { + for none in [false, true] { + for preview in [false, true] { + let mut s = boards(); + if none { + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + } + let green = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#00ff00").unwrap()); + let params = json!({"commands": [ + {"command": "paint.setFill", "params": {"color": "#00ff00"}}, + {"command": FLOOD, "params": {}} + ]}); + let r = if preview { + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview("command.batch", ¶ms).unwrap(); + let r = s.preview("command.batch", ¶ms).unwrap(); + s.commit_interaction().unwrap(); + r + } else { + s.execute("command.batch", ¶ms).unwrap() + }; + let id = NodeId(r["results"][1]["ids"][0].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), green, "initial fill None: {none}, batch preview: {preview}"); + } + } +} + +#[test] +fn flood_fill_rejects_a_destination_layer_with_a_clipping_mask_without_an_edit() { + let mut s = boards(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert!(s.doc().unwrap().doc.node(layer).unwrap().clips()); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone(), s.doc().unwrap().history.undo.len(), s.paint.clone()); + let error = s.execute(FLOOD, &json!({"layer": " Layer 1 "})).unwrap_err().to_string(); + assert!(error.contains("destination layer holds a clipping mask"), "{error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); +} + +#[test] +fn flood_fill_refuses_symbol_and_pattern_editing_without_an_edit() { + for symbol in [true, false] { + let mut s = boards(); + if symbol { + s.execute("symbol.new", &json!({"name": "Flood Fill"})).unwrap(); + s.execute("symbol.edit", &json!({"name": "Flood Fill"})).unwrap(); + } else { + s.execute("object.pattern.make", &json!({"name": "Tile"})).unwrap(); + } + let st = s.doc().unwrap(); + let layer = if symbol { st.doc.symbol_edit.as_ref().unwrap().layer } else { st.doc.pattern_edit.as_ref().unwrap().layer }; + let name = st.doc.node(layer).unwrap().name.clone().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + for params in [json!({}), json!({"layer": name}), json!({"layer": "Paper"})] { + let error = s.execute(FLOOD, ¶ms).unwrap_err().to_string(); + assert!(error.contains(if symbol { "finish editing the symbol" } else { "finish editing the pattern" }), "{error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + } + } +} + +#[test] +fn flood_fill_is_disabled_while_editing_symbols_or_patterns() { + let spec = crate::find_command(FLOOD).unwrap(); + for symbol in [true, false] { + let mut s = boards(); + assert!(spec.info(&s).enabled); + if symbol { + s.execute("symbol.new", &json!({"name": "Flood Fill"})).unwrap(); + s.execute("symbol.edit", &json!({"name": "Flood Fill"})).unwrap(); + } else { + s.execute("object.pattern.make", &json!({"name": "Tile"})).unwrap(); + } + let info = spec.info(&s); + assert!(!info.enabled); + assert!(info.disabled_reason.unwrap().contains(if symbol { "finish editing the symbol" } else { "finish editing the pattern" })); + } +} + +#[test] +fn flood_fill_is_disabled_without_artboards() { + let mut s = boards(); + let spec = crate::find_command(FLOOD).unwrap(); + assert!(spec.info(&s).enabled); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear(); + let info = spec.info(&s); + assert!(!info.enabled); + assert_eq!(info.disabled_reason.as_deref(), Some("the document has no artboards")); + let before = s.doc().unwrap().doc.clone(); + for params in [json!({}), json!({"all": true})] { + assert!(s.execute(FLOOD, ¶ms).unwrap_err().to_string().contains("the document has no artboards")); + assert_eq!(*s.doc().unwrap().doc, *before); + } +} + +#[test] +fn flood_fill_action_batch_rejects_non_object_params_at_preflight() { + let mut s = boards(); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len(), s.paint.clone()); + for params in [json!([]), json!([{}]), json!(5), json!(true), json!("all")] { + let batch = json!({"commands": [{"command": FLOOD, "params": params}]}); + for error in [s.check_params("action.batch", &batch).unwrap_err(), s.execute("action.batch", &batch).unwrap_err()] { + let error = error.to_string(); + assert!(error.contains("action step 1 (`addon.document.floodFillArtboards`)"), "{error}"); + assert!(error.contains("params must be an object or null"), "{error}"); + } + assert_eq!(*s.doc().unwrap().doc, *before.0); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1); + assert_eq!(s.paint, before.2); + } +} + +#[test] +fn flood_fill_requires_object_or_null_params_directly_and_in_a_batch() { + for batch in [false, true] { + let mut s = boards(); + for params in [json!([]), json!([{}]), json!(5), json!(true), json!("all")] { + let st = s.doc().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + let result = if batch { + s.execute("command.batch", &json!({"commands": [{"command": FLOOD, "params": params}]})) + } else { + s.execute(FLOOD, ¶ms) + }; + assert!(result.is_err(), "batch: {batch}, params: {params}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + } + let result = if batch { + s.execute("command.batch", &json!({"commands": [{"command": FLOOD}]})).unwrap()["results"][0].clone() + } else { + s.execute(FLOOD, &Value::Null).unwrap() + }; + assert_eq!(result["ids"].as_array().unwrap().len(), 1); + } +} + +#[test] +fn flood_fill_replay_rejects_non_object_params_without_an_edit() { + let mut s = boards(); + let st = s.doc().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone(), s.journal.clone()); + for params in [json!([]), json!([{}]), json!(5), json!(true), json!("all")] { + let error = s.replay(FLOOD, ¶ms).unwrap_err().to_string(); + assert!(error.contains("params must be an object or null"), "{params}: {error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + assert_eq!(s.journal, before.4); + } + assert_eq!(s.replay(FLOOD, &Value::Null).unwrap()["ids"].as_array().unwrap().len(), 1); +} + +#[test] +fn flood_fill_refuses_bad_params_and_a_none_fill() { + let mut s = boards(); + let long = "x".repeat(256); + for p in [ + json!({"color": "#ff000080"}), + json!({"color": "red-ish"}), + json!({"color": null}), + json!({"artboards": [3]}), + json!({"artboards": []}), + json!({"artboards": null}), + json!({"artboards": [0.5]}), + json!({"activeArtboard": null}), + json!({"activeArtboard": "1"}), + json!({"activeArtboard": true}), + json!({"activeArtboard": -1}), + json!({"activeArtboard": 0.5}), + json!({"activeArtboard": 3}), + json!({"activeArtboard": u64::MAX}), + json!({"all": null}), + json!({"all": "yes"}), + json!({"all": true, "artboards": [0]}), + json!({"layer": ""}), + json!({"layer": " "}), + json!({"layer": 5}), + json!({"layer": null}), + json!({"layer": long}), + ] { + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + assert!(s.execute(FLOOD, &p).is_err(), "{p}"); + assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1, "{p} changed nothing"); + } + // Components too large for f32 become infinite once read. + for color in [json!({"c": 1e308, "m": 0, "y": 0, "k": 0}), json!([1e39, 0, 0]), json!({"gray": 1e41}), json!({"l": 1e39, "a": 0, "b": 0})] { + let p = json!({ "color": color }); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute(FLOOD, &p).unwrap_err().to_string(); + assert!(e.contains("bad color"), "{p}: {e}"); + assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1, "{p} changed nothing"); + } + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + let e = s.execute(FLOOD, &json!({})).unwrap_err().to_string(); + assert!(e.contains("the current fill is None"), "{e}"); + assert!(s.execute(FLOOD, &json!({"color": "#336699"})).is_ok(), "a given color needs no current fill"); +} + +/// With New Art Has Basic Appearance off, a preview in a color selects rectangles whose color the +/// new-art fill takes; a later preview without `color` still uses the fill the interaction began with. +#[test] +fn flood_fill_previews_without_color_use_the_fill_the_interaction_began_with() { + let mut s = boards(); + s.prefs.new_art_basic = false; + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red, "the previewed rectangles gave their color to the new-art fill"); + let r = s.preview(FLOOD, &json!({})).unwrap(); + s.commit_interaction().unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert_eq!(fill, red, "the fill the interaction began with, not the previewed color"); +} + +/// With New Art Has Basic Appearance off and nothing selected, rectangle previews that follow a fill +/// preview each draw with that preview's fill, not the fill the interaction began with. +#[test] +fn rectangle_previews_after_a_fill_preview_keep_its_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let blue = s.paint.fill.clone(); + assert_ne!(blue, red); + for n in 0..2 { + let r = s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert_eq!(fill, blue, "rectangle preview {n} draws with the previewed fill"); + } + s.commit_interaction().unwrap(); +} + +/// A cancel or a commit after a fill preview, a rectangle preview and a failed rectangle preview +/// puts back the fill the interaction began with. +#[test] +fn cancel_or_commit_after_a_failed_rectangle_preview_restores_the_starting_fill() { + for commit in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + assert!(s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": "wide", "height": 20})).is_err()); + if commit { + s.commit_interaction().unwrap(); + } else { + s.cancel_interaction().unwrap(); + } + assert_eq!(s.paint, before, "commit {commit}"); + } +} + +/// A cancel or a commit puts back the fill the interaction began with when a deselect preview +/// started from the rectangle preview's paints and a failed rectangle preview followed it. +#[test] +fn cancel_or_commit_after_a_deselect_and_a_failed_rectangle_preview_restores_the_starting_fill() { + for commit in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.preview("select.none", &json!({})).unwrap(); + assert!(s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": "wide", "height": 20})).is_err()); + if commit { + s.commit_interaction().unwrap(); + } else { + s.cancel_interaction().unwrap(); + } + assert_eq!(s.paint, before, "commit {commit}"); + } +} + +/// A failed fill preview after a fill preview and a rectangle preview leaves the starting fill for +/// the next rectangle preview. +#[test] +fn rectangle_preview_after_a_failed_fill_preview_uses_the_starting_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + assert!(s.preview("paint.setFill", &json!({"color": "not a color"})).is_err()); + let r = s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), red); + s.cancel_interaction().unwrap(); +} + +#[test] +fn paint_swap_previews_from_an_empty_selection_commit_one_swap() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + let before = s.paint.clone(); + assert_ne!(before.fill, before.stroke); + s.begin_interaction("Swap").unwrap(); + for _ in 0..2 { + s.preview("paint.swap", &json!({})).unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); + } + s.commit_interaction().unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); +} + +#[test] +fn paint_preview_replacement_from_an_empty_selection_uses_the_starting_defaults() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Paint").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, before.fill); + s.preview("paint.swap", &json!({})).unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); + s.commit_interaction().unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); +} + +#[test] +fn paint_previews_from_an_empty_selection_restore_defaults_on_cancel() { + for (command, params) in + [("paint.swap", json!({})), ("paint.setFill", json!({"color": "#0000ff"})), ("paint.setStroke", json!({"color": "#0000ff"}))] + { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Paint").unwrap(); + s.preview(command, ¶ms).unwrap(); + assert_ne!(s.paint, before, "{command}"); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint, before, "{command}"); + } +} + +#[test] +fn paint_preview_from_an_empty_selection_keeps_its_fill_for_the_next_step() { + for cancel in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Fill").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let blue = s.paint.fill.clone(); + assert_ne!(blue, red); + assert!(s.doc().unwrap().selection.is_empty()); + if cancel { + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, red); + } else { + let result = s.preview("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap(); + let id = NodeId(result["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), blue); + assert_eq!(s.paint.fill, blue); + s.commit_interaction().unwrap(); + } + } +} + +#[test] +fn flood_fill_cancel_with_a_selection_preserves_the_opening_paint_defaults() { + for resume in [false, true] { + for params in [json!({}), json!({"color": "#00ff00"}), json!({"color": "invalid"})] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("paint.setFill", &json!({"color": "#0000ff", "defaultsOnly": true})).unwrap(); + let st = s.doc().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + assert!(!before.1.is_empty()); + assert_ne!(st.doc.node(before.1.objects[0]).unwrap().appearance.fill_paint(), before.3.fill); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#00ff00"})).unwrap(); + let result = s.preview(FLOOD, ¶ms); + assert_eq!(result.is_err(), params["color"] == "invalid"); + s.cancel_interaction().unwrap(); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + if resume { + s.begin_interaction("Flood Fill Artboards").unwrap(); + let r = s.preview(FLOOD, &json!({})).unwrap(); + s.commit_interaction().unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), before.3.fill); + } + } + } +} + +/// With New Art Has Basic Appearance off and nothing selected, a canceled preview in a color puts +/// back the new-art fill that its selected rectangles had given their color to. +#[test] +fn flood_fill_cancel_from_an_empty_selection_keeps_the_new_art_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + assert!(s.doc().unwrap().selection.is_empty()); + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red, "the previewed rectangles gave their color to the new-art fill"); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, red, "the cancel puts the new-art fill back"); + assert!(s.doc().unwrap().selection.is_empty()); +} + +#[test] +fn flood_fill_cancel_after_a_rejected_preview_keeps_the_new_art_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + assert!(s.doc().unwrap().selection.is_empty()); + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red); + assert!(s.preview(FLOOD, &json!({"color": [1e39, 0, 0]})).is_err()); + assert_eq!(s.paint.fill, red); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, red); + assert!(s.doc().unwrap().selection.is_empty()); +} + +/// A commit after a fill preview with nothing selected and a failed flood fill preview puts back +/// the fill the interaction began with. +#[test] +fn flood_fill_commit_after_a_fill_preview_and_a_rejected_preview_restores_the_new_art_fill() { + for stroke_first in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + if stroke_first { + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + } + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red); + if !stroke_first { + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + } + let stroke = s.paint.stroke.clone(); + assert!(s.preview(FLOOD, &json!({"color": [1e39, 0, 0]})).is_err()); + assert_eq!(s.paint.fill, red, "stroke first {stroke_first}"); + s.commit_interaction().unwrap(); + assert_eq!(s.paint.fill, red, "stroke first {stroke_first}"); + assert_eq!(s.paint.stroke, stroke, "a command run outside the previews keeps its change (stroke first {stroke_first})"); + } +} + /// #4920: Export All Open Documents writes an SVG of each open document; a folder that can't be /// written lists every document in `failed`, and either way the active document stays active. #[test] diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index e8e512a448..ef010d7f32 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -71,7 +71,7 @@ pub fn specs() -> Vec { "Make Numbers Sequence…", ["Object", "Plug-ins", "Type Tools"], None, - "{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}", + "{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error, unless replace skips it because its story holds no number or placeholder. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}", has_selection, numbers::make_numbers ), diff --git a/crates/engine/src/cmd/addons/typetools/numbers.rs b/crates/engine/src/cmd/addons/typetools/numbers.rs index c83c306496..f8064b9ded 100644 --- a/crates/engine/src/cmd/addons/typetools/numbers.rs +++ b/crates/engine/src/cmd/addons/typetools/numbers.rs @@ -9,7 +9,7 @@ mod tests; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject, TextRun}; use vectorcraft_geom::Rect; use vectorcraft_render::effects; use vectorcraft_text::edit; @@ -273,6 +273,109 @@ pub(crate) fn edits(text: &str, spans: Vec<(usize, usize)>, number: &str) -> Vec spans.into_iter().rev().filter(|(a, b)| text.get(*a..*b) != Some(number)).map(|(a, b)| (a, b, number.to_string())).collect() } +thread_local! { + /// [`text_passes`] of this thread. + static TEXT_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times Make Numbers Sequence has gone over a type object's text or style runs on this +/// thread: once to build the text an object would read, and once for each part of the object it +/// changes, however many numbers the text holds. +#[cfg(test)] +pub(crate) fn text_passes() -> u64 { + TEXT_PASSES.get() +} + +/// Adds one to [`text_passes`]. +fn note_text_pass() { + TEXT_PASSES.set(TEXT_PASSES.get().saturating_add(1)); +} + +/// `text` with `changes` (from the last to the first, as [`edits`] gives them) made. +pub(crate) fn replaced(text: &str, changes: &[Edit]) -> String { + note_text_pass(); + let mut out = String::with_capacity(text.len()); + let mut at = 0; + for (a, b, n) in changes.iter().rev() { + out.push_str(text.get(at..*a).unwrap_or_default()); + out.push_str(n); + at = *b; + } + out.push_str(text.get(at..).unwrap_or_default()); + out +} + +/// Makes `changes` (from the last to the first, as [`edits`] gives them) in `t`, with the +/// paragraphs, style runs and ruby that replacing each range by itself with +/// [`edit::replace_range`] would give, in one pass over each. +pub(crate) fn apply(t: &mut TextObject, changes: &[Edit]) { + if changes.len() < 2 || !t.ruby.is_empty() || t.runs.iter().any(|r| r.inline.is_some()) || { + let text = t.plain_text(); + changes.iter().any(|(a, b, n)| n.contains('\n') || text.get(*a..*b).is_none_or(|s| s.contains('\n'))) + } { + // One change (a whole text), one that adds or removes paragraphs, or text with ruby or + // inline art, whose spans each replacement moves or drops in turn. + for (a, b, n) in changes { + note_text_pass(); + t.splice_paras(*a, *b, n); + edit::replace_range(&mut t.runs, *a, *b, n); + t.ruby_after_replace(*a, *b, n.len()); + } + return; + } + // Changes inside paragraphs leave every paragraph's style where it is: one splice sets the + // paragraph list as each of them would. + if let Some((a, b, n)) = changes.first() { + t.splice_paras(*a, *b, n); + } + replace_runs(&mut t.runs, changes); +} + +/// The runs with each range of `changes` replaced by its number in the style of the range's first +/// character, without a glyph choice, as [`edit::replace_range`] gives it. +fn replace_runs(runs: &mut Vec, changes: &[Edit]) { + note_text_pass(); + let old = std::mem::take(runs); + let mut out: Vec = Vec::with_capacity(old.len()); + let mut pending = changes.iter().rev().peekable(); + // Where the run starts and where the last replaced range ends. + let (mut off, mut cut) = (0, 0); + for r in old { + let (start, end) = (off, off + r.text.len()); + off = end; + // The run's style without a glyph choice, for pieces that start inside it and numbers. + let plain = CharStyle { glyph_alternate: None, ..r.style.clone() }; + // A piece of the run from `a` to `b`: one that starts inside it has no glyph choice. + let piece = |out: &mut Vec, a: usize, b: usize| { + let style = if a == start { &r.style } else { &plain }; + push(out, r.text.get(a - start..b - start).unwrap_or_default(), style); + }; + let mut pos = start.max(cut).min(end); + while let Some((a, b, n)) = pending.next_if(|(a, _, _)| *a < end) { + if pos < *a { + piece(&mut out, pos, *a); + } + push(&mut out, n, &plain); + cut = *b; + pos = cut.min(end); + } + if pos < end { + piece(&mut out, pos, end); + } + } + edit::normalize(&mut out); + *runs = out; +} + +/// Adds `text` in `style` to the end of `out`, onto the last run when it has the same style, so a +/// style is copied once for each change of style rather than once for each number. +fn push(out: &mut Vec, text: &str, style: &CharStyle) { + match out.last_mut() { + Some(last) if last.style == *style && last.inline.is_none() && style.glyph_alternate.is_none() => last.text.push_str(text), + _ => out.push(TextRun { text: text.to_string(), style: style.clone(), inline: None }), + } +} + pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { const C: &str = COMMAND; let o = Options::parse(p)?; @@ -292,24 +395,43 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { if texts.len() > MAX_TEXTS { return Err(bad(C, format!("too many type objects: at most {MAX_TEXTS}"))); } - let threads = threads::ThreadIndex::of(d); - if texts.iter().any(|id| threads.threaded(*id)) { - return Err(bad(C, "threaded type can't be numbered: its frames share one story")); - } let plain = |id: NodeId| match d.node(id).map(|n| &n.kind) { Some(NodeKind::Text(t)) => t.plain_text(), _ => String::new(), }; - // Only objects that hold a number or the placeholder count, for the order too. - let mut texts: Vec<(NodeId, String)> = texts - .into_iter() - .map(|id| (id, plain(id))) - .filter(|(_, t)| match o.replace { - "numbers" => t.bytes().any(|b| b.is_ascii_digit()), - "placeholder" => !placeholder_spans(t).is_empty(), - _ => true, - }) - .collect(); + let threads = threads::ThreadIndex::of(d); + let threaded = || bad(C, "threaded type can't be numbered: its frames share one story"); + if o.replace == "all" && texts.iter().any(|id| threads.threaded(*id)) { + return Err(threaded()); + } + let holds = |t: &str| match o.replace { + "numbers" => t.bytes().any(|b| b.is_ascii_digit()), + "placeholder" => !placeholder_spans(t).is_empty(), + _ => true, + }; + // Only objects that hold a number or the placeholder count, for the order too. Threaded type + // is skipped like other type when its whole story holds none, so a placeholder split across + // two frames is still refused. + let mut kept: Vec<(NodeId, String)> = Vec::with_capacity(texts.len()); + let mut checked_threads = std::collections::HashSet::::new(); + for id in texts { + if threads.threaded(id) { + if threads.first_thread_index(id).is_some_and(|index| !checked_threads.insert(index)) { + continue; + } + let frames = threads.story(id); + let story: String = frames.iter().copied().map(plain).collect(); + if holds(&story) { + return Err(threaded()); + } + continue; + } + let t = plain(id); + if holds(&t) { + kept.push((id, t)); + } + } + let mut texts = kept; if o.order != "stacking" && o.shuffle.is_none() { let placed: Vec<(NodeId, Rect)> = texts .iter() @@ -345,11 +467,7 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { _ => vec![(0, text.len(), number.clone())], }; // The text it would have, to leave out objects that already read so. - let mut after = text.clone(); - for (a, b, n) in &changes { - after.replace_range(*a..*b, n); - } - if after != *text { + if replaced(text, &changes) != *text { plans.push((*id, changes)); } } @@ -367,11 +485,7 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { s.edit("Make Numbers Sequence", |d, sel| { for (id, changes) in &plans { let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; - for (a, b, n) in changes { - t.splice_paras(*a, *b, n); - edit::replace_range(&mut t.runs, *a, *b, n); - t.ruby_after_replace(*a, *b, n.len()); - } + apply(t, changes); refresh_bounds(t); } d.remove_many(&removed)?; diff --git a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs index e7d51d47b4..d472268049 100644 --- a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs @@ -2,9 +2,9 @@ //! orders, removed objects, one undo step, and bad params refused without a change. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{NodeId, NodeKind, TextObject, TextRun}; -use super::{COMMAND as C, Options, number_spans, placeholder_spans, sequence}; +use super::{COMMAND as C, Options, apply, edits, number_spans, placeholder_spans, sequence, text_passes}; use crate::Session; fn session() -> Session { @@ -93,6 +93,51 @@ fn threaded_type_is_refused() { assert_eq!((plain(&s, NodeId(a)), steps(&s)), ("1 2 3".to_string(), n)); } +/// Replacing numbers or placeholders skips threaded type that holds none, as it skips other type. +#[test] +fn threaded_type_with_nothing_to_replace_is_skipped() { + let mut s = session(); + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a b c", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let seat = text_at(&mut s, 40.0, 300.0, "Seat 0"); + let scans = super::threads::thread_scans(); + let builds = super::threads::story_builds(); + let out = s.execute(C, &json!({"ids": [a, b, seat.0], "replace": "numbers", "start": 4})).unwrap(); + assert_eq!(super::threads::thread_scans() - scans, 1, "one thread index"); + assert_eq!(super::threads::story_builds() - builds, 1, "selected frames of one story share its match check"); + assert_eq!(out["count"], json!(1)); + assert_eq!((plain(&s, NodeId(a)), plain(&s, seat)), ("a b c".to_string(), "Seat 4".to_string())); + let n = steps(&s); + let scans = super::threads::thread_scans(); + let builds = super::threads::story_builds(); + assert!(s.execute(C, &json!({"ids": [a, b], "replace": "placeholder"})).is_ok(), "no placeholder in the story"); + assert_eq!(super::threads::thread_scans() - scans, 1, "one thread index"); + assert_eq!(super::threads::story_builds() - builds, 1, "selected frames of one story share its match check"); + assert!(s.execute(C, &json!({"ids": [a, b]})).is_err(), "the whole text of threaded type is still refused"); + assert_eq!(steps(&s), n); +} + +/// A placeholder in a threaded story is refused even when no one frame holds all of it. +#[test] +fn threaded_type_whose_story_holds_a_placeholder_is_refused() { + let mut s = session(); + let words = format!("{} {{%n}}", "word ".repeat(40)); + let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": words, "area": {"width": 60, "height": 30}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 300, "height": 300})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let first = plain(&s, NodeId(a)); + let second = plain(&s, NodeId(b)); + assert!(!first.contains("{%n}"), "the selected frame alone has no placeholder"); + assert!((first + &second).contains("{%n}"), "the story contains the placeholder in thread order"); + let n = steps(&s); + assert!(s.execute(C, &json!({"ids": [a], "replace": "placeholder"})).is_err()); + assert_eq!(steps(&s), n); +} + #[test] fn the_spans_find_numbers_and_placeholders() { assert_eq!(number_spans("No. 12, page 3.5 of 1,000."), [(4, 6), (13, 16), (20, 25)]); @@ -335,3 +380,65 @@ fn a_run_that_changes_nothing_makes_no_step_and_bad_params_fail() { } assert_eq!((plain(&s, a), steps(&s)), ("1".to_string(), n)); } + +#[test] +fn a_long_text_is_numbered_in_a_few_passes() { + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, &"9 ".repeat(2_000)); + let before = text_passes(); + s.execute(C, &json!({"ids": [a.0], "replace": "numbers", "start": 1})).unwrap(); + let passes = text_passes() - before; + assert_eq!(plain(&s, a), "1 ".repeat(2_000)); + assert!(passes <= 4, "2,000 numbers in one object took {passes} passes over its text"); +} + +/// `t` with `changes` made one at a time, as the command made them before it made them in one pass. +fn one_at_a_time(t: &TextObject, changes: &[(usize, usize, String)]) -> TextObject { + let mut t = t.clone(); + for (a, b, n) in changes { + t.splice_paras(*a, *b, n); + vectorcraft_text::edit::replace_range(&mut t.runs, *a, *b, n); + t.ruby_after_replace(*a, *b, n.len()); + } + t +} + +#[test] +fn numbers_made_in_one_pass_keep_the_styles_and_ruby_of_one_at_a_time() { + let mut s = session(); + let id = text_at(&mut s, 40.0, 100.0, "x"); + let NodeKind::Text(base) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not text") }; + let base = base.clone(); + let style = |size: f64, glyph: Option| { + let mut st = base.first_style(); + st.size = size; + st.glyph_alternate = glyph.map(|ch| serde_json::from_value(json!({"ch": ch.to_string(), "gid": 7, "font": "F"})).unwrap()); + st + }; + let ruby = |start: usize, end: usize| serde_json::from_value(json!({"start": start, "end": end, "text": "r"})).unwrap(); + // Runs that split numbers, start at them and end inside them, with glyph choices and ruby + // over, across and between the numbers. + type Case<'a> = (Vec<(&'a str, f64, Option)>, Vec<(usize, usize)>); + let cases: Vec = vec![ + (vec![("a12 b", 10.0, None), ("34 c5", 12.0, Some('3')), ("6 -7.8 9", 14.0, None)], vec![(1, 3), (0, 6), (7, 12), (12, 14), (16, 18)]), + (vec![("1", 10.0, Some('1')), ("2", 11.0, Some('2')), (" x ", 12.0, None), ("333", 13.0, None)], vec![(0, 2), (2, 4), (5, 8)]), + (vec![("no 1, 2 or 3", 10.0, None), ("", 11.0, None), ("44", 12.0, Some('4'))], vec![(3, 4), (4, 9), (13, 14)]), + (vec![("a", 10.0, Some('a')), ("a", 10.0, Some('a')), (" 12 34", 10.0, None)], vec![(3, 5), (6, 8)]), + ]; + for (runs, spans) in cases { + let mut t = base.clone(); + t.runs = runs.iter().map(|(text, size, glyph)| TextRun { text: text.to_string(), style: style(*size, *glyph), inline: None }).collect(); + let text = t.plain_text(); + // Without ruby the runs are rebuilt in one pass; with it each change is made in turn. + for with_ruby in [false, true] { + t.ruby = if with_ruby { spans.iter().map(|(a, b)| ruby(*a, *b)).collect() } else { Vec::new() }; + for number in ["0", "123456", "5", "123"] { + let changes = edits(&text, number_spans(&text), number); + let mut fast = t.clone(); + apply(&mut fast, &changes); + let slow = one_at_a_time(&t, &changes); + assert_eq!((&fast.runs, &fast.ruby, &fast.paras), (&slow.runs, &slow.ruby, &slow.paras), "{text:?} numbered {number}"); + } + } + } +} diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 21618367b6..0601124298 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -41,10 +41,10 @@ pub use live_paint::live_paint_gaps; pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation}; use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; use shape_builder::{sb_copy_region, sb_merge, sb_regions}; -pub(crate) use trace::TracePresetChanges; pub use trace::{ TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target, }; +pub(crate) use trace::{TracePresetChanges, is_seam_fills, is_trace_group, is_trace_source}; use trace::{ trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view, }; diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index a4e2892f39..f5b3d9fa38 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -17,12 +17,17 @@ thread_local! { // ---------- Image Trace ---------- -fn is_trace_group(n: &Node) -> bool { +pub(crate) fn is_trace_group(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.name.as_deref() == Some(TRACE_NAME) && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) } +/// Whether object `id` of `d` is the source image an Image Trace object keeps as its first child. +pub(crate) fn is_trace_source(d: &Document, id: NodeId) -> bool { + d.parent_of(id).and_then(|g| d.node(g)).is_some_and(|g| is_trace_group(g) && g.children().and_then(|c| c.first()).is_some_and(|f| f.id == id)) +} + /// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]). const SEAM_FILLS_NAME: &str = "Seam Fills"; @@ -32,7 +37,7 @@ const SEAM_FILLS_NAME: &str = "Seam Fills"; /// it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) Traces made /// before the seam fills were clipped hold a group without a clip: one named as seam fills, or one /// of stroked paths without fills. (Auto Grouping groups hold filled paths.) -fn is_seam_fills(n: &Node) -> bool { +pub(crate) fn is_seam_fills(n: &Node) -> bool { let path = |m: &Arc| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); let stroke_only = |m: &Arc| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None; let fill_only = |m: &Arc| path(m) && m.appearance.fill_paint() != Paint::None && m.appearance.stroke_paint() == Paint::None; @@ -774,8 +779,12 @@ pub fn image_trace_target(s: &Session, p: &Value) -> Result { fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box)> { let roots = root_ids(s, p)?; let d = &s.doc()?.doc; + // The source image an Image Trace object keeps is traced through that object, so it is never + // the object traced, and naming only such images is an error. + let source = |r: &NodeId| is_trace_source(d, *r); roots .iter() + .filter(|r| !source(r)) .find_map(|r| { let n = d.node(*r)?; match &n.kind { @@ -787,7 +796,10 @@ fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box None, } }) - .ok_or_else(|| bad(c, "select an image (or an Image Trace group)")) + .ok_or_else(|| match roots.iter().find(|r| source(r)) { + Some(r) => bad(c, format!("object {} is the source image of an Image Trace object: trace that object", r.0)), + None => bad(c, "select an image (or an Image Trace group)"), + }) } /// What command `c` with params `p` traces, and how, from the session: everything but the trace. @@ -1076,10 +1088,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result traced, - _ => trace_now(&inputs, &trace, &|_, _| true)?, + _ => trace_now(&inputs, &trace, &|_, _| stop.as_ref().is_none_or(|i| !i.is_set()))?, }; let TraceInputs { target, image: img, .. } = inputs; let mut warnings = keep_warnings(&trace, &res); @@ -1098,6 +1112,11 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result Result Result { n.name = None; n.extras_mut().trace = None; if let Some(ch) = n.children_mut() { - ch.retain(|c| !matches!(c.kind, NodeKind::Image(_))); + let source = ch.first().map(|c| c.id); + ch.retain(|c| Some(c.id) != source); } if by_color { let items = d.node(*g).and_then(Node::children).cloned().unwrap_or_default(); diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 20cb4c96ab..28a9fbaaa9 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -23,7 +23,7 @@ use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, Node use vectorcraft_geom::{PathData, Rect}; pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; -pub use flavours::{ImageRead, read_image}; +pub use flavours::{ImageRead, read_image, read_pixels}; pub(crate) use resources::SwatchChoices; pub use resources::{ArtResources, SymbolOptions, art_resources}; @@ -320,17 +320,8 @@ impl Clipboard { if let Some(bounds) = gradient_box { piece.appearance.pin_gradients(bounds); } - piece.opacity = parent.opacity; - piece.blend = parent.blend; - piece.isolate = parent.isolate; - piece.knockout = parent.knockout; - piece.knockout_shape = parent.knockout_shape; - let (mask, pixel_aligned) = (parent.extras().mask.clone(), parent.extras().pixel_aligned); - { - let mut extras = piece.extras_mut(); - extras.mask = mask; - extras.pixel_aligned = pixel_aligned; - } + super::object::copy_transparency(&mut piece, parent); + piece.extras_mut().pixel_aligned = parent.extras().pixel_aligned; let link = parent .extras() .graphic_style diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 680e2902c8..80e31e849e 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -385,6 +385,16 @@ impl Session { self.prefs.copy_as_svg && !self.clipboard_svg_refused() } + /// After a Copy or Cut has filled the clipboard: counts it in [`Session::copies`] when it put + /// something there, and marks the clipboard as holding a copy ([`Session::clipboard_copied`]). + pub(crate) fn note_copy(&mut self) { + let filled = !self.clipboard.is_empty(); + if filled { + self.copies = self.copies.wrapping_add(1); + } + self.clipboard_copied = filled; + } + /// Replace the clipboard with `clip`, centred on `p`'s `center` (default: the first /// artboard's centre) → the number of objects. pub(super) fn load_clipboard(&mut self, mut clip: Clipboard, p: &Value) -> Result { @@ -400,6 +410,7 @@ impl Session { } let count = clip.nodes.len(); self.clipboard = clip; + self.clipboard_copied = false; Ok(count) } } @@ -450,6 +461,20 @@ pub fn read_image(bytes: &[u8]) -> Result { Ok(ImageRead(img)) } +/// [`read_image`] for a bitmap another app put on the clipboard as decoded pixels, on any thread: +/// the pixels are encoded once as the PNG the document keeps, and kept as the decoded image the +/// renderers share, so neither this read nor the first frame that draws the image decodes them. +/// When the renderers' store refuses the pixels (over its budget, or no room beside the images +/// being drawn), they are dropped, and the renderers decode the PNG as they decode any other image, +/// under the same memory limits. An error when the image is empty or too large to draw. +pub fn read_pixels(img: image::RgbaImage) -> Result { + let img = image::DynamicImage::ImageRgba8(img); + let read = fileio::pixels_png(&img).map_err(|e| bad("clipboard.importImage", e.to_string()))?; + // Refused pixels are not held anywhere else, so the store's budget stays the only one. + let _kept = vectorcraft_render::keep_decoded_image(&read.blob, img); + Ok(ImageRead(read)) +} + impl Session { /// `clipboard.importImage` with `p` (its `mime` and `center`) for an image [`read_image`] read /// (off the UI thread in the desktop app), which it loads instead of reading `dataBase64`. diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 1ed09da2ee..2a87e7e53c 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -1521,6 +1521,13 @@ fn store_view(s: &mut Session, v: proof::ProofView) { } } +/// Turn Overprint Preview on, as `view.overprintPreview` with `on` true does. +pub(crate) fn turn_on_overprint_preview(s: &mut Session) { + let mut v = proof::view(); + v.overprint = true; + store_view(s, v); +} + fn toggle_view(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut proof::ProofView, Option)) -> Result { let on = on_param(p, "on", cmd)?; let mut v = proof::view(); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 16ceda7d38..083cfa65d9 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -12,6 +12,25 @@ use super::{ }; use crate::EngineError; +pub(crate) fn on_layer(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if p.get("onLayer").is_none() { + return run(s); + } + let parent = object_param(p, "onLayer", cmd)?; + let d = &s.doc()?.doc; + if let Some(id) = parent + && !d.node(id).is_some_and(|n| n.is_layer() && d.is_editable(id)) + { + return Err(bad(cmd, "onLayer must name an editable layer")); + } + let mode = std::mem::replace(&mut s.draw_mode, crate::DrawMode::Normal); + let isolation = std::mem::replace(&mut s.doc_mut()?.isolation, parent); + let result = run(s); + s.doc_mut()?.isolation = isolation; + s.draw_mode = mode; + result +} + pub fn specs() -> Vec { vec![ cmd!( @@ -19,7 +38,7 @@ pub fn specs() -> Vec { "Rectangle", [], None, - "{x, y, width, height, radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, rectangle ), @@ -28,7 +47,7 @@ pub fn specs() -> Vec { "Ellipse", [], None, - "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", has_doc, ellipse ), @@ -37,7 +56,7 @@ pub fn specs() -> Vec { "Polygon", [], None, - "{cx, cy, radius, sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", + "{cx, cy, radius, onLayer?: layer id|null (draw normally on this layer), sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", has_doc, polygon ), @@ -46,7 +65,7 @@ pub fn specs() -> Vec { "Star", [], None, - "{cx, cy, radius1, radius2, points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", + "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", has_doc, star ), @@ -137,7 +156,7 @@ pub fn specs() -> Vec { "Create Path", [], None, - "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], closed?: bool, d?: SVG path data} → {id}", + "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], onLayer?: layer id|null (draw normally on this layer), closed?: bool, d?: SVG path data} → {id}", has_doc, path_create ), @@ -155,7 +174,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -956,7 +975,38 @@ fn path_create(s: &mut Session, p: &Value) -> Result { add_look(s, "Pen", path_kind(path, None), look, None) } +/// The shown, unlocked layer or group `text.create`'s `parent` names, if it names one. +fn text_parent(s: &Session, p: &Value) -> Result> { + const C: &str = "text.create"; + let Some(parent) = object_param(p, "parent", C)? else { return Ok(None) }; + let d = &s.doc()?.doc; + let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) }; + if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() { + return Err(bad(C, format!("{} is not a layer or group", parent.0))); + } + if !d.is_editable(parent) { + return Err(bad(C, "the layer or group is hidden or locked")); + } + Ok(Some(parent)) +} + +/// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected. +fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result { + let id = s.edit("Type", |d, sel| { + let id = d.alloc_id(); + let mut n = Node::new(id, kind); + NewArt::plain(Appearance::default()).apply(d, &mut n); + super::object::align_new_object(d, &mut n); + n.bbox_angle = bbox_angle; + d.insert(Some(parent), usize::MAX, n)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + fn text_create(s: &mut Session, p: &Value) -> Result { + let parent = text_parent(s, p)?; let x = f64_req(p, "x", "text.create")?; let y = f64_req(p, "y", "text.create")?; super::paint::check_keep_model(p, "text.create")?; @@ -993,8 +1043,12 @@ fn text_create(s: &mut Session, p: &Value) -> Result { // Lays the text out (and sizes an Auto Size frame). super::typecmd::refresh_bounds(&mut t); } - let made = - insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?; + let made = match parent { + Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?, + None => { + insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)? + } + }; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index d9b6e25b96..55726c31c9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones; an unknown category, or one without preset, is an error), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), @@ -234,7 +234,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected", + "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); a clipping group or layer left without art releases its mask in the same undo step; without ids, refused while an object of a symbol instance's art is selected", has_selection_or_guides, clear ), @@ -1221,6 +1221,7 @@ fn copy(s: &mut Session, p: &Value) -> Result { } clip.guides = guides; s.clipboard = clip; + s.note_copy(); Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() })) } @@ -1311,6 +1312,20 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { ok() } +pub(super) fn clipped_ancestors(d: &Document, ids: impl IntoIterator) -> BTreeSet { + ids.into_iter().flat_map(|id| d.ancestry(id).unwrap_or_default()).filter(|id| d.node(*id).is_some_and(Node::clips)).collect() +} + +pub(super) fn release_empty_clips(d: &mut Document, ids: BTreeSet) { + for id in ids { + if let Some(n) = d.node_mut(id) + && n.children().is_some_and(|c| c.iter().all(|n| n.is_ruler_guide())) + { + n.set_clips(false); + } + } +} + fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?; @@ -1347,6 +1362,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Clear", |d, sel| { + let clipped = clipped_ancestors(d, ids.iter().copied()); let parents: Vec<_> = if keep_empty { Vec::new() } else { @@ -1362,6 +1378,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { let gone = sel.guides.clone(); d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); } + release_empty_clips(d, clipped); if is_explicit { sel.remove_all(ids.iter().copied()); sel.prune(d); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index e5463f6c44..60a7aaba29 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -5,6 +5,7 @@ //! own stacks, groups and layers included (layers through `ids`), or with `target: "contents"` //! the objects inside them (see `appearance`). +use std::collections::HashSet; use std::sync::Arc; use serde_json::{Value, json}; @@ -115,7 +116,7 @@ fn effect_specs() -> Vec { "Move Effect", [], None, - "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", + "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (different appearances allow only a reorder within the same shared fill or stroke, or within identical object effect lists; a graph design's art given first still requires equal appearances)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", has_doc, move_effect ), @@ -481,6 +482,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { super::params::check_effect_color(C, id, ¶ms)?; super::params::check_effect_channel(C, id, ¶ms)?; super::params::check_effect_center(C, id, ¶ms)?; + super::params::check_effect_halftone_style(C, id, ¶ms)?; super::params::check_effect_pathfinder(C, id, ¶ms)?; // Crop Marks take their style from the preferences when applied. if id == effects::CROP_MARKS && params.get("style").is_none() { @@ -677,6 +679,35 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&ids) })) } +impl Session { + /// Can the Appearance panel reorder shared effects on the exact subjects it displays? + /// A generated graph design or a selection normalized to different objects has no matching row. + pub fn can_reorder_selected_effects(&self) -> bool { + let Ok(st) = self.doc() else { return false }; + let Ok(roots) = edit_targets(self, &Value::Null, "effect.move") else { return false }; + let selected: HashSet<_> = st.selection.subjects().iter().copied().collect(); + roots.len() == selected.len() && roots.iter().all(|id| selected.contains(id) && st.doc.is_editable(*id)) + } +} + +/// Resolves a same-list reorder for objects whose appearances differ. Every object must share the +/// complete ordered object effect list or the same fill/stroke row, with its effects, before editing. +fn shared_reorder_slots(d: &Document, ids: &[NodeId], source: ItemTarget, anchor: usize) -> Option>> { + let mut seen = HashSet::with_capacity(ids.len()); + let mut appearances: Vec<&vectorcraft_doc::Appearance> = + ids.iter().map(|id| d.node(*id).filter(|_| seen.insert(*id) && d.is_editable(*id)).map(|n| &*n.appearance)).collect::>()?; + let first = *appearances.get(anchor)?; + if source == ItemTarget::Top { + return appearances.iter().all(|ap| ap.effects == first.effects).then(|| vec![None; appearances.len()]); + } + let item = source.effects_item(first, "effect.move").ok()??; + appearances.swap(0, anchor); + let shared = SharedStack::of(&appearances); + let mut slots = (0..appearances.len()).map(|k| shared.item_in(item, k).map(Some)).collect::>>()?; + slots.swap(0, anchor); + Some(slots) +} + /// `effect.move`: moves (with `copy`: copies) effect `from`, or the effects `from` lists as one block in their order, to `to` in its own list or in `toItem`'s. fn move_effect(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.move"; @@ -693,17 +724,30 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src }; let copy = switch_or(p, "copy", false, C)?; let roots = edit_targets(s, p, C)?; - // Where an aligned effect would go in each of several different stacks isn't one place. - if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &roots)) { - return Err(bad(C, "effects of objects whose appearances differ can't be moved together")); - } + let reference = design_reference(s, p, C)?; + let d = &s.doc()?.doc; + let slots = if aligned(p, C)? && super::appearance::appearances_differ(d, &with_reference(reference, &roots)) { + // An omitted item and a numbered item can use different anchors and still name the same row. + let shared = (!copy && reference.is_none()) + .then(|| { + shared_reorder_slots(d, &roots, src, src.anchor(s, &roots)) + .filter(|source| src == dst || shared_reorder_slots(d, &roots, dst, dst.anchor(s, &roots)).as_ref() == Some(source)) + }) + .flatten(); + Some(shared.ok_or_else(|| bad(C, "effects of objects whose appearances differ can't be moved together"))?) + } else { + None + }; // Where the effect landed in each object it moved in, in the order of `ids`. let mut landed = vec![]; let ids = s.edit(if copy { "Duplicate Effect" } else { "Move Effect" }, |d, _| { let mut done = vec![]; - for id in &roots { + for (k, id) in roots.iter().enumerate() { let Some(n) = d.node_mut(*id) else { continue }; - let (si, di) = (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?); + let (si, di) = match &slots { + Some(slots) => (slots[k], slots[k]), + None => (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?), + }; let Some(fx) = n.appearance.effects_mut(si).filter(|fx| from.iter().all(|i| *i < fx.len())) else { continue }; // Taken out from the top down, so the lower positions stay valid; put back in order. let mut taken: Vec = from.iter().rev().filter_map(|&i| if copy { fx.get(i).cloned() } else { Some(fx.remove(i)) }).collect(); @@ -826,6 +870,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { super::params::check_effect_color(C, effect, ¶ms)?; super::params::check_effect_channel(C, effect, ¶ms)?; super::params::check_effect_center(C, effect, ¶ms)?; + super::params::check_effect_halftone_style(C, effect, ¶ms)?; super::params::check_effect_pathfinder(C, effect, ¶ms)?; } if edited.iter().any(|e| texture_load_effect(e)) { 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 122bbff3c3..fc6fc47756 100644 --- a/crates/engine/src/cmd/effectcmd/three_d_type_tests.rs +++ b/crates/engine/src/cmd/effectcmd/three_d_type_tests.rs @@ -90,6 +90,16 @@ fn three_d_type_carries_depth_between_extrude_and_inflate_and_merges_params_afte assert!(params.get("bevel").is_none()); } +#[test] +fn the_material_survives_a_type_change() { + let material = json!({"roughness": 0.3, "metallic": 0.6}); + let (mut s, id) = setup("threeD.extrude", json!({"material": material})); + for kind in ["inflate", "revolve", "plane"] { + s.execute("effect.setParams", &json!({"index": 0, "item": null, "threeDType": kind})).unwrap(); + assert_eq!(effect(&s, id).1["material"], material, "{kind}"); + } +} + #[test] fn revolve_angles_outside_half_a_turn_wrap_when_the_type_leaves_revolve() { let (mut s, id) = setup("threeD.revolve", json!({"rotationX": 270.0, "rotationY": -200.0})); diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 38654bb8ba..52871e23fa 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -44,7 +44,7 @@ pub mod jxlread; mod legacy_ai; mod load; mod mesh3d; -pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, preview_with_clip, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, pixels_png, preview_with_clip, size_note}; mod heifread; pub mod hpgl; mod jp2read; @@ -87,6 +87,7 @@ pub(crate) use load::decode_native_file; use load::err; pub(crate) use load::import_svg; pub(crate) use load::is_placeholder; +pub(crate) use load::is_raster_image; pub(crate) use load::page_or_editing_data; pub(crate) use load::source; pub use load::{ @@ -146,6 +147,8 @@ mod commands; mod export_names; mod formats; +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) use access::FILES_READ; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 0edfc53c54..0a4cf89b18 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -265,6 +265,17 @@ pub(crate) fn may_write(path: &str) -> Result<()> { crate::file_access::check_write(path).map_err(EngineError::Other) } +/// [`may_write`], and an error when something other than a regular file is at `path` (a folder): +/// the check each file of a set gets before the first of them is written. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn may_write_file(path: &str) -> Result<()> { + may_write(path)?; + match std::fs::metadata(path) { + Ok(m) if !m.is_file() => Err(EngineError::Other(format!("{path}: not a file"))), + _ => Ok(()), + } +} + /// The most a file read during a script command holds, the limit an importer reads. #[cfg(not(target_arch = "wasm32"))] pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX_INPUT_BYTES; @@ -272,10 +283,18 @@ pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX #[cfg(not(target_arch = "wasm32"))] pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB"; +#[cfg(all(test, not(target_arch = "wasm32")))] +thread_local! { + /// The paths [`read_file`] has read on this thread, in order. + pub(crate) static FILES_READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_file(path: &str) -> Result> { use std::io::Read; may_read(path)?; + #[cfg(test)] + FILES_READ.with(|r| r.borrow_mut().push(path.to_string())); // A device or pipe may never end: only a regular file is read to its end. if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() { return Err(EngineError::Other(format!("{path}: not a file"))); diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index aa3be78e2a..9beed7e8a2 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -872,6 +872,7 @@ mod tests { ("source", json!(1), "`source` must be a string"), ("source", json!("files"), "`source` must be `folder` or `datasets`"), ("destination", json!(true), "`destination` must be a string"), + ("destination", json!("nowhere"), "`destination` must be `none`, `saveAndClose` or `folder`"), ("folder", json!(5), "`folder` must be a string"), ("label", json!(5), "`label` must be a string"), ("datasetFileNaming", json!(3), "`datasetFileNaming` must be a string"), @@ -895,6 +896,17 @@ mod tests { .to_string(); assert!(e.contains("`destinationFolder` must be a string"), "{e}"); assert!(s.active().is_none(), "no file was opened"); + // Saving to a folder needs the folder. + let e = s + .execute( + "action.batch", + &json!({"folder": src.to_string_lossy(), "destination": "folder", "commands": [{"command": "object.unlockAll"}]}), + ) + .unwrap_err() + .to_string(); + assert!(e.contains("`destinationFolder` is required when destination is `folder`"), "{e}"); + assert!(s.active().is_none(), "no file was opened"); + assert_eq!(std::fs::read_dir(&src).unwrap().count(), 1, "nothing was written next to the source file"); } #[cfg(unix)] diff --git a/crates/engine/src/cmd/fileio/affinity/nodes.rs b/crates/engine/src/cmd/fileio/affinity/nodes.rs index 36734dbe39..a6961c28c2 100644 --- a/crates/engine/src/cmd/fileio/affinity/nodes.rs +++ b/crates/engine/src/cmd/fileio/affinity/nodes.rs @@ -288,4 +288,33 @@ mod tests { assert!(!path_in_range(&path(&[(0.0, 0.0), (f64::NAN, 0.0)]), k)); assert!(!path_in_range(&path(&[(0.0, 0.0), (1.0, 1.0)]), Affine::scale(1.0e9))); } + + fn blended(blend: Blend) -> af::Node { + af::Node { + class: vectorcraft_affinity::stream::Tag::of(b"GrpN"), + name: String::new(), + visible: true, + locked: false, + opacity: 1.0, + blend, + kind: Kind::Group, + mask: None, + pixel_mask: None, + effects: vec![], + children: vec![], + } + } + + /// A blend mode VectorCraft has keeps it; one it lacks imports as Normal with one warning. + #[test] + fn blend_modes_map_or_import_as_normal_with_a_warning() { + let group = || NodeKind::Group { children: vec![], clip: false }; + let mut b = Builder::new(1.0); + assert_eq!(b.base(&blended(Blend::Multiply), group()).blend, BlendMode::Multiply); + assert!(b.warnings.is_empty(), "{:?}", b.warnings); + for _ in 0..2 { + assert_eq!(b.base(&blended(Blend::LinearLight), group()).blend, BlendMode::Normal); + } + assert!(b.warnings.len() == 1 && b.warnings[0].contains("Linear Light"), "{:?}", b.warnings); + } } diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 93670cefd9..dcb26b94b5 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -18,13 +18,19 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // A drag or typing still in progress is a step of its own, as before Undo: the batch's steps // would otherwise run inside it and take its baseline as theirs (#1697). if s.active().is_some() && !s.previewing { + let open = s.holds_interaction() || s.docs.iter().any(|d| d.interaction.is_some()); super::super::edit::settle_interaction(s)?; + s.plugin_events_batch_settled(open); } let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); + let (clipboard_copied, copies) = (s.clipboard_copied, s.copies); // The documents as they are now, whole: what a failed step brings back. Their art, history, // file, format and saved state share their data with the open ones until a step changes them. let start = s.docs.clone(); let active = s.active; + // A rollback puts back the swatch renames recorded before the batch, including any its steps pushed out of the record. + let swatch_renames = s.swatch_renames.clone(); + let opens = s.plugin_events_mark(); s.batch_stash = Some(vec![]); let mut grouped = Vec::with_capacity(cmds.len()); // The Type tool keeps what the steps' Undo and Redo change in it, to put back on a rollback. @@ -38,11 +44,15 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { results } Err(e) => { + s.swatch_renames = swatch_renames; roll_back(s, start, &stash); + // The documents the steps opened are closed again: plug-ins are not told of them. + s.forget_plugin_opens_since(opens); s.notify_text_tool("batch.rollBack"); s.active = active; s.sync_front_profiles(); (s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved; + (s.clipboard_copied, s.copies) = (clipboard_copied, copies); s.pending_paint = None; return Err(e); } diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index e902f4185a..bddd245b71 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index a79ac295e5..96e5d2210f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1210,12 +1210,29 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { vectorcraft_doc::cancel::progress(done as u64, total, &format!("Rendering artboard {} of {total}", done + 1)); let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect; // `width` or `height`: each file gets the scale that makes its region that size. - if let Some(size) = size { - settings.ppi = clamped_ppi(72.0 * size.scale_for(C, region)?); + let requested_scale = size.map(|size| size.scale_for(C, region)).transpose()?; + if let Some(scale) = requested_scale { + settings.ppi = clamped_ppi(72.0 * scale); } let scale = settings.scale(); check_format_size(f, region.width() * scale, region.height() * scale)?; - vectorcraft_render::raster_size(region, scale).map_err(|e| bad(C, e))?; + let (width, height) = vectorcraft_render::raster_size(region, scale).map_err(|e| bad(C, e))?; + if let Some(requested_scale) = requested_scale.filter(|scale| !(0.01..=64.0).contains(scale)) { + let dimension = match size { + Some(ScreenSize::Width(requested)) => Some(("width", requested, width, "wide")), + Some(ScreenSize::Height(requested)) => Some(("height", requested, height, "high")), + _ => None, + }; + if let Some((axis, requested, written, direction)) = dimension + && f64::from(written) != requested + { + let limit = if requested_scale > 64.0 { "more than 64" } else { "less than 0.01" }; + enc.add_setting_notes([format!( + "{axis} {requested} px needs {limit} pixels per point: artboard {} was written {written} px {direction}", + b + 1 + )]); + } + } enc.maps.extend(imagemap::build(doc, region, scale, map, enc.files.len())); let bytes = renderer.export_region(doc, region, format, &settings).map_err(EngineError::Other)?; // File Info as PNG text chunks. diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 48a8c828ab..19c754be4b 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -87,7 +87,10 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 { for (p, _) in &files { - super::may_write(p)?; + super::access::may_write_file(p)?; + if std::fs::metadata(p).is_ok_and(|meta| meta.permissions().readonly()) { + return Err(super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied))); + } } } for (p, bytes) in &files { diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index cce50485dd..53cac16bee 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1060,7 +1060,8 @@ fn open_loaded( st.import_losses = losses; st.links_from = read_from; let opened = &s.documents()[index]; - let (title, file_info_title) = (opened.title(), opened.doc.info_title().to_string()); + let (title, file_info_title, uid) = (opened.title(), opened.doc.info_title().to_string(), opened.uid); + s.note_plugin_event(vectorcraft_plugins::Event::DocumentOpened, uid); Ok(super::merge( json!({ "index": index, "title": title, "fileInfoTitle": file_info_title, "format": format.id, "warnings": warnings, "restored": restored }), links.to_json(), @@ -1159,6 +1160,20 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { (drawn != (w, h)).then(|| format!("an image of {w} × {h} pixels is shown at reduced size")) } +/// Whether `bytes` start as a file in a format [`raster_image`] reads, whether or not the rest of +/// it can be decoded. +pub(crate) fn is_raster_image(bytes: &[u8]) -> bool { + super::pcraftread::is_pcraft(bytes) + || psdread::is_psd(bytes) + || jxlread::is_jxl(bytes) + || super::jp2read::is_jpeg2000(bytes) + || super::heifread::is_heif(bytes) + || super::pxrread::is_pxr(bytes) + || craft_image_codecs::detect(bytes).is_some() + || super::tgaread::is_targa(bytes) + || super::pcxread::is_pcx(bytes) +} + /// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as /// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per /// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]); @@ -1337,6 +1352,18 @@ pub(super) fn as_png(img: impl Into, icc: Option>, stored(png, "image/png", size, ppi) } +/// Decoded pixels `img` stored as a PNG, without a resolution or an ICC profile. An image whose +/// pixels as RGBA need more than [`MAX_RASTER_ALLOC`] is refused as too large to draw. +pub(crate) fn pixels_png(img: &image::DynamicImage) -> Result { + let (w, h) = (img.width(), img.height()); + if u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC { + return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); + } + let mut png = Vec::new(); + img.write_with_encoder(image::codecs::png::PngEncoder::new(&mut png)).map_err(err)?; + stored(png, "image/png", (w, h), None) +} + /// Effect › Distort › Glass › Load Texture…: encoded image `bytes`, in any format [`raster_image`] /// reads, as the `textureImage` Glass stores ([`LoadedTexture::to_stored`]). The pixels are decoded /// within [`MAX_RASTER_ALLOC`], counted as RGBA, as the renderer decodes them (#1717); a CMYK image diff --git a/crates/engine/src/cmd/fileio/mesh3d.rs b/crates/engine/src/cmd/fileio/mesh3d.rs index 205a3cec35..e30cd8750a 100644 --- a/crates/engine/src/cmd/fileio/mesh3d.rs +++ b/crates/engine/src/cmd/fileio/mesh3d.rs @@ -3,7 +3,8 @@ //! USDZ (the USDA layer in an uncompressed ZIP, its data on a 64-byte boundary). //! //! Each solid of the object ([`vectorcraft_render::effects::three_d_meshes`]) is its own mesh, with a -//! material in the color it is painted (solids of one color share it). Positions are y up and +//! material in the color it is painted. Parts of one color and picture share a material; glTF and +//! USD also distinguish Roughness and Metallic, which OBJ's MTL omits. Positions are y up and //! about the point the object turns about: in points in OBJ and USD (whose layer says how many //! meters a unit is), in meters in glTF, as its specification asks. glTF and USD colors are linear, //! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since @@ -200,23 +201,32 @@ fn check_parts(parts: &[SolidMesh]) -> Result<(), String> { parts.iter().try_for_each(|p| p.mesh.check()) } -/// A material: a color, with a picture that replaces its red, green and blue. +/// A material: a color, with a picture that replaces its red, green and blue, and the surface's +/// Roughness and Metallic, written by glTF and USD and omitted by OBJ's MTL. #[derive(Clone, Copy, PartialEq)] struct Material { color: [f32; 4], image: Option, + roughness: f64, + metallic: f64, } -/// The distinct materials of `scene`'s parts in order, and each part's index among them. -fn materials(scene: &Scene) -> (Vec, Vec) { +/// The distinct materials of `scene`'s parts in order, and each part's index among them. With +/// `with_factors`, Roughness and Metallic distinguish materials; otherwise only color and picture do. +fn materials(scene: &Scene, with_factors: bool) -> (Vec, Vec) { let mut out: Vec = vec![]; let index = scene .parts .iter() .enumerate() .map(|(k, p)| { - let m = Material { color: p.color, image: scene.texture(k).map(|(_, i)| i) }; - out.iter().position(|c| *c == m).unwrap_or_else(|| { + let m = Material { + color: p.color, + image: scene.texture(k).map(|(_, i)| i), + roughness: p.material.roughness(), + metallic: p.material.metallic(), + }; + out.iter().position(|c| c.color == m.color && c.image == m.image && (!with_factors || *c == m)).unwrap_or_else(|| { out.push(m); out.len() - 1 }) @@ -237,7 +247,7 @@ fn num(v: f64) -> String { fn obj(stem: &str, scene: &Scene) -> (String, String) { let parts = scene.parts; - let (materials, material) = materials(scene); + let (materials, material) = materials(scene, false); let mut o = String::new(); let _ = writeln!(o, "mtllib {stem}.mtl"); let _ = writeln!(o, "o {stem}"); @@ -303,7 +313,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) { fn gltf(stem: &str, scene: &Scene) -> String { let parts = scene.parts; - let (materials, material) = materials(scene); + let (materials, material) = materials(scene, true); let mut buffer: Vec = vec![]; let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]); let mut view = |buffer: &mut Vec, bytes: Vec, target: u32| -> usize { @@ -348,8 +358,8 @@ fn gltf(stem: &str, scene: &Scene) -> String { "name": format!("Material_{}", k + 1), "pbrMetallicRoughness": { "baseColorFactor": [linear(c[0]), linear(c[1]), linear(c[2]), c[3]], - "metallicFactor": 0.0, - "roughnessFactor": 1.0, + "metallicFactor": mat.metallic, + "roughnessFactor": mat.roughness, }, "doubleSided": true, }); @@ -400,7 +410,7 @@ fn prim_name(name: &str) -> String { fn usda(stem: &str, scene: &Scene) -> String { let parts = scene.parts; - let (materials, material) = materials(scene); + let (materials, material) = materials(scene, true); let root = prim_name(stem); let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2])); let list = |items: Vec| items.join(", "); @@ -462,7 +472,11 @@ fn usda(stem: &str, scene: &Scene) -> String { let _ = writeln!(u, " float inputs:opacity = {}", c[3]); } } - let _ = writeln!(u, " float inputs:roughness = 1"); + // UsdPreviewSurface's metallic is 0 when it is not written. + if mat.metallic != 0.0 { + let _ = writeln!(u, " float inputs:metallic = {}", num(mat.metallic)); + } + let _ = writeln!(u, " float inputs:roughness = {}", num(mat.roughness)); let _ = writeln!(u, " token outputs:surface\n }}"); if let Some(i) = mat.image { let _ = writeln!(u, "\n def Shader \"Texture\"\n {{"); diff --git a/crates/engine/src/cmd/fileio/mesh3d/tests.rs b/crates/engine/src/cmd/fileio/mesh3d/tests.rs index f87625d9fe..c2bf782d8f 100644 --- a/crates/engine/src/cmd/fileio/mesh3d/tests.rs +++ b/crates/engine/src/cmd/fileio/mesh3d/tests.rs @@ -283,3 +283,38 @@ fn parts_sharing_a_picture_write_it_once() { assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]); assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png"); } + +/// A part in `roughness` and `metallic`. +fn shiny(color: [f32; 4], roughness: f64, metallic: f64) -> SolidMesh { + let Some(material) = vectorcraft_three_d::Material::new(roughness, metallic) else { panic!("material") }; + SolidMesh { material, ..square(color) } +} + +#[test] +fn gltf_and_usda_write_each_parts_roughness_and_metallic() { + let parts = [square(RED), shiny(RED, 0.25, 0.75)]; + let g: Value = serde_json::from_str(&text(&plain_files("Box", "gltf", &parts).unwrap(), "Box.gltf")).unwrap(); + let pbr = |k: usize| { + (g["materials"][k]["pbrMetallicRoughness"]["roughnessFactor"].as_f64(), g["materials"][k]["pbrMetallicRoughness"]["metallicFactor"].as_f64()) + }; + assert_eq!(g["materials"].as_array().map(Vec::len), Some(2), "one red material per surface"); + assert_eq!((pbr(0), pbr(1)), ((Some(1.0), Some(0.0)), (Some(0.25), Some(0.75)))); + let u = text(&plain_files("Box", "usda", &parts).unwrap(), "Box.usda"); + assert_eq!(u.matches("float inputs:roughness = 1\n").count(), 1, "{u}"); + assert_eq!(u.matches("float inputs:roughness = 0.25\n").count(), 1, "{u}"); + assert_eq!(u.matches("float inputs:metallic = 0.75\n").count(), 1, "the default material writes no metallic: {u}"); + // OBJ's materials carry no factors; both red parts share one material. + let files = plain_files("Box", "obj", &parts).unwrap(); + assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 1); + let o = text(&files, "Box.obj"); + assert_eq!(o.lines().filter(|line| line.starts_with("usemtl ")).collect::>(), ["usemtl Material_1", "usemtl Material_1"]); +} + +/// Parts in the default material write what they wrote before materials existed. +#[test] +fn the_default_material_writes_the_earlier_factors() { + let g = text(&plain_files("Box", "gltf", &[square(RED)]).unwrap(), "Box.gltf"); + assert!(g.contains("\"metallicFactor\": 0.0,") && g.contains("\"roughnessFactor\": 1.0\n"), "{g}"); + let u = text(&plain_files("Box", "usda", &[square(RED)]).unwrap(), "Box.usda"); + assert!(u.contains(" float inputs:roughness = 1\n") && !u.contains("inputs:metallic"), "{u}"); +} diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index af84199414..8878456b5c 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,8 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + /// The client did not give the path: a file the file access refuses before anything is + /// written is named as [`super::access::naming_in_error`] names it ([`SaveJob::naming_refusals`]). redact_paths: bool, } @@ -972,6 +974,14 @@ impl SaveJob { &self.plan } + /// The job for a save whose path the client did not give: a file the file access refuses + /// before anything is written is named in the error as the request being served may see it + /// ([`super::access::naming_in_error`]). + pub(crate) fn naming_refusals(mut self) -> Self { + self.redact_paths = true; + self + } + /// The document when the job was made (what counts as saved once the file is written). pub(crate) fn snapshot(&self) -> &Arc { &self.snapshot @@ -1072,17 +1082,33 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file is not handed to `write`, so a writer that does not check the - // file access writes none of the files; the error is the file access's own refusal, as - // the writers that check it give. + // written. A refused file, or a folder at a file's path, is not handed to `write`, so a + // writer that does not check the file access writes none of the files; the error is the + // file access's own refusal, as the writers that check it give. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some(refused) = files - .iter() - .find_map(|(p, _)| super::may_write(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e })) + && let Some(refused) = files.iter().find_map(|(p, _)| { + super::access::may_write_file(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e }) + }) { return Err(refused); } + // An existing destination that is a folder or a read-only file is refused before any file + // is written too. + #[cfg(not(target_arch = "wasm32"))] + if files.len() > 1 { + for (p, _) in &files { + let Ok(meta) = std::fs::metadata(p) else { continue }; + let refused = if meta.is_dir() { + crate::EngineError::Other(format!("{p}: is a folder, not a file")) + } else if meta.is_file() && meta.permissions().readonly() { + super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } else { + continue; + }; + return Err(if self.redact_paths { super::access::naming_in_error(refused, p) } else { refused }); + } + } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { write(p, bytes)?; @@ -1219,6 +1245,8 @@ impl SaveJob { } if saved { crate::cmd::recovery::forget(s, uid); + // Also when the document closed while its file was being written. + s.note_plugin_event(vectorcraft_plugins::Event::DocumentSaved, uid); } if let Some(path) = written { if native { @@ -1243,10 +1271,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let mut job = save_job(s, plan)?; - let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); - job.redact_paths = !given; + let job = save_job(s, plan)?; + let job = if given { job } else { job.naming_refusals() }; + let uid = s.doc()?.uid; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) @@ -1388,7 +1416,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when access to one of a save's files is refused, or it is a directory or an existing read-only file, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 7a6547890f..5369b34398 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -47,7 +47,12 @@ pub const OPTIONS: &[FormatOption] = &[ default: "\"layerNames\"", description: "layerNames (readable ids from names) | minimal (only referenced ids) | unique (content-hashed prefix on every id and class)", }, - FormatOption { name: "decimals", ty: "integer", default: "3", description: "coordinate precision, 1–7 decimal places" }, + FormatOption { + name: "decimals", + ty: "integer", + default: "3", + description: "coordinate precision, 1–7 decimal places; positive root width/height and viewBox size stay positive", + }, FormatOption { name: "minify", ty: "boolean", default: "false", description: "no XML declaration, indentation or line breaks" }, FormatOption { name: "responsive", ty: "boolean", default: "false", description: "no width/height: the SVG scales to its container" }, FormatOption { diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index cec025b69a..ed0034b99e 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -1040,6 +1040,31 @@ fn a_save_canceled_after_its_first_file_writes_them_all() { let _ = std::fs::remove_dir_all(&d); } +/// A save that writes several files, through a writer that does not check the file access in +/// force, writes none of them when that access refuses one: the save refuses it itself. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_save_of_several_files_refused_by_the_file_access_writes_none_through_any_writer() { + let d = tmp_dir("refused-files"); + let mut s = session(100.0, 100.0, 2); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + let path = d.join("logo.eps").to_string_lossy().to_string(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let mut written = vec![]; + let r = crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || { + job.write(|p, b| { + std::fs::write(p, b).map_err(|e| EngineError::Other(e.to_string()))?; + written.push(p.to_string()); + Ok(()) + }) + }); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("write authority is absent")), "{r:?}"); + assert!(written.is_empty(), "{written:?}"); + assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0, "nothing written"); + let _ = std::fs::remove_dir_all(&d); +} + /// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them. #[test] fn a_failed_save_does_not_stamp_the_documents_dates() { diff --git a/crates/engine/src/cmd/fileio/tests_pcraftread.rs b/crates/engine/src/cmd/fileio/tests_pcraftread.rs index 444ba06606..ba46f8040b 100644 --- a/crates/engine/src/cmd/fileio/tests_pcraftread.rs +++ b/crates/engine/src/cmd/fileio/tests_pcraftread.rs @@ -215,6 +215,14 @@ fn layers_that_cant_be_combined_leave_the_preview_with_a_note() { assert!(pixels.width() == 30 && w.len() == 1 && w[0].contains(said), "{said}: {w:?}"); } + // A canvas whose combined pixels would take more memory than one image may use leaves the + // preview, saying so before any layer is read. + let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]); + b.size = (12_000, 12_000); + let (r, _, pixels) = place(&b.bytes()); + let w = warnings(&r); + assert!(pixels.width() == 30 && w.len() == 1 && w[0].contains("too large to combine"), "{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); diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index 7c0aa4a74b..fc386ac09c 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -71,9 +71,163 @@ fn export(s: &mut Session, p: Value) -> (Vec, Vec) { (bytes, v["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect()) } -/// The transparency `pdf` has, in its dictionaries. +/// Whether `b` ends a PDF token: white space or a delimiter. +fn ends_token(b: u8) -> bool { + b.is_ascii_whitespace() || b"()<>[]{}/%".contains(&b) +} + +/// The offset of object `number generation` in the cross-reference tables of `pdf`, starting at the +/// `startxref` at `startxref` and following `/Prev`. +fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) -> Option { + let mut offset = String::from_utf8_lossy(&pdf[startxref + b"startxref".len()..]).split_ascii_whitespace().next()?.parse::().ok()?; + let mut visited = vec![]; + loop { + if visited.contains(&offset) { + return None; + } + visited.push(offset); + let table = String::from_utf8_lossy(pdf.get(offset..)?); + let mut words = table.split_ascii_whitespace(); + if words.next()? != "xref" { + return None; + } + loop { + let first = words.next()?; + if first == "trailer" { + break; + } + let first = first.parse::().ok()?; + let count = words.next()?.parse::().ok()?; + for index in 0..count { + let at = words.next()?.parse::().ok()?; + let entry_generation = words.next()?.parse::().ok()?; + let status = words.next()?; + if first.checked_add(index)? == number { + return (status == "n" && entry_generation == generation).then_some(at); + } + } + } + let trailer = table.split_once("trailer")?.1.split_once(">>")?.0; + let mut words = trailer.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()); + words.find(|&w| w == "Prev")?; + offset = words.next()?.parse().ok()?; + } +} + +/// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary +/// after the object's `obj` keyword. The keyword counts only at the start of `text` or after white +/// space, so a name such as `/Tag/obj` is not taken for it. An indirect length is read from its +/// object in `pdf`. `None` when it is missing or cannot be read. +fn stream_length(text: &[u8], pdf: &[u8]) -> Option { + let from = text + .windows(3) + .enumerate() + .rev() + .find(|&(at, w)| w == b"obj" && (at == 0 || matches!(text[at - 1], b'\0' | b'\t' | b'\n' | b'\x0c' | b'\r' | b' '))) + .map_or(0, |(at, _)| at + 3); + let dict = &text[from..]; + let mut i = dict.windows(2).position(|w| w == b"<<")? + 2; + let mut depth = 1usize; + let mut length = None; + while i < dict.len() && depth > 0 { + let rest = &dict[i..]; + if rest.starts_with(b"<<") { + depth += 1; + i += 2; + } else if rest.starts_with(b">>") { + depth -= 1; + i += 2; + } else if rest[0] == b'<' { + // A hex string. + i += rest.iter().position(|&b| b == b'>').map_or(rest.len(), |at| at + 1); + } else if depth == 1 && rest.starts_with(b"/Length") && rest.get(7).is_none_or(|&b| ends_token(b)) { + let value = String::from_utf8_lossy(&rest[7..]); + let words: Vec<&str> = value.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()).take(3).collect(); + length = match words[..] { + // `n g R` is an indirect length: the integer in object `n g`. + [n, g, "R", ..] => { + let header = format!("{n} {g} obj"); + let read_length = |at: usize| { + let body = String::from_utf8_lossy(&pdf[at + header.len()..]); + match body.split_ascii_whitespace().take(2).collect::>()[..] { + [n, "endobj"] => n.parse::().ok(), + _ => None, + } + }; + if let Some(startxref) = pdf.windows(b"startxref".len()).rposition(|w| w == b"startxref") { + let at = + xref_offset(pdf, n.parse().ok()?, g.parse().ok()?, startxref).expect("stream /Length reference is missing from xref"); + let object = pdf.get(at..).expect("stream /Length xref offset is outside the file"); + assert!(object.starts_with(header.as_bytes()), "stream /Length xref offset has a different object"); + read_length(at) + } else { + pdf.windows(header.len()) + .enumerate() + // An object header starts a line, and the length object holds one integer. + .filter(|&(at, w)| w == header.as_bytes() && (at == 0 || matches!(pdf[at - 1], b'\r' | b'\n'))) + .find_map(|(at, _)| read_length(at)) + } + } + [n, ..] => n.parse::().ok(), + [] => None, + }; + i += 7; + } else { + i += 1; + } + } + length +} + +/// The transparency `pdf` has, in its dictionaries. Stream data and literal strings are left out: +/// the file ID, in the trailer and in the XMP stream, is base64 that changes with the export time +/// and can spell `/BM`. fn transparency(pdf: &[u8]) -> Vec<&'static str> { - let text = String::from_utf8_lossy(pdf); + let mut text = Vec::with_capacity(pdf.len()); + let mut i = 0; + while i < pdf.len() { + let rest = &pdf[i..]; + // A keyword follows white space or a dictionary's `>>`; after `/` it is part of a name. + let keyword_start = i == 0 || pdf[i - 1].is_ascii_whitespace() || pdf[i - 1] == b'>'; + if keyword_start && rest.starts_with(b"endstream") { + text.extend_from_slice(b"endstream"); + i += b"endstream".len(); + } else if keyword_start && rest.starts_with(b"stream") && matches!(rest.get(b"stream".len()), Some(b'\r' | b'\n')) { + // Stream data is the dictionary's `/Length` bytes after the end of line (else it runs to + // `endstream`); its bytes are not PDF syntax. + let start = i + b"stream".len() + if rest[b"stream".len()..].starts_with(b"\r\n") { 2 } else { 1 }; + i = match stream_length(&text, pdf) { + Some(n) => { + let mut end = start.checked_add(n).filter(|&end| end <= pdf.len()).expect("stream /Length is inconsistent with endstream"); + while matches!(pdf.get(end), Some(b'\r' | b'\n')) { + end += 1; + } + assert!(pdf[end..].starts_with(b"endstream"), "stream /Length is inconsistent with endstream"); + end + } + None => i + rest.windows(b"endstream".len()).position(|w| w == b"endstream").expect("stream has no endstream"), + }; + } else if rest[0] == b'(' { + // A literal string: balanced parentheses, with `\` escaping the next byte. + let mut depth = 0usize; + while i < pdf.len() { + match pdf[i] { + b'\\' => i += 1, + b'(' => depth += 1, + b')' => depth -= 1, + _ => {} + } + i += 1; + if depth == 0 { + break; + } + } + } else { + text.push(rest[0]); + i += 1; + } + } + let text = String::from_utf8_lossy(&text); let mut found = vec![]; for (what, there) in [ ("soft masks", text.contains("/SMask") && !text.contains("/SMask/None")), @@ -193,3 +347,79 @@ fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() { s.execute("document.open", &json!({"dataBase64": vectorcraft_format::base64_encode(&pdf), "name": "old.pdf", "password": "nope"})).is_err() ); } + +/// The file ID is base64 that changes with the export time, so it can spell `/BM`; the check +/// reads the file's dictionaries only, not its strings or its XMP packet. +#[test] +fn the_transparency_check_skips_strings_and_metadata() { + let pdf = b"%PDF-1.3\n5 0 obj\n<>\nendobj\n6 0 obj\n<>\nstream\nq/BMx/S/Transparency\nendstream\nendobj\ntrailer\n<>\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + assert_eq!(transparency(b"<>>>>>"), vec!["blend modes", "opacity"]); + // A `(` in image data starts no string, and nested and escaped parentheses end where the + // string does. + let pdf = b"<>\nstream\n(\x00(\nendstream\n<>\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks", "transparency groups"]); + // Stream data is skipped by its length, even when it holds `endstream` itself. + let pdf = b"1 0 obj\n<>\nstream\nendstream (/BM\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + let pdf = b"1 0 obj\n<>\nstream\nabc\r\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + let pdf = b"1 0 obj\n<>\nstream\nabcendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + // Only the stream dictionary's own `/Length` counts, not one in a nested dictionary. + let pdf = b"1 0 obj\n<>>>\nstream\n/BM \nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + // `stream` inside a name is not the keyword. + let pdf = b"1 0 obj\n<>\nendobj\n"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nendobj\n"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + // An indirect length is read from its object, so `endstream` in the data does not end it. + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n2 0 obj\n13\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + let payload = b"2 0 obj\n13\nendobj\nendstream /BM"; + let mut pdf = b"%PDF-1.3\n".to_vec(); + let stream_at = pdf.len(); + pdf.extend_from_slice(b"1 0 obj\n<>\nstream\n"); + pdf.extend_from_slice(payload); + pdf.extend_from_slice(b"\nendstream\nendobj\n"); + let length_at = pdf.len(); + pdf.extend_from_slice(format!("2 0 obj\n{}\nendobj\n", payload.len()).as_bytes()); + let catalog_at = pdf.len(); + pdf.extend_from_slice(b"3 0 obj\n<>\nendobj\n"); + let pages_at = pdf.len(); + pdf.extend_from_slice(b"4 0 obj\n<>\nendobj\n"); + let xref_at = pdf.len(); + pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f\r\n"); + for at in [stream_at, length_at, catalog_at, pages_at] { + pdf.extend_from_slice(format!("{at:010} 00000 n\r\n").as_bytes()); + } + pdf.extend_from_slice(format!("trailer\n<>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes()); + assert_eq!(transparency(&pdf), Vec::<&str>::new()); + // A stream with no length and no `endstream` fails rather than hiding the rest of the file. + let pdf = b"1 0 obj\n<<>>\nstream\nabc\n<>"; + assert!(std::panic::catch_unwind(|| transparency(pdf)).is_err()); + for length in [2, 20, 999, usize::MAX] { + let pdf = format!("1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"); + let panic = std::panic::catch_unwind(|| transparency(pdf.as_bytes())).expect_err("an inconsistent stream /Length must panic"); + let message = panic.downcast_ref::<&str>().copied().or_else(|| panic.downcast_ref::().map(String::as_str)); + assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}"); + } +} + +/// A name that ends in `obj`, such as `/Tag/obj`, is not the object's `obj` keyword, so the +/// stream's `/Length` is still read from the outer dictionary. +#[test] +fn the_stream_length_skips_names_that_end_in_obj() { + let text = b"1 0 obj\n<>\nstream\n"; + assert_eq!(stream_length(text, text), Some(5)); + // NUL is PDF white space, so it may separate the generation number from `obj`. + let text = b"1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n2 0\0obj\n<>\nstream\n"; + assert_eq!(stream_length(text, text), Some(5)); + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); +} diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index ded0f137b3..fce524598e 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -374,6 +374,11 @@ fn slices_that_cant_be_read_warn_and_the_file_still_opens() { // The count follows the version, the bounds and the group's name. ([&good[..34], &u32::MAX.to_be_bytes()[..], &good[38..]].concat(), "more than the 10000 read"), (v7(8, vec![D::Long(3)]), "other than a slice"), + // A descriptor's list of more slices than are read, refused before any is looked at. + (v7(7, (0..10_001).map(|_| D::Long(0)).collect()), "more than the 10000 read"), + // Objects, and lists, nested one level deeper than are read. + (deep(17, |d| D::Obj(vec![("in", d)])), "nests too deep"), + (deep(17, |d| D::List(vec![d])), "nests too deep"), // A whole record whose name is longer than a slice's text may be. (v6(&[user("a".repeat(65_537).leak(), [0, 0, 5, 5])], &[]), "more than the 65536 characters read"), ]; @@ -395,6 +400,21 @@ fn slices_that_cant_be_read_warn_and_the_file_still_opens() { // A file without slices opens without a word about them. let (s, r) = open(&psd(true), json!({})); assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}"); + // Objects and lists nested as deep as are read come in. + for data in [deep(16, |d| D::Obj(vec![("in", d)])), deep(16, |d| D::List(vec![d]))] { + let (_, r) = open(&with_resource(&psd(false), 1050, &data), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + } +} + +/// Resource 1050 in version 7 with no slices, whose descriptor also holds `levels` values nested +/// one in another by `wrap`, around a long. +fn deep(levels: usize, wrap: fn(D) -> D) -> Vec { + let nested = (0..levels).fold(D::Long(0), |d, _| wrap(d)); + let mut b = 7u32.to_be_bytes().to_vec(); + b.extend(16u32.to_be_bytes()); + b.extend(descriptor(&[("deep", nested), ("slices", D::List(vec![]))])); + b } #[test] diff --git a/crates/engine/src/cmd/fileio/tests_raster.rs b/crates/engine/src/cmd/fileio/tests_raster.rs index b43f3d0547..93e875b35a 100644 --- a/crates/engine/src/cmd/fileio/tests_raster.rs +++ b/crates/engine/src/cmd/fileio/tests_raster.rs @@ -397,6 +397,30 @@ fn width_or_height_sets_the_pixel_size_of_a_raster_export() { assert_eq!(size(&mut s, json!({"format": "png", "width": 1})), (2, 1), "the scale stays at 0.01 pixels per point or more"); } +#[test] +fn raster_pixel_size_clamping_reports_the_requested_and_written_size() { + for (points, axis, requested, written, limit, direction) in [ + ((16.0, 8.0), "width", 1920, 1024, "more than 64", "wide"), + ((16.0, 8.0), "height", 1920, 512, "more than 64", "high"), + ((200.0, 100.0), "width", 1, 2, "less than 0.01", "wide"), + ((100.0, 200.0), "height", 1, 2, "less than 0.01", "high"), + ] { + let mut s = session(points.0, points.1, 1); + s.paint.stroke = vectorcraft_color::Paint::None; + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": points.0, "height": points.1})).unwrap(); + for extra in [json!({}), json!({"rect": [0, 0, points.0, points.1]}), json!({"useArtboards": false})] { + let mut p = json!({"format": "png"}); + p[axis] = json!(requested); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let r = s.execute("document.export", &p).unwrap(); + let size = rgba(&b64(&r)).dimensions(); + assert_eq!(if axis == "width" { size.0 } else { size.1 }, written, "{p}"); + let note = format!("{axis} {requested} px needs {limit} pixels per point: artboard 1 was written {written} px {direction}"); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str() == Some(note.as_str())), "{p}: {r}"); + } + } +} + #[test] fn a_width_or_height_that_is_not_a_positive_number_is_refused() { let mut s = session(200.0, 100.0, 1); diff --git a/crates/engine/src/cmd/fileio/tests_readonly.rs b/crates/engine/src/cmd/fileio/tests_readonly.rs index ae9762efc3..a60e9841b2 100644 --- a/crates/engine/src/cmd/fileio/tests_readonly.rs +++ b/crates/engine/src/cmd/fileio/tests_readonly.rs @@ -28,6 +28,64 @@ fn readonly_error_is_typed_and_other_writers_keep_their_error() { } } +#[test] +fn readonly_sidecar_leaves_every_save_destination_unchanged() { + let dir = vectorcraft_testkit::TempDir::new("save-readonly-sidecar"); + for format in ["vectorcraft", "eps"] { + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 40, "height": 40, "artboards": 2})).unwrap(); + let path = dir.join(format!("Poster.{format}")).to_string_lossy().into_owned(); + let params = if format == "eps" { json!({"path": path, "useArtboards": true}) } else { json!({"path": path, "separateArtboards": true}) }; + let saved = session.execute("file.saveAs", ¶ms).unwrap(); + let files: Vec<_> = saved["files"].as_array().unwrap().iter().map(|p| p.as_str().unwrap()).collect(); + assert!(files.len() > 1); + let before: Vec<_> = files.iter().map(std::fs::read).collect::>().unwrap(); + session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + let doc = session.doc().unwrap().doc.clone(); + let sidecar = files.last().unwrap(); + let original = std::fs::metadata(sidecar).unwrap().permissions(); + let mut readonly = original.clone(); + readonly.set_readonly(true); + std::fs::set_permissions(sidecar, readonly).unwrap(); + let result = session.execute("file.saveAs", ¶ms); + std::fs::set_permissions(sidecar, original).unwrap(); + let error = result.unwrap_err(); + assert!(matches!(error, EngineError::ReadOnlyLocation(_)), "{error}"); + for (file, bytes) in files.iter().zip(before) { + assert_eq!(std::fs::read(file).unwrap(), bytes, "{file}"); + } + assert_eq!(*session.doc().unwrap().doc, *doc); + assert!(session.doc().unwrap().is_dirty()); + } +} + +#[test] +fn readonly_export_file_leaves_every_export_destination_unchanged() { + let dir = vectorcraft_testkit::TempDir::new("export-readonly-sidecar"); + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 40, "height": 40, "artboards": 2})).unwrap(); + let doc = session.doc().unwrap().doc.clone(); + let enc = super::Encoded { files: vec![(None, b"new main".to_vec()), (Some(1), b"new board".to_vec())], ..Default::default() }; + let path = dir.join("Poster.svg").to_string_lossy().into_owned(); + let files: Vec = enc.named(&doc, &path).into_iter().map(|(p, _)| p).collect(); + assert_eq!(files.len(), 2); + for file in &files { + std::fs::write(file, b"old").unwrap(); + } + let sidecar = &files[1]; + let original = std::fs::metadata(sidecar).unwrap().permissions(); + let mut readonly = original.clone(); + readonly.set_readonly(true); + std::fs::set_permissions(sidecar, readonly).unwrap(); + let result = super::write_encoded(Some(&path), "Poster.svg", &doc, &enc, json!({})); + std::fs::set_permissions(sidecar, original).unwrap(); + let error = result.unwrap_err(); + assert!(matches!(error, EngineError::ReadOnlyLocation(_)), "{error}"); + for file in &files { + assert_eq!(std::fs::read(file).unwrap(), b"old", "{file}"); + } +} + #[test] fn readonly_failed_save_keeps_document_and_options() { let mut session = Session::new(); diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index fe1e183d16..8a884b67ea 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -692,7 +692,19 @@ fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Optio } } } - let png = img.to_png().map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; + // The PNG is written with fast compression: the exports that flatten (EPS, PDF 1.3) decode it + // again right away. + let raw = craft_image_codecs::Image::from_raw( + img.width, + img.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.to_straight(), + ) + .map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &opts) + .map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; Ok(Raster { blob: ImageBlob::new("image/png", png), width: img.width, height: img.height, xf, clip }) } diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 01e0a5a732..810953fa3f 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -88,8 +88,8 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { /// paint for (the Live Paint Bucket, or the Shape Builder's Fill proxy). Selecting other art, /// picking a part of the instance, toggling the proxy, picking another item or choosing such a /// tool or leaving it leaves no stop selected. The Gradient panel keys its selected midpoint -/// diamond by it as well ([`Session::gradient_owner`]). -#[derive(Clone, Copy, Debug, PartialEq)] +/// diamond and its fields' unfinished values by it as well ([`Session::gradient_owner`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct StopOwner { /// The active document's uid, which stays the same when its tab moves. doc: Option, @@ -128,6 +128,13 @@ impl StopOwner { #[derive(PartialEq)] pub struct GradientEditPaints(Vec); +impl GradientEditPaints { + /// Whether every edited paint, including every text run's paint, satisfies `matches`. + pub fn all_paints_match(&self, matches: impl FnMut(&Paint) -> bool) -> bool { + self.0.iter().flat_map(|target| &target.paints).all(matches) + } +} + #[derive(PartialEq)] struct EditedPaint { id: NodeId, @@ -520,12 +527,20 @@ fn apply_gradient_edit_in_model( switched = true; } } - let recolor = p.get("stops").is_some() || bool_or(p, "reverse", false); + let reverse = bool_or(p, "reverse", false); + let recolor = p.get("stops").is_some() || reverse; if let Some(stops) = p.get("stops") { - gp.gradient.stops = parse_stops(stops)?; - gp.swatch = None; - } - if bool_or(p, "reverse", false) { + let stops = parse_stops(stops)?; + let before = std::mem::replace(&mut gp.gradient.stops, stops); + if reverse { + // Midpoints mirrored with their segments. + gp.gradient.reverse(); + } + // A paint whose final stops stay as they are keeps its gradient swatch. + if gp.gradient.stops != before { + gp.swatch = None; + } + } else if reverse { // Midpoints mirrored with their segments. gp.gradient.reverse(); } @@ -894,3 +909,39 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::>() })) } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_color::Color; + + fn linked(stops: &[(f32, &str)]) -> Paint { + let stops = stops.iter().map(|(offset, hex)| GradientStop::new(*offset, Color::from_hex(hex).unwrap())).collect(); + let mut paint = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + paint.swatch = Some("Linked".into()); + Paint::Gradient(Box::new(paint)) + } + + fn swatch(paint: &Paint) -> Option<&str> { + match paint { + Paint::Gradient(g) => g.swatch.as_deref(), + _ => None, + } + } + + #[test] + fn writing_the_stops_a_paint_already_has_keeps_its_gradient_swatch() { + let paint = linked(&[(0.0, "#ffffff"), (1.0, "#000000")]); + let same = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]}); + assert_eq!(swatch(&apply_gradient_edit(&paint, &same, None).unwrap()), Some("Linked")); + let other = json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#000000"}]}); + assert_eq!(swatch(&apply_gradient_edit(&paint, &other, None).unwrap()), None, "new stops unlink the swatch"); + } + + #[test] + fn writing_the_same_stops_reversed_unlinks_the_gradient_swatch() { + let paint = linked(&[(0.0, "#ffffff"), (1.0, "#000000")]); + let reversed = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}], "reverse": true}); + assert_eq!(swatch(&apply_gradient_edit(&paint, &reversed, None).unwrap()), None, "reversed stops unlink the swatch"); + } +} diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index f348a97f3c..9de04ef106 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -41,14 +41,12 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; -pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs}; +pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs, series_drawn_designs}; pub use edit::{GraphTypeSubject, graph_type_subject}; pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed}; pub use generate::calculated_axes; #[cfg(test)] use generate::generate; -#[cfg(test)] -use series::default_series_color; pub(crate) use series::{ LabelTextChange, RowWrites, capture_label_anti_alias, capture_label_changes, capture_label_kind_rows, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes, @@ -57,6 +55,8 @@ pub(crate) use series::{ is_graph_line, is_series_group, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades, }; +#[cfg(test)] +use series::{WEDGE_BUDGET, default_series_color, legend_on_dark}; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/graph/designs.rs b/crates/engine/src/cmd/graph/designs.rs index f0d42808ab..6b7ac1e9ec 100644 --- a/crates/engine/src/cmd/graph/designs.rs +++ b/crates/engine/src/cmd/graph/designs.rs @@ -88,22 +88,36 @@ pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: sup /// on or the legend has an entry for the series, or as the columns of a series drawn as columns or /// bars. fn draws_with(g: &GraphSpec, name: &str) -> bool { + let count = g.series_markers.len().max(g.series_columns.len()); + let drawn = series_drawn_designs(g); + (0..count).any(|s| { + let (marker, column) = drawn(s); + marker == Some(name) || column == Some(name) + }) +} + +/// For each series `s` of graph `g`, the designs it draws with, as [`draws_with`] counts them: its +/// marker design and its column design, each only when the series draws it. +pub(crate) fn series_drawn_designs<'a>(g: &'a GraphSpec) -> impl Fn(usize) -> (Option<&'a str>, Option<&'a str>) + 'a { let scatter = g.kind == GraphKind::Scatter; let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES); // The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank // (a scatter graph's entries are its pairs of series, labeled by the first of each pair). - let in_legend = |s: usize| { + let in_legend = move |s: usize| { let entries = if scatter { nser.div_ceil(2) } else { nser }; let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str); g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label) }; // Point markers use the same range of designs: a scatter graph plots a pair of series for each. let plotted = if scatter { nser.div_ceil(2) } else { nser }; - let shown = |s: usize| s < plotted && (g.mark_points || in_legend(s)); - let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line); - let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar); - g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s)) - || g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s)) + let shown = move |s: usize| s < plotted && (g.mark_points || in_legend(s)); + let marked = move |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line); + let columnar = move |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar); + move |s: usize| { + let marker = g.series_markers.get(s).and_then(Option::as_deref).filter(|_| marked(s)); + let column = g.series_columns.get(s).and_then(Option::as_ref).map(|c| c.design.as_str()).filter(|_| columnar(s)); + (marker, column) + } } /// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 7371961c20..550f72c478 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -1113,7 +1113,7 @@ fn redrawn_on_dark(n: &Node, g: &GraphSpec) -> Option> { /// on, which lies inside its wedge: the wedge holding it of the series the label names (the nearest one when none holds /// it), or of any series when the label names none. When the wedges of the series a label names are all dark or all /// light, the label's place does not matter. -fn legend_on_dark(n: &Node, g: &GraphSpec) -> HashMap { +pub(super) fn legend_on_dark(n: &Node, g: &GraphSpec) -> HashMap { wedge_contrast(&legend_labels(n), &pie_wedges(n), g) } @@ -1134,6 +1134,28 @@ fn label_anchor(text: &vectorcraft_doc::TextObject, name: &str, g: &GraphSpec, l text.xf * vectorcraft_geom::Point::new(0.0, middle - ls * 0.35) } +/// Most wedges [`wedge_contrast`] measures for one pie's legend labels together. +const WEDGE_MEASUREMENTS: usize = 1 << 20; + +#[cfg(test)] +thread_local! { + /// The limit [`wedge_budget`] gives on this thread: [`WEDGE_MEASUREMENTS`] unless a test sets a lower one, so that a + /// test of the limit uses a small pie. + pub(super) static WEDGE_BUDGET: std::cell::Cell = const { std::cell::Cell::new(WEDGE_MEASUREMENTS) }; +} + +/// Most wedges [`wedge_contrast`] measures: [`WEDGE_MEASUREMENTS`]. +#[cfg(not(test))] +fn wedge_budget() -> usize { + WEDGE_MEASUREMENTS +} + +/// Most wedges [`wedge_contrast`] measures: [`WEDGE_MEASUREMENTS`], or the lower limit a test set in [`WEDGE_BUDGET`]. +#[cfg(test)] +fn wedge_budget() -> usize { + WEDGE_BUDGET.with(std::cell::Cell::get) +} + /// [`legend_on_dark`] for legend labels `legend` of a pie of spec `g` with wedges `wedges`. fn wedge_contrast(legend: &[&Node], wedges: &[Wedge], g: &GraphSpec) -> HashMap { use vectorcraft_geom::kurbo::ParamCurveNearest; @@ -1164,7 +1186,7 @@ fn wedge_contrast(legend: &[&Node], wedges: &[Wedge], g: &GraphSpec) -> HashMap< let ls = label_size(&g.label_styles, Role::Legend); // The search for the nearest wedge looks at this many wedges in all; past it, a label takes the contrast most of the // wedges of its series show. - let mut budget: usize = 1 << 20; + let mut budget = wedge_budget(); for t in legend { let NodeKind::Text(text) = &t.kind else { continue }; let id = t.id; diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index b41415ef02..59fdb38862 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6891,6 +6891,11 @@ fn new_design_rename_delete_and_select_unused() { assert_eq!(spec(&s, id).series_markers, [Some("Dot".to_string()), Some("Dot".to_string())]); assert!(s.execute("graph.design", &json!({"rename": "Dot", "to": "New Design 2"})).is_err(), "taken"); assert!(s.execute("graph.design", &json!({"rename": "Nope", "to": "X"})).is_err()); + // Renaming a design to its own name succeeds and records no undo step. + let (steps, designs) = (s.doc().unwrap().history.undo.len(), s.execute("graph.design", &json!({})).unwrap()["designs"].clone()); + assert_eq!(s.execute("graph.design", &json!({"rename": "Dot", "to": "Dot"})).unwrap()["name"], "Dot"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(s.execute("graph.design", &json!({})).unwrap()["designs"], designs); // Delete several at once. s.execute("graph.design", &json!({"delete": ["Dot", "New Design 2"]})).unwrap(); assert_eq!(s.execute("graph.design", &json!({})).unwrap()["designs"], json!([])); @@ -10285,6 +10290,60 @@ fn a_color_mode_change_keeps_the_default_legend_fill_of_other_graphs() { } } +/// Past the limit on wedge measurements, a legend label of a pie with Legends in Wedges takes the contrast most of the +/// wedges of its series show: dark when 2 of its 3 wedges are dark, light when 1 of its 3 is. +#[test] +fn past_the_wedge_limit_a_legend_label_takes_the_contrast_most_of_its_wedges_show() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = make(&mut s, "pie", ",a,b\nP1,1,2\nP2,1,2\nP3,1,2"); + s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap(); + // The first two wedges of series a are dark and the third light; only the first wedge of series b is dark. + let wedge_ids = |s: &Session, index: u32| -> Vec { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let mut ids = vec![]; + series(&n, index).walk(&mut |m| { + if matches!(m.kind, NodeKind::Path { .. }) { + ids.push(m.id); + } + }); + ids + }; + let (a, b) = (wedge_ids(&s, 0), wedge_ids(&s, 1)); + assert_eq!((a.len(), b.len()), (3, 3), "one wedge of each series in each of the 3 pies"); + s.edit("shade", |d, _| { + for (ids, darks) in [(&a, 2), (&b, 1)] { + for (i, w) in ids.iter().enumerate() { + let color = if i < darks { vectorcraft_color::Color::BLACK } else { vectorcraft_color::Color::WHITE }; + d.node_mut(*w).unwrap().appearance.set_fill(Paint::solid(color)); + } + } + Ok(()) + }) + .unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let g = spec(&s, id); + let label = |text: &str| -> Vec { + group(&n, "Legend") + .children() + .unwrap() + .iter() + .filter(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)) + .map(|c| c.id) + .collect() + }; + let (label_a, label_b) = (label("a"), label("b")); + assert!(!label_a.is_empty() && !label_b.is_empty(), "the legend labels a and b"); + let measured = super::legend_on_dark(&n, &g); + super::WEDGE_BUDGET.with(|b| b.set(0)); + let past = super::legend_on_dark(&n, &g); + super::WEDGE_BUDGET.with(|b| b.set(1 << 20)); + let on_dark = |map: &std::collections::HashMap, ids: &[NodeId]| -> Vec { ids.iter().map(|i| map[i]).collect() }; + assert!(on_dark(&measured, &label_a).contains(&false), "measured: a label of a sits on its light wedge: {measured:?}"); + assert!(on_dark(&past, &label_a).iter().all(|d| *d), "past the limit: 2 of 3 dark gives dark: {past:?}"); + assert!(on_dark(&past, &label_b).iter().all(|d| !*d), "past the limit: 1 of 3 dark gives light: {past:?}"); +} + #[test] fn labels_are_told_apart_by_where_they_come_not_by_their_text() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/halftone.rs b/crates/engine/src/cmd/halftone.rs index 9677f23ad6..70a5b11b9f 100644 --- a/crates/engine/src/cmd/halftone.rs +++ b/crates/engine/src/cmd/halftone.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use vectorcraft_color::Color; use vectorcraft_doc::Node; -use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes}; +use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes, style}; use super::edit::selected_roots; use super::{CommandSpec, EngineError, Result, Session, bad, cmd, color_value, has_selection, number_or, switch_or, text_param}; @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Vector Halftone…", ["Object"], None, - "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; at partial tones circle, ellipse and diamond dots stay inside their cell, sized to preserve the tone's coverage; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes; at full tone every shape but line is the cell's square), style?: \"custom\"|\"grid\"|\"gridAngle\"|\"gridDots\"|\"gridDotsAngle\" (custom; sets shape and angle unless they are given: grid euclidean at 0°, gridAngle euclidean at 45°, gridDots circle at 0°, gridDotsAngle circle at 45°), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_selection, halftone )] @@ -27,17 +27,24 @@ pub fn specs() -> Vec { fn halftone(s: &mut Session, p: &Value) -> Result { const C: &str = "object.vectorHalftone"; + let styled = match p.get("style") { + Some(v) => { + let v = v.as_str().ok_or_else(|| bad(C, "style must be a string"))?; + style(v).ok_or_else(|| bad(C, format!("unknown style `{v}` (custom|grid|gridAngle|gridDots|gridDotsAngle)")))? + } + None => None, + }; let shape = match text_param(p, "shape", C)? { Some(v) => { DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line|euclidean|elliptical)")))? } - None => DotShape::Circle, + None => styled.map_or(DotShape::Circle, |s| s.0), }; let frequency = number_or(p, "frequency", 20.0, C)?; if !(1.0..=300.0).contains(&frequency) { return Err(bad(C, "frequency must be between 1 and 300 lines per inch")); } - let angle = number_or(p, "angle", 45.0, C)?; + let angle = number_or(p, "angle", styled.map_or(45.0, |s| s.1), C)?; if !angle.is_finite() { return Err(bad(C, "invalid angle")); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 78febf0f18..3a52534ac8 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -1001,18 +1001,79 @@ fn move_node(s: &mut Session, p: &Value) -> Result { let index = p.get("index").and_then(Value::as_u64).map_or(usize::MAX, index); let d = &s.doc()?.doc; let n = d.node(id).ok_or(EngineError::NoNode(id))?; - if !accepts(d, parent, n) { + let compound = parent.and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); + if let Some(c) = compound { + if !matches!(n.kind, NodeKind::Path { guide: false, .. }) { + return Err(bad(C, "a compound path holds only paths")); + } + // A clip group's or clipping layer's clipping path stays where it is: without it, the + // next object up would become the clipping path. + if d.position(id).is_some_and(|(from, i, _)| i == 0 && from.and_then(|f| d.node(f)).is_some_and(Node::clips)) { + return Err(bad(C, "a clipping path does not go into a compound path; release the clipping mask first")); + } + if !d.is_editable(c.id) { + return Err(bad(C, "the compound path is hidden or locked")); + } + } else if !accepts(d, parent, n) { return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups")); } + // The clipping path stays at the bottom of its clip group or clipping layer. + let from = d.parent_of(id); + let clips = |p: Option| p.and_then(|p| d.node(p)).filter(|p| p.clips()); + let is_mask = clips(from).and_then(Node::children).and_then(|c| c.first()).is_some_and(|c| c.id == id); + if is_mask && (parent != from || index != 0) { + return Err(bad(C, "the clipping path stays at the bottom of its clip group; release the clipping mask first")); + } + let index = if !is_mask && clips(parent).and_then(Node::children).is_some_and(|c| c.iter().any(|c| c.id != id)) { index.max(1) } else { index }; + // An empty compound path takes the paint of the first path that goes into it: the path's own, + // or the paint of the compound path it leaves, which is what painted it. + let from_compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); + let shown = from_compound.map_or(&n.appearance, |p| &p.appearance); + let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, shown.clone())); + let into = compound.map(|c| c.id); + // A compound path that is pixel-aligned already snaps the path it takes, too. + let from_aligned = from_compound.is_some_and(|c| c.extras().pixel_aligned) || compound.is_some_and(|c| c.extras().pixel_aligned); + // A path that leaves a compound path for a layer or a group takes the compound path's paint and + // pixel alignment, as Release Compound Path gives them to its paths. + let out_of = from_compound.filter(|_| compound.is_none()).map(|c| (c.appearance.clone(), c.extras().pixel_aligned)); if let Some(what) = super::intertwine::refused_in(d, parent, n) { return Err(bad(C, format!("{what} can't be intertwined"))); } let live_paint = LivePaintMove::plan(d, &[id], parent, false)?; let label = if live_paint.joins() { "Merge Live Paint" } else { "Reorder" }; - let from = d.parent_of(id); let left = super::intertwine::groups_of(d, &[id]); s.edit(label, |d, sel| { d.move_node(id, parent, index)?; + if let Some((c, appearance)) = paint + && let Some(n) = d.node_mut(c) + { + n.appearance = appearance; + } + // A path in a compound path keeps no paint, live shape or pixel alignment of its own, as + // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when + // the path was, or when the compound path it leaves was. + if let Some(c) = into { + let mut aligned = from_aligned; + if let Some(m) = d.node_mut(id) { + m.appearance = vectorcraft_doc::Appearance::default().into(); + aligned |= std::mem::take(&mut m.extras_mut().pixel_aligned); + if let NodeKind::Path { live, .. } = &mut m.kind { + *live = None; + } + } + if aligned && let Some(cn) = d.node_mut(c) { + cn.extras_mut().pixel_aligned = true; + super::object::snap_if_aligned(cn); + } + } + if let Some((appearance, aligned)) = out_of + && let Some(m) = d.node_mut(id) + { + m.appearance = appearance; + if aligned { + m.extras_mut().pixel_aligned = true; + } + } super::intertwine::settle_members(d, &[(id, from)], &left)?; live_paint.finish(d, sel, &[id])?; sel.prune(d); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 142cb8a654..a5e00eab67 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -174,6 +174,11 @@ struct Group { document: Option, /// An image placed from a DCS file: the plate files of their own its plates were read from. plate_files: Vec, + /// The stored relative paths of the group's objects other than `link`'s, each once: objects + /// with the same path and content can each keep a relative path of its own. + other_relatives: Vec, + /// `other_relatives` as a set, looked up for every object added to the group. + relatives_seen: std::collections::HashSet, } /// What a placed document shows: whether the art's bounds (not the artboard or page) are shown, @@ -203,6 +208,32 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { out } +/// Every place a linked image or placed document of `d` (a document looking from `base`) is read +/// from, wherever it is stored, brush art included, whether or not a file is there: each place +/// [`locate`] looks at, and beside each one the plate files of an image placed from a DCS file, +/// as its plate-change check finds them. A link's absolute stored and relative paths are listed +/// too, for the relative path of every object in a group. Document-path restrictions apply before +/// any filesystem probe. +pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec { + let mut out = vec![]; + for g in groups(d, None) { + let others = g.other_relatives.iter().map(|r| LinkInfo { relative: Some(r.clone()), ..g.link.clone() }); + for link in std::iter::once(g.link.clone()).chain(others) { + let mut mains: Vec = std::iter::once(link.path.as_str()) + .chain(link.relative.as_deref()) + .filter(|p| Path::new(p).is_absolute()) + .filter_map(|p| fileio::document_path(p, base.doc).ok()) + .collect(); + mains.extend(places(&link, base)); + for main in mains { + out.extend(g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&main, &f.name))); + out.push(main); + } + } + } + out +} + /// The linked images and placed documents of `d` by file and content, wherever they are stored /// (only `ids` when given), in [`Document::visit_stored`] order. An object whose id an object /// visited before it has (art being edited on a layer and its definition) counts once, by its @@ -220,10 +251,26 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { None => d.images.get(key).map(ImageBlob::plate_files).unwrap_or_default(), Some(_) => vec![], }; - out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document, plate_files }); + out.push(Group { + link: link.clone(), + key: key.to_string(), + ids: vec![], + document, + plate_files, + other_relatives: vec![], + relatives_seen: Default::default(), + }); out.len() - 1 }); - if let (Some(id), Some(g)) = (id, out.get_mut(i)) { + let Some(g) = out.get_mut(i) else { return }; + if let Some(r) = &link.relative + && g.link.relative.as_ref() != Some(r) + && !g.relatives_seen.contains(r) + { + g.relatives_seen.insert(r.clone()); + g.other_relatives.push(r.clone()); + } + if let Some(id) = id { g.ids.push(id); } }; @@ -399,6 +446,17 @@ fn found_at(path: String) -> Option { /// by name in the document's folder, then in that of [`LinkBase::relative`]. Only paths /// [`fileio::document_path`] follows from the document's own file are looked at. fn locate(link: &LinkInfo, base: LinkBase) -> Option { + let mut f = places(link, base).find_map(found_at)?; + f.relative = base.relative.map(|from| { + let from = absolute_path(from); + Path::new(&from).parent().and_then(|dir| relative_path(Path::new(&f.path), dir)) + }); + Some(f) +} + +/// The places [`locate`] looks for the file of `link` at, in its order, whether or not a file is +/// there. +fn places<'a>(link: &'a LinkInfo, base: LinkBase<'a>) -> impl Iterator + 'a { let (relative, other) = (link.relative.as_deref(), base.doc != base.relative); let stored = [ (Some(link.path.as_str()), base.doc), @@ -407,12 +465,11 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { (Some(link.name()), base.doc), (other.then_some(link.name()), base.relative), ]; - let mut f = stored.into_iter().filter_map(|(p, from)| follow_from(p?, from, base.doc, fileio::document_path)).find_map(found_at)?; - f.relative = base.relative.map(|from| { - let from = absolute_path(from); - Path::new(&from).parent().and_then(|dir| relative_path(Path::new(&f.path), dir)) - }); - Some(f) + stored.into_iter().filter_map(move |(p, from)| follow_from(p?, from, base.doc, fileio::document_path)) +} + +pub(crate) fn located_path(link: &LinkInfo, base: LinkBase) -> Option { + locate(link, base).map(|f| f.path) } /// The files the links of `d` (a document looking from `base`) lead to now: where [`locate`] @@ -2335,7 +2392,17 @@ fn relink(s: &mut Session, p: &Value) -> Result { } } // Read before it is copied: a file that can't be shown isn't copied. - let img = if images.is_empty() { None } else { Some(linked_image(&bytes, Some(&path)).map_err(|e| bad(C, format!("{path}: {e}")))?) }; + let img = if images.is_empty() { + None + } else { + Some(linked_image(&bytes, Some(&path)).map_err(|e| { + // A file in no image format; a damaged image keeps its own error. + if s.image_only.get().is_some() && !fileio::is_raster_image(&bytes) && !super::place::dcs::is_dcs(&bytes) { + s.image_only.set(Some(false)); + } + bad(C, format!("{path}: {e}")) + })?) + }; // A copy beside the document would point at plate files it can't find there. if copy_to.is_some() && img.as_ref().is_some_and(|img| !img.blob.plate_files().is_empty()) { return Err(bad(C, format!("{path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are"))); @@ -3274,6 +3341,43 @@ mod tests { assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes)); } + /// Many objects of one file and content that each keep a relative path of their own make one + /// group, which lists every other relative path once, in the order the objects are stored. + #[test] + fn a_group_lists_each_other_relative_path_once_in_stored_order() { + let mut d = Document::new(612.0, 792.0); + let layer = d.default_layer(); + let relatives: Vec = (0..2_000).map(|i| format!("art/{}/pic.png", i % 1_000)).collect(); + for r in &relatives { + let link = LinkInfo { relative: Some(r.clone()), ..LinkInfo::new("/art/pic.png") }; + let im = ImageObject { + key: "pic".into(), + width: 1, + height: 1, + xf: Affine::IDENTITY, + link: Some(link), + placement: Default::default(), + pixels: None, + }; + let id = d.alloc_id(); + d.insert(layer, 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + } + let groups = groups(&d, None); + assert_eq!(groups.len(), 1); + let g = &groups[0]; + assert_eq!(g.ids.len(), 2_000); + // Objects inserted at index 0 are stored last to first. + let first = g.link.relative.clone().unwrap(); + let mut expected: Vec = vec![]; + for r in relatives.iter().rev() { + if *r != first && !expected.contains(r) { + expected.push(r.clone()); + } + } + assert_eq!(expected.len(), 999); + assert_eq!(g.other_relatives, expected); + } + #[test] fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() { for (name, stem) in [ diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index b44a26e645..5724498e14 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Blend"], Some("Cmd+Alt+B"), - "{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}", + "{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way. A start anchor makes rectangles blend anchor by anchor.), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}", has_doc, blend_make ), diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 8385350b2e..661fe741e7 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, off locked artboards, and visible in visible layers and groups; an object inside another listed one is left out, as from a selection; the nearest clip group or clipped layer around each object must be the same one, or none for all; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -896,11 +896,39 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p }) .collect(); // What the art draws, its geometry effects applied. - let b = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, vectorcraft_render::drawn_bounds(doc, n))); - let b = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?.inflate(pad, pad); + let each: Vec = nodes.iter().filter_map(|n| vectorcraft_render::drawn_bounds(doc, n)).collect(); + let b = each.iter().fold(None, |acc, r| vectorcraft_geom::union_opt(acc, Some(*r))); + let drawn = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?; + let mut b = drawn.inflate(pad, pad); + let mut clip_bounds = None; + if let Some(v) = p.get("clipBounds").filter(|v| !v.is_null()) { + let [x0, y0, x1, y1] = super::finite_numbers::<4>(v).ok_or_else(|| bad(cmd, "clipBounds must be four finite numbers [x0, y0, x1, y1]"))?; + if x1 <= x0 || y1 <= y0 { + return Err(bad(cmd, "clipBounds must have x1 greater than x0 and y1 greater than y0")); + } + let clip_rect = Rect::new(x0, y0, x1, y1); + // The rectangle must reach the art itself, not only the padding around it or the gap + // between two of the selected objects. + let reaches = |r: &Rect| { + let on = r.intersect(clip_rect); + on.width() > 0.0 && on.height() > 0.0 + }; + if !each.iter().any(reaches) { + return Err(bad(cmd, "clipBounds does not overlap the art")); + } + clip_bounds = Some(clip_rect); + b = b.intersect(clip_rect); + } let scale = ppi / 72.0; - // Snap to whole pixels. - let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale); + // The image covers the bounds in whole pixels. + let px = |lo: f64, hi: f64| { + let pixels = (hi - lo) * scale; + let nearest = pixels.round(); + let error = 8.0 * f64::EPSILON * (lo.abs() + hi.abs()) * scale; + let pixels = if (pixels - nearest).abs() <= error { nearest } else { pixels }; + pixels.ceil().max(1.0) + }; + let region = Rect::new(b.x0, b.y0, b.x0 + px(b.x0, b.x1) / scale, b.y0 + px(b.y0, b.y1) / scale); // Create Clipping Mask: the image is clipped to the art's outline with its geometry effects // applied, as on the canvas. let clip = look @@ -918,7 +946,15 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p }) .flatten() .map(|(bp, rule)| (PathData::from_bezpath(&bp), rule)); - let tmp = isolated_doc(doc, nodes); + let mut tmp = isolated_doc(doc, nodes); + if let Some(rect) = clip_bounds { + let children = tmp.layers.first_mut().and_then(|layer| Arc::make_mut(layer).children_mut()).map(std::mem::take).unwrap_or_default(); + let art = Node::group(tmp.alloc_id(), children); + let art = super::rasterfx::clip_group(&mut tmp, vectorcraft_geom::shapes::rectangle(rect), vectorcraft_geom::FillRule::NonZero, art); + if let Some(children) = tmp.layers.first_mut().and_then(|layer| Arc::make_mut(layer).children_mut()) { + children.push(Arc::new(art)); + } + } let opts = raster.render_options(RasterFormat::Png); let (img, warning) = render_pixels(&tmp, region, scale, &opts, look.color_model)?; let png = @@ -937,9 +973,88 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p Ok(Rasterized { blob, alpha, width: img.width, height: img.height, xf, clip, warning }) } +/// The objects `ids` names for Rasterize, in paint order: each an object of the active document, +/// listed once, with no locks on it, its descendants, or a layer or group it is in. An object +/// inside another listed one is left out, as `edit::roots_of` leaves it out of a selection. +fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { + let ids = super::checked_ids_param(s, p, "ids", cmd)?; + let d = &s.doc()?.doc; + let mut listed = HashSet::with_capacity(ids.len()); + for id in &ids { + if !listed.insert(*id) { + return Err(bad(cmd, format!("id {} is listed twice", id.0))); + } + } + let mut roots = Vec::with_capacity(ids.len()); + let locks = d.locked_artboards(); + for id in &ids { + // The layers and groups from the top down to the object itself. + let Some(up) = d.ancestry(*id) else { return Err(bad(cmd, format!("no such object id {}", id.0))) }; + if d.node(*id).is_some_and(|n| n.is_layer()) { + return Err(bad(cmd, format!("id {} is a layer, not an object", id.0))); + } + if up.iter().any(|a| a != id && listed.contains(a)) { + continue; + } + let parent = up.len().checked_sub(2).and_then(|i| d.node(up[i])); + if !parent.is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { + return Err(bad(cmd, format!("id {} is part of a compound path or another object; give that object's id", id.0))); + } + // A clipping path's image would clip its siblings to a rectangle. + if parent.is_some_and(Node::clips) && d.position(*id).is_some_and(|(_, i, _)| i == 0) { + let message = if parent.is_some_and(Node::is_layer) { + "is a layer's clipping path and cannot be rasterized on its own" + } else { + "is a clipping path; give its clip group's id" + }; + return Err(bad(cmd, format!("id {} {message}", id.0))); + } + let mut locked = false; + if let Some(node) = d.node(*id) { + node.walk(&mut |n| locked |= n.locked); + } + if locked || up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { + return Err(bad(cmd, format!("id {} is locked, in a locked layer or group, or contains locked art", id.0))); + } + if locks.holds_id(*id) { + return Err(bad(cmd, format!("id {} is on a locked artboard", id.0))); + } + if up.iter().any(|a| d.node(*a).is_some_and(|n| !n.visible)) { + return Err(bad(cmd, format!("id {} is hidden or in a hidden layer or group", id.0))); + } + roots.push(*id); + } + // The image goes where the last object is, so every object must share its clipping context: + // the nearest clip group or clipped layer around it, or none. + let clipper = |id: NodeId| d.ancestry(id).and_then(|up| up.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(Node::clips))); + if let Some(first) = roots.first() { + let context = clipper(*first); + if let Some(other) = roots.iter().find(|id| clipper(**id) != context) { + return Err(bad( + cmd, + format!( + "id {} is clipped differently from id {}: the nearest clip group or clipped layer around each object must be the same one, or none for all", + other.0, first.0 + ), + )); + } + } + Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d)) +} + +/// The id of the image in `node`, the node Rasterize makes: the image itself, or the image in its +/// clip group. +fn image_in(node: &Node) -> NodeId { + match &node.kind { + NodeKind::Group { children, .. } => children.iter().find(|c| matches!(c.kind, NodeKind::Image(_))).map_or(node.id, |c| c.id), + _ => node.id, + } +} + fn rasterize(s: &mut Session, p: &Value) -> Result { const C: &str = "object.rasterize"; - let roots = selected_roots(s)?; + let given = p.get("ids").is_some_and(|v| !v.is_null()); + let roots = if given { rasterize_sources(s, p, C)? } else { selected_roots(s)? }; let st = s.doc()?; let nodes: Vec = roots.iter().filter_map(|id| st.doc.node(*id).cloned()).collect(); let image = rasterize_art(&st.doc, nodes, p, C, true)?; @@ -947,16 +1062,21 @@ fn rasterize(s: &mut Session, p: &Value) -> Result { if roots.is_empty() { return Err(bad(C, "nothing selected")); } - let id = s.edit("Rasterize", |d, sel| { + let (id, image_id) = s.edit("Rasterize", |d, sel| { let threaded = super::threads::frames(d); let node = image.into_node(d); + let image_id = image_in(&node); let id = d.wrap(&roots, |_| node)?; // Rasterized frames of threaded text leave their threads with the text they show. super::threads::leave_threads(d, &threaded); - sel.set([id]); - Ok(id) + if given { + sel.prune(d); + } else { + sel.set([id]); + } + Ok((id, image_id)) })?; - let mut out = json!({ "id": id.0, "width": w, "height": h }); + let mut out = json!({ "id": id.0, "imageId": image_id.0, "width": w, "height": h }); if let Some(w) = warning { out["warning"] = json!(w); } diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index f420054d11..d719434f28 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -109,6 +109,13 @@ pub(crate) fn stored_color(s: &Session, c: vectorcraft_color::Color) -> vectorcr super::paint::new_color(s, &json!({}), c) } +/// `c` as a paint command without `keepModel` stores it in `d`: an RGB color in a CMYK document +/// becomes CMYK through the document's own color settings ([`super::colormgmt::doc_cms`]). +pub(crate) fn stored_color_in(d: &vectorcraft_doc::Document, c: vectorcraft_color::Color) -> vectorcraft_color::Color { + let model = (d.color_mode != vectorcraft_doc::ColorMode::Rgb).then(|| d.color_mode.model()); + vectorcraft_color::cms::with_active(super::colormgmt::doc_cms(d), || super::paint::stored_color(model, c)) +} + /// `appearance.setNewArt`: new art's fill, stroke and stroke options, every value checked before /// anything changes. fn set_new_art(s: &mut Session, p: &Value) -> Result { @@ -408,6 +415,14 @@ impl Session { if matches!(&self.defaults_only_ran, Some(Some(ran)) if *ran == source) { return; } + if self.previewing + && self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.selection.is_empty() && it.inherited_preview_paint.is_none()) + { + let before = self.paint.clone(); + if let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut()) { + it.inherited_preview_paint = Some(before); + } + } let NewArtSource { appearance, opacity, blend, style, .. } = source; let kept_fill = fill.then(|| self.paint.fill.clone()); let kept_stroke = stroke.then(|| (self.paint.stroke.clone(), self.paint.stroke_width)); diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 7f54f8c03f..4dee23bcda 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -18,7 +18,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Artboard, Background, ColorMode, CompositeFont, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, LayerColor, Node, Unit}; use vectorcraft_geom::{Point, Rect}; -use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or}; +use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or, text_param}; pub fn specs() -> Vec { vec![ @@ -395,7 +395,7 @@ impl DocSettings { } "rows" => { self.rows = if replaying { - v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32) + v.as_f64().map(f64::round).filter(|n| *n >= 1.0).map(|n| n.min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) } @@ -605,10 +605,10 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result { - Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS)) + Ok(f64::deserialize(d)?.round().clamp(0.0, MAX_ARTBOARDS as f64) as u32) } /// A count `file.new` takes (artboards, columns, rows): a whole number, written `4` or `4.0`, from 1 @@ -858,6 +858,42 @@ pub fn find(s: &Session, name: &str) -> Option { .or_else(|| CATEGORIES.iter().flat_map(|c| builtin(c, s.default_units())).find(|p| p.name.eq_ignore_ascii_case(name))) } +/// The preset the `preset` param of `cmd` names, looked up in the category `presetCategory` names +/// when it is given ([`category`]) and with [`find`] otherwise; the starting settings without +/// `preset`. A `preset` or `presetCategory` that is not a string, a `presetCategory` that names no +/// category, and a `presetCategory` without a `preset` are errors, except in a replay, which reads +/// a saved step as earlier versions did: such a value is left out, and an unknown category finds no +/// preset. +fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { + if s.replaying() { + let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) }; + let found = match str_param(p, "presetCategory") { + Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), + None => find(s, name), + }; + return found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)"))); + } + let name = text_param(p, "preset", cmd)?; + let wanted = text_param(p, "presetCategory", cmd)? + .map(|c| { + category_names() + .find(|n| n.eq_ignore_ascii_case(c)) + .ok_or_else(|| bad(cmd, format!("unknown category `{c}` ({})", category_names().collect::>().join(", ")))) + }) + .transpose()?; + let Some(name) = name else { + return match wanted { + Some(_) => Err(bad(cmd, "presetCategory needs a preset")), + None => Ok(s.default_settings()), + }; + }; + let found = match wanted { + Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), + None => find(s, name), + }; + found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)"))) +} + impl Session { /// New Document's starting settings: Letter in Preferences ▸ Units ▸ General. fn default_settings(&self) -> DocSettings { @@ -871,10 +907,7 @@ const RECENT: usize = 12; /// `file.new`: a new document from a preset and/or explicit settings. pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { const C: &str = "file.new"; - let base = match str_param(p, "preset") { - Some(name) => find(s, name).ok_or_else(|| bad(C, format!("no preset called `{name}` (see file.newPresets)")))?, - None => s.default_settings(), - }; + let base = preset_param(s, p, C)?; // A preset keeps its name in Recent unless its size changed (turning it doesn't count). let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); let size = str_param(p, "preset").map(|_| sorted(&base)); @@ -911,9 +944,14 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { super::newart::reset(s); } // Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both - // are views of the whole app, so Default leaves them as they are. + // are views of the whole app, so Default leaves them as they are. A script's run turns it on + // when the run ends, and not at all when the run fails. if settings.preview_mode == PreviewMode::Overprint { - s.execute("view.overprintPreview", &json!({ "on": true }))?; + if s.script_in_run { + s.overprint_after_run = true; + } else { + s.execute("view.overprintPreview", &json!({ "on": true }))?; + } } remember(s, &settings); let mut out = json!({ "index": i, "previewMode": settings.preview_mode.id() }); @@ -959,10 +997,7 @@ fn save(s: &mut Session, p: &Value) -> Result { .map(str::trim) .filter(|n| !n.is_empty() && n.chars().count() <= 64) .ok_or_else(|| bad(C, "give the preset a name (1–64 characters)"))?; - let base = match str_param(p, "preset") { - Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?, - None => s.default_settings(), - }; + let base = preset_param(s, p, C)?; let mut preset = base.with_params_inner(p, C, s.replaying())?; preset.name = name.to_string(); let saved = &mut s.prefs.new_doc_presets; @@ -1103,8 +1138,11 @@ impl Session { // them, so the new document's assigned profiles draw and are saved with it. let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?; // Linked images in its symbols, patterns and brushes are read from their files, as placing - // a document reads them. - super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false); + // a document reads them. They are part of the profile, so a script's gate does not apply to + // them either; the automation roots in force still do. + crate::file_access::app_folder_read(|| { + super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false); + }); warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc)); Ok(Some(ReadProfile { doc, file, warnings })) } diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 2c875762a6..413405ba4f 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -35,10 +35,10 @@ pub(crate) use align::choice; pub(crate) use arrange::group_nodes; pub(crate) use bounds::{bounds_rewrite, object_bounds_transform}; pub use commands::specs; -pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip}; +pub(super) use compound::{as_clipping_path, copy_transparency, make_clipping_path, release_clip}; pub(crate) use pixelgrid::{ - align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, - snap_if_aligned, snap_symbol_art, + align_new_object, aligned_symbol_transforms, can_align, keep_aligned_in, keep_aligned_in_with, keep_compound_aligned, keep_pixel_aligned, + keep_symbol_instances_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned, snap_symbol_art, }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, nudge_step, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index a0f292fecf..8ed4656295 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -105,6 +105,53 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result { Ok(json!({ "id": gid.0 })) } +/// `object.newGroup`: an empty group, or with `compound` an empty compound path, in a layer or a +/// group (default: the current layer), on top of its contents or at `index` (0 = bottom; refused +/// in an Image Trace object, whose source image stays at the bottom). The selection stays as it is. +pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.newGroup"; + // Only an omitted key takes its default; `null` is refused like any other bad value. + let compound = match p.get("compound") { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad(C, "compound must be true or false"))?, + }; + let st = s.doc()?; + let parent = match p.get("parent") { + None => st.current_layer().or_else(|| st.doc.default_layer()).ok_or_else(|| bad(C, "the document has no layer"))?, + Some(v) => NodeId(v.as_u64().ok_or_else(|| bad(C, "parent must be a layer or group id"))?), + }; + let index = match p.get("index") { + None => usize::MAX, + Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(C, "index must be a whole number"))?, + }; + let d = &st.doc; + let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) }; + if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() { + return Err(bad(C, format!("{} is not a layer or group", parent.0))); + } + if !d.is_editable(parent) { + return Err(bad(C, "the layer or group is hidden or locked")); + } + // An Image Trace object keeps its source image first; a group below it would end the tracing. + if index == 0 && crate::cmd::is_trace_group(n) { + return Err(bad(C, "index 0 of an Image Trace object is its source image; use index 1 or more")); + } + let label = if compound { "Compound Path" } else { "Group" }; + let gid = s.edit(label, |d, _| { + let gid = d.alloc_id(); + let clips = d.node(parent).is_some_and(Node::clips); + let index = if clips { index.max(1) } else { index }; + let node = if compound { + Node::new(gid, NodeKind::Compound { children: Vec::new(), rule: vectorcraft_geom::FillRule::NonZero }) + } else { + Node::group(gid, Vec::new()) + }; + d.insert(Some(parent), index, node)?; + Ok(gid) + })?; + Ok(json!({ "id": gid.0 })) +} + /// Put `ids` (top-level objects, in paint order) in a new group where the front-most one was. pub(crate) fn group_nodes(d: &mut Document, ids: &[NodeId]) -> Result { if ids.is_empty() { diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 3b949efd8b..f20f4fc782 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -1,5 +1,5 @@ use super::align::{align, can_distribute, distribute, distribute_spacing}; -use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, send_to_current_layer, show_all, ungroup, unlock_all}; +use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, new_group, send_to_current_layer, show_all, ungroup, unlock_all}; use super::bounds::set_bounds; use super::compound::{clip_edit, clip_make, clip_release, compound_make, compound_release}; use super::pixelgrid::set_pixel_aligned; @@ -137,6 +137,15 @@ pub fn specs() -> Vec { has_selection, group ), + cmd!( + "object.newGroup", + "Group", + [], + None, + "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; 0 is refused in an Image Trace object, whose source image stays at the bottom; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is", + has_doc, + new_group + ), cmd!( "object.ungroup", "Ungroup", @@ -187,7 +196,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Compound Path"], Some("Cmd+8"), - "{ids?: [id…] (selected first; default: the selection)}", + "{ids?: [id…] (selected first; default: the selection)} make one compound path of the selected paths, with the backmost object's paint and transparency (opacity, blend mode, Isolate Blending, Knockout Group, Knockout Shape and opacity mask); a selected group's transparency applies to the backmost path in it, with the two opacities multiplied", has_selection, compound_make ), @@ -196,7 +205,7 @@ pub fn specs() -> Vec { "Release", ["Object", "Compound Path"], Some("Cmd+Alt+Shift+8"), - "{ids?: [id…] (selected first; default: the selection)} release the selected compound paths into their paths, each with the compound path's paint; a path of several subpaths (an SVG `d` with several `M`s) splits into one path per subpath", + "{ids?: [id…] (selected first; default: the selection)} release the selected compound paths into their paths, each with the compound path's paint and transparency (opacity, blend mode, Isolate Blending, Knockout Group, Knockout Shape and opacity mask; a path keeps its own opacity mask when the compound path has none); a path of several subpaths (an SVG `d` with several `M`s) splits into one path per subpath", has_selection, compound_release ), diff --git a/crates/engine/src/cmd/object/compound.rs b/crates/engine/src/cmd/object/compound.rs index 4f4b0739c2..1d522531cd 100644 --- a/crates/engine/src/cmd/object/compound.rs +++ b/crates/engine/src/cmd/object/compound.rs @@ -12,7 +12,7 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result { let id = s.edit("Make Compound Path", |d, sel| { d.node(backmost).ok_or(EngineError::NoNode(backmost))?; let mut units: Vec>> = vec![]; - let mut appearance = None; + let mut backmost = None; // The compound path is pixel-aligned when any of its paths was, or any compound path whose // paths it takes; its paths snap with its stroke, so they do not keep the property themselves. let mut aligned = false; @@ -22,11 +22,19 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result { return Err(EngineError::Other("compound paths can only contain paths".into())); } n.walk(&mut |c| aligned |= c.extras().pixel_aligned); - compound_members(n, &mut appearance, &mut units); + compound_members(n, &mut backmost, &mut units); } let cid = d.alloc_id(); let mut c = Node::new(cid, NodeKind::Compound { children: vec![], rule: FillRule::NonZero }); - c.appearance = appearance.unwrap_or_default(); + // The compound path takes the paint and the transparency of the backmost object, its opacity + // mask included. A backmost path gives its mask up: mask art is stored art, and its ids are + // in the document once. + let mut mask_from = None; + if let Some(b) = &backmost { + c.appearance = b.appearance.clone(); + copy_transparency(&mut c, b); + mask_from = matches!(b.kind, NodeKind::Path { .. }).then_some(b.id); + } let ch = c.children_mut().ok_or(EngineError::NoNode(cid))?; // The paths in front run against the backmost one, so where they overlap it they cut holes // under the non-zero fill rule (#1197). A compound path's paths turn together, by its @@ -45,6 +53,9 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result { let pn = Arc::make_mut(&mut p); pn.appearance = Appearance::default().into(); pn.extras_mut().pixel_aligned = false; + if mask_from == Some(pn.id) { + pn.extras_mut().mask = None; + } if let NodeKind::Path { path, live, .. } = &mut pn.kind { *live = None; if flip { @@ -66,17 +77,50 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result { } /// The paths in `n` (a path, a compound path, or a group searched in depth) onto `out`, in paint -/// order: each path alone, a compound path's paths together. Into `paint` goes the appearance of -/// the backmost found so far: the path's own, or its compound path's, which is what painted it. A +/// order: each path alone, a compound path's paths together. Into `backmost` goes the backmost +/// path or compound path found so far, whose appearance and transparency are what painted it. A /// group has no paint of its own to give: a group of outlined type made a compound path that drew -/// nothing. -fn compound_members(n: &Node, paint: &mut Option>, out: &mut Vec>>) { +/// nothing. A group's transparency applies to all of its members, so the backmost found in it +/// takes that transparency too (see [`take_group_transparency`]). +fn compound_members(n: &Node, backmost: &mut Option, out: &mut Vec>>) { match (&n.kind, n.children()) { (NodeKind::Path { .. }, _) => out.push(vec![Arc::new(n.clone())]), (NodeKind::Compound { .. }, Some(paths)) if !paths.is_empty() => out.push(paths.clone()), - (_, children) => return children.into_iter().flatten().for_each(|c| compound_members(c, paint, out)), + (_, children) => { + let found = backmost.is_some(); + children.into_iter().flatten().for_each(|c| compound_members(c, backmost, out)); + if !found && let Some(b) = backmost { + take_group_transparency(b, n); + } + return; + } } - paint.get_or_insert_with(|| n.appearance.clone()); + backmost.get_or_insert_with(|| n.clone()); +} + +/// Give `member` the transparency of `group`, which holds it: the two opacities multiply, and the +/// group's blend mode, Knockout Group and opacity mask apply where the member has none of its own. +/// Isolate Blending and Knockout Shape are on when either has them on. +fn take_group_transparency(member: &mut Node, group: &Node) { + member.opacity *= group.opacity; + if member.blend == Default::default() { + member.blend = group.blend; + } + if member.knockout == Default::default() { + member.knockout = group.knockout; + } + member.isolate |= group.isolate; + member.knockout_shape |= group.knockout_shape; + if member.extras().mask.is_none() && group.extras().mask.is_some() { + member.extras_mut().mask = group.extras().mask.clone(); + } +} + +/// Give `to` the object-level transparency of `from` (Transparency panel): its opacity, blend +/// mode, Isolate Blending, Knockout Group, Knockout Shape and opacity mask. +pub(crate) fn copy_transparency(to: &mut Node, from: &Node) { + (to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = (from.opacity, from.blend, from.isolate, from.knockout, from.knockout_shape); + to.extras_mut().mask = from.extras().mask.clone(); } /// Is `n` a compound path to release: a compound path, or a path of several subpaths (an SVG `d` @@ -105,9 +149,25 @@ pub(super) fn compound_release(s: &mut Session, _: &Value) -> Result { let mut parts = vec![]; match &n.kind { NodeKind::Compound { children, .. } => { - for c in children { + for (k, c) in children.iter().enumerate() { let mut c = (**c).clone(); c.appearance = n.appearance.clone(); + // A path keeps its own opacity mask when the compound path has none. + let own_mask = c.extras().mask.clone(); + copy_transparency(&mut c, &n); + if n.extras().mask.is_none() && own_mask.is_some() { + c.extras_mut().mask = own_mask; + } + // Each path keeps the compound path's opacity mask; after the first, a copy + // of its art with ids of its own. + if k > 0 + && let Some(m) = n.extras().mask.as_deref() + { + let art = Arc::new(d.reid(&m.art)); + if let Some(mask) = c.extras_if_any().and_then(|e| e.mask.as_mut()) { + mask.art = art; + } + } // Each path keeps the compound path's pixel-aligned property. if n.extras().pixel_aligned { c.extras_mut().pixel_aligned = true; diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 5b0d47baa2..72fc1a93da 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -402,6 +402,15 @@ fn snap_instance(n: &mut Node, natural: &HashMap) { /// pixel-aligned objects and the instances of pixel-aligned symbols in them to the pixel grid /// again. pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { + if ids.is_empty() { + return; + } + let natural = aligned_symbol_transforms(doc); + keep_aligned_in_with(doc, ids, &natural); +} + +/// [`keep_aligned_in`] with the symbols' natural-size transforms from [`aligned_symbol_transforms`]. +pub(crate) fn keep_aligned_in_with(doc: &mut Document, ids: &[NodeId], natural: &HashMap) { for id in ids { if doc.node(*id).is_some_and(holds_aligned) && let Some(n) = doc.node_mut(*id) @@ -409,20 +418,42 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { keep_pixel_aligned(n, Scaling::default()); } } - let aligned = doc.pixel_aligned_symbols(); - if aligned.is_empty() { + if natural.is_empty() { return; } - let natural: HashMap = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect(); for id in ids { - if doc.node(*id).is_some_and(|n| holds_instance(n, &natural)) + if doc.node(*id).is_some_and(|n| holds_instance(n, natural)) && let Some(n) = doc.node_mut(*id) { - snap_instances_in(n, &natural); + snap_instances_in(n, natural); } } } +/// The natural-size transform of each symbol aligned to the pixel grid, by name. +pub(crate) fn aligned_symbol_transforms(doc: &Document) -> HashMap { + doc.pixel_aligned_symbols() + .into_iter() + .map(|name| { + let xf = doc.symbol_natural_xf(&name); + (name, xf) + }) + .collect() +} + +/// Snap the natural-size instances of the symbols in `natural` that object `id` holds to the pixel +/// grid again, except in a symbol's editing layer, whose instances the outer symbol places. +pub(crate) fn keep_symbol_instances_aligned(doc: &mut Document, id: NodeId, natural: &HashMap) { + if natural.is_empty() || doc.symbol_edit.as_ref().is_some_and(|e| doc.layer_of(id) == Some(e.layer)) { + return; + } + if doc.node(id).is_some_and(|n| holds_instance(n, natural)) + && let Some(n) = doc.node_mut(id) + { + snap_instances_in(n, natural); + } +} + /// The objects of `after` that differ from their counterparts in `before` (or are new) and are /// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the /// walk stops: [`keep_pixel_aligned`] visits what it holds. diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index 299ed5f49c..daa5277633 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -467,6 +467,30 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Vec { placed } +/// The Objects on Path groups in object `id` and inside it, outer ones first; empty when it holds +/// none. +pub(crate) fn groups_in(doc: &Document, id: NodeId) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + if is_objects_on_path(n) { + out.push(n.id); + } + for c in n.children().into_iter().flatten() { + walk(c, out); + } + } + let mut out = vec![]; + if let Some(n) = doc.node(id) { + walk(n, &mut out); + } + out +} + +/// Put the objects of `groups` (outer ones first, from [`groups_in`]) back on their paths, inner +/// groups first, as [`refresh`] does. Returns the groups that placing changed. +pub(crate) fn place_groups(doc: &mut Document, groups: &[NodeId]) -> Vec { + groups.iter().rev().copied().filter(|id| place_in(doc, *id)).collect() +} + /// Members of the group `id` that the edit replaced with new art at the same index keep their /// place on the path ([`ObjectsOnPath::follow_replacements`]). fn follow_replacements(before: &Document, doc: &mut Document, id: NodeId) { diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 2a61f7fb74..73daebcbff 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), or with an opacity alone how many took the opacity}", + "{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?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), 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) ), @@ -948,6 +948,22 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) apply_paint_opacity(s, p, Some(paint), None, fill) } +pub(crate) fn object_only(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if !switch_or(p, "objectOnly", false, cmd)? { + return run(s); + } + if (!names(p, "ids") && !names(p, "id")) || asks_defaults_only(p) { + return Err(bad(cmd, "objectOnly needs ids or id and cannot be combined with defaultsOnly")); + } + let kept = (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone(), s.pending_paint.clone()); + let result = run(s); + (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors, s.pending_paint) = kept; + if result.is_ok() { + s.note_defaults_only(); + } + result +} + /// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or /// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points' /// own opacity for a fill (with no paint or a solid color), nothing on a target without that item. diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 433c69202c..0f604d81f1 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -384,6 +384,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result Result<()> check_effect_color(id, effect, params)?; check_effect_channel(id, effect, params)?; check_effect_center(id, effect, params)?; + check_effect_halftone_style(id, effect, params)?; check_effect_pathfinder(id, effect, params) } +/// The `style` in `params` of Vector Halftone (`effect`), as command `id` was given it: a parameter +/// error unless it names Custom or one of the named styles, in any letter case. `effect.apply` and +/// `effect.setParams` run this themselves before they edit, as they run [`check_effect_channel`]. +pub(crate) fn check_effect_halftone_style(id: &str, effect: &str, params: &Value) -> Result<()> { + use vectorcraft_render::effects::addons::halftone::{HALFTONE, style}; + let Some(v) = params.get("style") else { return Ok(()) }; + if effect != HALFTONE || v.as_str().and_then(style).is_some() { + return Ok(()); + } + Err(bad(id, "`style` must be one of custom, grid, gridAngle, gridDots, gridDotsAngle")) +} + /// The Pathfinder Options in `params` of a Pathfinder effect (`effect`), as command `id` was given /// them: `precision` a number of points from 0.001 to 10, and `removeRedundantPoints` and /// `removeUnpainted` true or false. `effect.apply` and `effect.setParams` run this themselves @@ -1089,6 +1102,9 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> { /// `command.batch` or `action.batch` step aren't checked (running it reports that), however deep they go. fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { let Some(spec) = find_command(id) else { return Ok(()) }; + if id == "addon.document.floodFillArtboards" && !params.is_null() && !params.is_object() { + return Err(bad(id, "params must be an object or null")); + } if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) = (id, super::effectcmd::requested_effect(params), params.get("params")) { diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index a6f85d0c46..190c8b5810 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1921,6 +1921,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo .copied() .filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor))) .collect(); + let clipped = super::edit::clipped_ancestors(d, whole_ids.iter().chain(sel.keys()).chain(segments.keys()).copied()); // The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`. let compounds: BTreeSet = if keep_empty { BTreeSet::new() @@ -2002,6 +2003,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo d.remove(p)?; } } + super::edit::release_empty_clips(d, clipped); selection.set(survivors); for (id, next) in following { if !next.is_empty() { diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index ba2b523f62..949b470263 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -841,6 +841,15 @@ fn place(s: &mut Session, p: &Value) -> Result { Some(read) => read, None => prepare(s, p)?.read()?, }; + let image = match read.loaded.art { + Art::Image(..) => read.loaded.link.is_some(), + Art::Dcs(_) => true, + _ => false, + }; + if s.image_only.get().is_some() && !image { + s.image_only.set(Some(false)); + return Err(bad(PLACE, "the file is not an image")); + } apply(s, read) } diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index c8a3c2b46a..33b38e567b 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -134,6 +134,9 @@ pub fn describe(p: &Plugin) -> Value { if m.appearance_output { v["appearanceOutput"] = json!(true); } + if !m.events.is_empty() { + v["events"] = json!(m.events); + } if let Some(script) = p.script() { v["runtime"] = json!(m.runtime.name()); v["script"] = json!(script); @@ -977,6 +980,8 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[ (&["View"], "Show Corner Widget"), (&["View"], "Show Live Paint Gaps"), (&["View"], "Hide Live Paint Gaps"), + (&["View"], "Show Curvature Comb"), + (&["View"], "Hide Curvature Comb"), (&["View"], "Guides"), (&["View"], "Smart Guides"), (&["View"], "Perspective Grid"), @@ -1546,6 +1551,7 @@ fn install(s: &mut Session, p: &Value) -> Result { s.store_disabled_plugins_in(&turn); } drop(turn); + s.plugins_changed_for_events(); let mut v = describe_installed(&installed); if !unknown.is_empty() { v["unknownCommands"] = json!(unknown); @@ -2313,12 +2319,17 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result { Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::>()})) } -fn info(_: &mut Session, p: &Value) -> Result { +fn info(s: &mut Session, p: &Value) -> Result { let plugin = plugin_by_id("plugin.info", p)?; let mut v = describe_installed(&plugin); v["manifest"] = serde_json::to_value(plugin.manifest()).unwrap_or(Value::Null); v["defaults"] = Value::Object(plugin.manifest().defaults()); v["lastError"] = json!(effect::last_error(plugin.id())); + if !plugin.manifest().events.is_empty() { + let (off, last) = s.plugin_event_status(&plugin); + v["eventsOff"] = json!(off); + v["lastEventError"] = json!(last); + } Ok(v) } @@ -2389,6 +2400,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { if !stored && !module && (!installed || !registry::remove(id)) { return Err(err(vectorcraft_plugins::Error::NotFound(id.into()))); } + s.plugins_changed_for_events(); Ok(json!({"removed": id})) } @@ -2418,7 +2430,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {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)}", + "{} → {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; events: it reacts to the events it names, see events), 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), events?: [\"selection.changed\"|\"document.opened\"|\"document.saved\"|\"layer.changed\"] (the events its vc_event handler is given after each change of that kind, see docs/plugins.md), 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 ), @@ -2427,7 +2439,7 @@ pub fn specs() -> Vec { "Plug-in Info", [], None, - "{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width)}", + "{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width), eventsOff? (with events: true once 3 handlers in a row failed, until the app starts again or a module is installed with its id again, the same module included), lastEventError? (with events: its handler's last failure, null)}", always, info ), diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 330f1ee5f1..3ab02a0719 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -463,6 +463,82 @@ pub(crate) fn call(s: &mut Session, run: &Calls, id: &str, args: &Value) -> std: Ok(value) } +/// The commands a plug-in's event handler may call ([`event_call`]), in order: each one only reads +/// the document and returns what it found. Every other command is refused before it runs. +pub(crate) const EVENT_READS: &[&str] = &[ + "dataset.list", + "graphicStyle.list", + "guide.list", + "image.info", + "object.blend.info", + "swatch.list", + "symbol.list", + "text.getRange", + "transparency.info", + "variable.list", +]; + +/// Makes call `id` with `args` from a plug-in's handler of event `event` ([`crate::plugin_events`]) +/// as [`call`] does, for a command in [`EVENT_READS`]; any other command is refused before it runs, +/// with an error that names the event. The call runs inside [`read_only`]: every document and the +/// session state the commands a plug-in may call change go back to how they were afterwards, and a +/// call that changed a document, its selection, current layer or layer rows, or which document is +/// active, is refused. +pub(crate) fn event_call(s: &mut Session, run: &Calls, event: &str, id: &str, args: &Value) -> std::result::Result { + if super::find_command(id).is_none() { + return Err(CallFailure { code: CALL_UNKNOWN_COMMAND, why: super::params::unknown_command(id).to_string() }); + } + if !EVENT_READS.contains(&id) { + return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` is not a command it may call") }); + } + let (r, changed) = read_only(s, |s| call(s, run, id, args)); + if changed { + return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` changed the document") }); + } + r +} + +/// Runs `f` and then puts every open document (its art, selection, current layer, rows and +/// history), which document is active and the session state the commands a plug-in may call change +/// ([`Saved`]) back to how they were → `f`'s result, and whether `f` changed a document, its +/// selection, current layer or layer rows, opened or closed one, or changed which one is active. +/// A document `f` changed is given a newer revision, so it redraws. +fn read_only(s: &mut Session, f: impl FnOnce(&mut Session) -> R) -> (R, bool) { + let saved = Saved::of(s); + let pending_paint = s.pending_paint.clone(); + let start = s.docs.clone(); + let active = s.active; + // A panic in `f` still puts everything back before it carries on. + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(s))); + let now = std::mem::replace(&mut s.docs, start); + let mut changed = s.active != active || now.len() != s.docs.len(); + for st in &mut s.docs { + let Some(n) = now.iter().find(|d| d.uid == st.uid) else { + changed = true; + continue; + }; + if n.revision != st.revision + || !Arc::ptr_eq(&n.doc, &st.doc) + || n.selection != st.selection + || n.active_layer != st.active_layer + || n.layer_rows != st.layer_rows + { + st.revision = st.revision.max(n.revision).saturating_add(1); + changed = true; + } + } + s.active = active; + saved.restore(s); + s.pending_paint = pending_paint; + if changed { + s.sync_front_profiles(); + } + match r { + Ok(r) => (r, changed), + Err(payload) => std::panic::resume_unwind(payload), + } +} + /// Runs command `id` with `args` in `s` with no file or folder readable or writable: every path the /// command reaches through the checked file access ([`crate::file_access`]) is refused, whatever /// param carries it. @@ -563,6 +639,8 @@ struct Saved { draw_mode: crate::DrawMode, draw_inside: Option, clipboard: crate::Clipboard, + clipboard_copied: bool, + copies: u64, untitled_counter: u32, explicit_undo_group: Option>, prefs: crate::Prefs, @@ -588,6 +666,8 @@ impl Saved { draw_mode: s.draw_mode, draw_inside: s.draw_inside, clipboard: s.clipboard.clone(), + clipboard_copied: s.clipboard_copied, + copies: s.copies, untitled_counter: s.untitled_counter, explicit_undo_group: s.explicit_undo_group.clone(), prefs: s.prefs.clone(), @@ -612,6 +692,8 @@ impl Saved { s.draw_mode = self.draw_mode; s.draw_inside = self.draw_inside; s.clipboard = self.clipboard; + s.clipboard_copied = self.clipboard_copied; + s.copies = self.copies; s.untitled_counter = self.untitled_counter; s.explicit_undo_group = self.explicit_undo_group; s.prefs = self.prefs; @@ -952,4 +1034,50 @@ mod tests { assert!(!names_key("{pathData: 1}", "path")); assert!(names_key("path: x", "path")); } + + /// Each command an event handler may call is one a plug-in may call and one the journal does + /// not record, listed once, in order. + #[test] + fn event_reads_are_reviewed_reads() { + for id in EVENT_READS { + let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") }; + assert_eq!(denied(spec), None, "{id} is refused to every plug-in"); + assert!(!spec.journal, "{id} is journaled"); + } + assert!(EVENT_READS.windows(2).all(|w| w[0] < w[1]), "in order, once each"); + } + + /// [`read_only`] puts back what its function changed: the document, its selection, the + /// preferences and the paint defaults, and says that the document changed; a function that + /// changes nothing is no change. + #[test] + fn read_only_puts_everything_back() { + use serde_json::json; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone(); + s.execute("select.none", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let (doc, revision, history) = (st.doc.clone(), st.revision, st.history.undo.len()); + let (prefs, paint) = (s.prefs.history_states, s.paint.clone()); + let ((), changed) = read_only(&mut s, |s| { + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + s.prefs.history_states += 1; + s.paint.stroke_width += 3.0; + }); + assert!(changed); + let st = s.doc().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &doc), "the same document"); + assert!(st.selection.objects.is_empty(), "the selection as it was"); + assert_eq!(st.history.undo.len(), history, "no undo step"); + assert!(st.revision > revision, "a newer revision, so it redraws"); + assert_eq!((s.prefs.history_states, &s.paint), (prefs, &paint)); + let revision = st.revision; + let ((), changed) = read_only(&mut s, |s| { + s.execute("variable.list", &json!({})).unwrap(); + }); + assert!(!changed, "a read changes nothing"); + assert_eq!(s.doc().unwrap().revision, revision); + } } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 21433cf412..5f970bb568 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -346,6 +346,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.mesh.movePoints", "object.mesh.setPointColor", "object.move", + "object.newGroup", "object.nudge", "object.objectsOnPath.attach", "object.objectsOnPath.detach", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 8420e67d30..0ee0340542 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -371,6 +371,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ ), p!("autoCollapseIconPanels", "User Interface", "", "Auto-Collapse Iconic Panels", bool), p!("toolGroupLabels", "User Interface", "", "Show Tool Group Labels", bool), + p!("uiToolIcons", "User Interface", "", "Tool Icons", choice(&[("current", "Current"), ("classic", "Classic")])), p!("openDocumentsAsTabs", "User Interface", "", "Open Documents As Tabs", bool), p!("largeTabs", "User Interface", "", "Large Tabs", bool), p!("systemTitleBar", "User Interface", "", "System Title Bar", bool), diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 5d37ec4e9c..77e6d03395 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -240,15 +240,7 @@ fn print(s: &mut Session, p: &Value) -> Result { // The artboards' background colors print behind the art. let filled = super::fileio::with_artboard_fills(&full, p, 0..full.artboards.len()).map_err(|e| bad(PRINT, e))?; let doc = &*filled; - // Raster effects print as images at the document's raster effects resolution. - let flat = super::rasterfx::flatten_raster_effects(doc); - let doc = flat.as_ref().unwrap_or(doc); let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite; - // The flattener expands pattern fills whose tile images need flattening, in the layers that print. - let tile_images = postscript - && !bitmap - && super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)? - .is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o)); let level = match p.get("level").filter(|v| postscript && !v.is_null()) { Some(v) => { let t = super::fileio::dxf::text(v); @@ -256,20 +248,32 @@ fn print(s: &mut Session, p: &Value) -> Result { } None => Level::default(), }; - // A job past `maxPages` is turned away before Print as Bitmap or a flattener preset prepares it, - // once the options are checked, when its pages follow from the artboards alone (composite, no - // `skipBlank`, artboards not ignored); the pages are counted again on the prepared art. - super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?; + // A job past `maxPages` is turned away before its raster effects are flattened and before Print + // as Bitmap or a flattener preset prepares it, once the options are checked, when its pages + // follow from the artboards alone (composite, no `skipBlank`, artboards not ignored); the pages + // are counted again on the prepared art. + let flattener = super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?; let by_artboards = !set.skip_blank && !matches!(set.artboards, vectorcraft_pdf::PrintArtboards::Ignore) && set.output.mode == vectorcraft_pdf::OutputMode::Composite; - if max_pages.is_some() - && by_artboards - && let Ok(pv) = vectorcraft_pdf::preview(doc, &set) - && too_many(pv.pages) - { - return Ok(json!({ "pages": pv.pages, "format": if postscript { "postscript" } else { "pdf" } })); + // Those pages are counted on the artboards with no art, which is not prepared for the count. + if max_pages.is_some() && by_artboards { + let mut bare = Document::new(0.0, 0.0); + bare.artboards = doc.artboards.clone(); + bare.setup.bleed = doc.setup.bleed; + bare.color_mode = doc.color_mode; + bare.layers.clear(); + let pv = vectorcraft_pdf::preview(&bare, &set).map_err(|e| pdf_error(PRINT, e))?; + if too_many(pv.pages) { + return Ok(json!({ "pages": pv.pages, "format": if postscript { "postscript" } else { "pdf" } })); + } } + // Raster effects print as images at the document's raster effects resolution. + let flat = super::rasterfx::flatten_raster_effects(doc); + let doc = flat.as_ref().unwrap_or(doc); + // The flattener expands pattern fills whose tile images need flattening, in the layers that print. + let tile_images = + postscript && !bitmap && flattener.is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o)); // Print as Bitmap and the flattener preset (Advanced) render and flatten it first. let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?; let path = str_param(p, "path"); diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index f035ff55f5..97dd890457 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -817,9 +817,17 @@ fn staged_all(out: &mut Document, nodes: &[Arc], report: &mut FlattenRepor /// type, images, symbol instances, live objects) and on single fills and strokes, in the layers, /// opacity masks, symbol definitions and pattern tiles. pub fn flatten_raster_effects(doc: &Document) -> Option { + #[cfg(test)] + FLATTENED.with(|n| n.set(n.get() + 1)); flatten(doc, &mut FlattenReport::new(Which::All, doc)) } +#[cfg(test)] +thread_local! { + /// How many times this thread called [`flatten_raster_effects`]. + pub(crate) static FLATTENED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// A copy of `doc` in which the objects with Photoshop-style raster effects (Radial Blur, Unsharp /// Mask…) or Rasterize are images as [`flatten_raster_effects`] makes them (SVG export: its /// filters draw the other raster effects live), or `None` when there are none. diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index a0ba6d243c..c2b6bec7b6 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo or swatch, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`), swatch?: {name, library?: swatch library id or name; \"document\" (default)} (the swatch the new color was picked from: of the swatches with the name, the first with the row's new color (as a color key); while it is a global or spot swatch and there is no globalAdjust (or limitTo is given), the row's art takes the swatch as with limitTo, linked to it at its tints; a process swatch, or a swatch or library that is not there, links nothing; with limitTo the library's swatch of the row's new color comes first; a global swatch of `group` that is rewritten with another color links nothing, and the row's art keeps the row's new color; a null `swatch` is no swatch, and any other `swatch` that is not {name, library?} is an error)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], swatchesNotFound?: [names of rows' `swatch` that are not there, which linked nothing], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Randomize Colors", [], None, - "{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}", + "{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys; a row's tint and swatch move with its new color and are dropped when the color changes}", always, randomize ), @@ -1535,6 +1535,9 @@ struct Row { /// `added`: with no current colors, the new color is a color added to the group, which it /// joins after the colors of the rows with current colors. added: bool, + /// `swatch`: the library key ("document" for the document's swatches) and the name of the + /// swatch the new color was picked from. + swatch: Option<(String, String)>, } /// The color model a row's colors take (`model`): each color's own, the new color's, or the @@ -1590,7 +1593,9 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> { match p.get("map") { Some(Value::Object(m)) => m .iter() - .map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false })) + .map(|(k, v)| { + Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false, swatch: None }) + }) .collect(), Some(Value::Array(rows)) => rows .iter() @@ -1603,7 +1608,21 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> { let tint = (super::number_or(r, "tint", 100.0, cmd)? / 100.0).clamp(0.0, 1.0) as f32; let model = ModelRule::param(r, cmd)?; let added = switch_or(r, "added", false, cmd)?; - Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added }) + let swatch = match r.get("swatch") { + None | Some(Value::Null) => None, + Some(w) => { + let name = w.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()); + let library = match w.get("library") { + None | Some(Value::Null) => Some(super::swatchlib::DOCUMENT_SWATCHES), + Some(l) => l.as_str().filter(|l| !l.is_empty()), + }; + match (name, library) { + (Some(n), Some(l)) => Some((l.to_string(), n.to_string())), + _ => return Err(bad(cmd, format!("a row's `swatch` must be {{name, library?}} with a name and a library id: {w}"))), + } + } + }; + Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added, swatch }) }) .collect(), _ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")), @@ -1681,7 +1700,9 @@ impl ColorMap { }; let i = out.rows.len(); let colors: Vec = r.from.iter().map(Match::color).collect(); - let link = links.get(n).cloned().flatten(); + // A global swatch of the rewritten group that takes another color links nothing, and the + // row recolors as it would with no swatch (its tint of the swatch left out). + let link = links.get(n).cloned().flatten().filter(|l| !(l.global && out.group.iter().any(|g| g.name == l.name && g.shown != l.color))); // Colors that can't link to the swatch take the row's tint of it too. let mapped = link.as_ref().filter(|l| l.global && l.tint < 1.0).map_or(to, |l| to.tinted(l.tint)); out.rows.push(RowMap::new(method, &colors, mapped).with_own_model(r.model.unwrap_or(model) != ModelRule::Keep)); @@ -1792,10 +1813,33 @@ fn apply(s: &mut Session, p: &Value) -> Result { Some(k) => super::swatchlib::library_swatches(s, k).unwrap_or_default(), None => vec![], }; + // A row's own `swatch`, the one its new color was picked from: of the swatches with its name, the + // first with the row's new color (as a color key, which rounds), when that one is a global or + // spot swatch and no Global Adjust changes the colors the row maps. A swatch or library that is + // not there (deleted since the pick) links nothing, and the result names it. Limit to Library's + // swatch of that color comes first. + let same = |a: Color, b: Color| ColorKey::of(&a) == ColorKey::of(&b); + let mut not_found: Vec = vec![]; + let picked: Vec> = rows + .iter() + .map(|r| { + let (lib, name) = r.swatch.as_ref()?; + let list = super::swatchlib::library_swatches(s, lib).filter(|l| l.iter().any(|w| w.name == *name)); + if list.is_none() { + not_found.push(name.clone()); + } + let to = r.new_color()?; + let w = list?.into_iter().find(|w| w.name == *name && w.paint.color().is_some_and(|c| same(c, to)))?; + Some(w).filter(|w| (w.global || w.spot) && mapped_adjust.is_identity()) + }) + .collect(); // A row with no current colors recolors nothing, so its swatch does not join the document. let row_swatches: Vec> = rows .iter() - .map(|r| r.new_color().filter(|_| !r.from.is_empty()).and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned())) + .zip(picked) + .map(|(r, own)| { + r.new_color().filter(|_| !r.from.is_empty()).and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned().or(own)) + }) .collect(); // While an object of a dynamic symbol instance's art is selected, the selection is refused, as // `selected_roots` refuses it. @@ -1872,19 +1916,28 @@ fn apply(s: &mut Session, p: &Value) -> Result { // The rows' library swatches join the document (one it has with that name and colour is // used as it is). let mut added = vec![]; + // Each library swatch added under a free name, with its library name: rows that took two + // library swatches of one name both find theirs again. + let mut renamed: Vec<(String, Swatch)> = vec![]; let links: Vec> = row_swatches .iter() .zip(&rows) .map(|(w, row)| { let w = w.as_ref()?; + // A swatch is the same one when its paint, Global and spot are. + let alike = |x: &Swatch| x.paint == w.paint && x.global == w.global && x.spot == w.spot; let name = match d.swatch(&w.name) { - Some(x) if x.paint == w.paint => w.name.clone(), - _ => { - let name = d.free_swatch_name(&w.name); - d.swatches.push(Swatch { name: name.clone(), ..w.clone() }); - added.push(name.clone()); - name - } + Some(x) if alike(x) => w.name.clone(), + _ => match renamed.iter().find(|(_, x)| x.name == w.name && alike(x)) { + Some((name, _)) => name.clone(), + None => { + let name = d.free_swatch_name(&w.name); + d.swatches.push(Swatch { name: name.clone(), ..w.clone() }); + added.push(name.clone()); + renamed.push((name.clone(), w.clone())); + name + } + }, }; let color = d.global_color(&name).filter(|_| w.global).or(w.paint.color())?; Some(Link { name, global: w.global, color, tint: row.tint }) @@ -1932,6 +1985,9 @@ fn apply(s: &mut Session, p: &Value) -> Result { })?; let mut out = json!({ "changed": changed, "swatches": added }); not_changed.report(&mut out); + if !not_found.is_empty() { + out["swatchesNotFound"] = json!(not_found); + } if let Some(e) = edit { e.defaults(s)?; out["relinked"] = json!(e.relinked()); @@ -1950,21 +2006,21 @@ fn randomize(_: &mut Session, p: &Value) -> Result { let rows = parse_rows(p, C)?; let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?); let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?); - // Each new color with its row's tint and model: a tint moves with its color, and goes when - // the color changes; a model moves with its color. A row with no current colors recolors - // nothing, so it keeps its new color and takes no other row's. + // Each new color with its row's tint, model and swatch: a tint and a swatch move with their + // color, and go when the color changes; a model moves with its color. A row with no current + // colors recolors nothing, so it keeps its new color and takes no other row's. let takes = |r: &Row| !r.from.is_empty() && r.new_color().is_some(); - let mut news: Vec<(Color, f32, Option)> = - rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect(); + type New = (Color, f32, Option, Option<(String, String)>); + let mut news: Vec = rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model, r.swatch.clone()))).collect(); if order { rng.shuffle(&mut news); } if saturation_brightness { news = news .into_iter() - .map(|(c, tint, model)| { + .map(|(c, tint, model, swatch)| { let n = rng.saturation_brightness(c); - (n, if ColorKey::of(&n) == ColorKey::of(&c) { tint } else { 1.0 }, model) + if ColorKey::of(&n) == ColorKey::of(&c) { (n, tint, model, swatch) } else { (n, 1.0, model, None) } }) .collect(); } @@ -1972,8 +2028,11 @@ fn randomize(_: &mut Session, p: &Value) -> Result { let map: Vec = rows .iter() .map(|r| { - let (to, tint, model) = - if takes(r) { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) }; + let (to, tint, model, swatch) = if takes(r) { + news.next().map_or((None, 1.0, None, None), |(c, t, m, w)| (Some(c), t, m, w)) + } else { + (r.to, r.tint, r.model, r.swatch.clone()) + }; let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::>(), "to": to.as_ref().map(key_str)}); if r.exclude { row["exclude"] = json!(true); @@ -1984,6 +2043,9 @@ fn randomize(_: &mut Session, p: &Value) -> Result { if let Some(m) = model { row["model"] = json!(m.id()); } + if let Some((library, name)) = swatch { + row["swatch"] = json!({"name": name, "library": library}); + } if r.added { row["added"] = json!(true); } diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 02994a9f8c..4936a06d74 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -419,8 +419,9 @@ impl FolderStore { /// Does `path` still name `file`? On Unix the two must be the same file (device and inode); on /// Windows they must be the same file (volume serial number and file index); elsewhere `path` - /// must exist. When either file can't be read, it does not. - fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool { + /// must exist. A link at `path` is not followed, so it names the link and not `file`. When + /// either file can't be read, it does not. + pub(crate) fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool { #[cfg(unix)] { use std::os::unix::fs::MetadataExt as _; @@ -431,8 +432,19 @@ impl FolderStore { } #[cfg(windows)] { + use std::os::windows::fs::OpenOptionsExt as _; + // FILE_FLAG_OPEN_REPARSE_POINT opens a link itself rather than its target, and + // FILE_FLAG_BACKUP_SEMANTICS lets a folder be opened, as `same_file::Handle::from_path` + // opens one. + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000; let opened = file.try_clone().and_then(same_file::Handle::from_file); - match (opened, same_file::Handle::from_path(path)) { + let named = std::fs::OpenOptions::new() + .read(true) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS) + .open(path) + .and_then(same_file::Handle::from_file); + match (opened, named) { (Ok(a), Ok(b)) => a == b, _ => false, } diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 37a661dfcb..ee2f3fcc5d 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 script file (.js, .mjs or .jsx) | 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), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), 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), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.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; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its 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", + "{path?: a script file (.js, .mjs or .jsx) | 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), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), 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); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.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), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.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 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; new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, unless a run of that engine takes it first with update(), which runs the handler during that run with no report or undo step of its own, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog 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; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its 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. Document.saveAs without options selects the format from the script's File name before resolving symbolic links; a name without a recognized extension uses the document's current format. imageCapture excludes source paths outside the automation read roots before filesystem probes. 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, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), 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 ), @@ -63,6 +63,24 @@ pub fn specs() -> Vec { always, engine_drop ), + cmd!( + query "script.palettes", + "List Script Palettes", + [], + None, + "{} the ScriptUI palettes that runs in named engines showed and have not closed, shown or hidden, in the order they were first shown, and the events that wait for a run; a hidden palette lists its controls as they were when it was hidden, until show() shows it again → {palettes: [{id, engine, title, visible, controls: [{index, kind, name, text, enabled, visible, value (check box, radio button, slider, progress bar), items and selection (lists)}]}], waiting: events waiting, limit: 16, waitingLimit: 64}", + always, + palettes + ), + cmd!( + query "script.palette.event", + "Script Palette Event", + [], + None, + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", + always, + palette_event + ), cmd!( query "script.console", "Script Console", @@ -95,7 +113,7 @@ pub fn specs() -> Vec { "Run Startup Scripts", [], None, - "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry", + "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry; in the app, a run lists the printers once when the runs are queued and each queued run may print to them, except with reason launch, whose runs list no printers and cannot print to a printer, and a queued run waits while the jobs the run before it prepared for a printer wait for Print or Cancel", always, startup_run ), @@ -268,6 +286,36 @@ fn engine_drop(s: &mut Session, p: &Value) -> Result { Ok(json!({"dropped": true, "name": name})) } +fn palettes(s: &mut Session, _: &Value) -> Result { + let list: Vec = s.script_palettes().iter().map(script::palettes::palette_json).collect(); + Ok(json!({ + "palettes": list, + "waiting": s.script_palette_events_waiting(), + "limit": script::palettes::MAX_PALETTES, + "waitingLimit": script::palettes::MAX_WAITING, + })) +} + +fn palette_event(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.palette.event"; + let Some(id) = p.get("palette").and_then(Value::as_u64) else { + return Err(bad(C, "`palette` must be a palette's id, as script.palettes lists it")); + }; + let Some(event) = p.get("event").and_then(Value::as_str) else { return Err(bad(C, "`event` must be click, change or close")) }; + let Some(palette) = s.script_palettes().iter().find(|q| q.id == id) else { return Err(bad(C, format!("there is no script palette {id}"))) }; + let event = script::palettes::parse_event(&palette.dialog, event, p.get("control"), p.get("value")).map_err(|e| bad(C, e))?; + // With nobody to ask, the event runs now or not at all: it is not kept for after an open undo + // group or a drag in another document, which a run cannot start in. + if !s.script_frames && s.palette_run_blocked() { + return Err(EngineError::Other(script::OPEN_EDIT.to_string())); + } + let waiting = s.script_palette_event(id, event).map_err(|e| bad(C, e))?; + if s.script_frames { + return Ok(json!({"waiting": true, "merged": waiting == script::Waiting::Merged, "waitingEvents": s.script_palette_events_waiting()})); + } + s.script_palette_run_waiting() +} + fn console_lines(s: &mut Session, _: &Value) -> Result { Ok(s.script_console().to_json()) } diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 931504dedb..0e937376bd 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -1034,8 +1034,7 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } let mut members = Members::of(sel); for (id, refs) in items { - // A segment pick's endpoints aren't selected anchors: start from none of them. - let segment_pick = sel.segments.remove(&id).is_some(); + let endpoints = sel.segments.remove(&id).and_then(|segments| segment_endpoints(d, id, &segments, "select.anchorsMany").ok()); let all: BTreeSet = d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); // Anything but a path is selected, toggled or deselected as a whole. @@ -1049,8 +1048,10 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } // From the anchors selected now (all of them for a path selected as a whole). let now = match sel.partial(id) { - _ if segment_pick => BTreeSet::new(), - Some(a) => a.clone(), + Some(a) => match &endpoints { + Some(endpoints) => a.difference(endpoints).copied().collect(), + None => a.clone(), + }, None if members.contains(id) => all.clone(), None => BTreeSet::new(), }; diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index 16684a3284..6b447fca7c 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -15,6 +15,16 @@ const MAX_CELLS: usize = 10_000; /// The most objects the copies may hold in all, counting every object inside each copy. const MAX_COPIED_OBJECTS: usize = 250_000; const EPS: f64 = 1e-9; +/// How far past a whole point a place may be and still count as on it, in points. +const GRID_EPS: f64 = 1e-6; + +/// Whether `n` or an object in it, the art of linked opacity masks included, is pixel-aligned: the +/// objects that the snap after a transform moves. +fn holds_pixel_aligned(n: &Node) -> bool { + n.extras().pixel_aligned + || n.children().is_some_and(|cs| cs.iter().any(|c| holds_pixel_aligned(c))) + || n.extras().mask.as_ref().is_some_and(|m| m.linked && holds_pixel_aligned(&m.art)) +} pub fn specs() -> Vec { vec![cmd!( @@ -22,7 +32,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); when the selection holds a pixel-aligned object, every cell moves by whole points (the pitch is rounded up, with fill the first cell's place is rounded toward the sheet's inside and only cells that still fit are counted, and a turned cell turns about a center up to half a point right of and below its own, with extra pitch only between alternating columns or rows and fill reserving the turn offset on both axes only where turned cells fit), so the copies stay on the pixel grid and the objects in each copy keep their places against each other; otherwise gaps are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; a single cell that neither moves nor groups the artwork and leaves the selection unchanged adds no undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -166,8 +176,75 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { } else { None }; + // With a pixel-aligned object in the selection, every cell moves by whole points, so the snap + // leaves each copy as it moved it and the objects in a copy keep their places against each other. + // The pitch and the first cell's place are rounded up, so neighbors never come closer than asked + // and the first cell stays inside the sheet. + let aligned = roots.iter().filter_map(|r| d.node(*r)).any(holds_pixel_aligned); + let whole = |v: f64| if aligned { (v - GRID_EPS).ceil() } else { v }; + // A half turn about the center maps x to 2 × center − x. On the pixel grid, twice the center is + // rounded up to whole points, so a turned copy also moves its objects by whole points; it then + // sits up to a point right of and below its cell, and the pitch and the fill make room for that. + let c2 = b.center().to_vec2() * 2.0; + let turn = if aligned && alt != Alternate::None { + let mut rounded = Vec2::new(whole(c2.x), whole(c2.y)); + if rounded.x < c2.x - EPS { + rounded.x += 1.0; + } + if rounded.y < c2.y - EPS { + rounded.y += 1.0; + } + rounded - c2 + } else { + Vec2::ZERO + }; + let center = (c2 + turn) / 2.0; + let clearance = match alt { + Alternate::Columns => Vec2::new(turn.x, 0.0), + Alternate::Rows => Vec2::new(0.0, turn.y), + Alternate::None => Vec2::ZERO, + }; + let (gx, gy) = if aligned { + let pitch = |v: f64| { + let rounded = whole(v).max(1.0); + if rounded < v - EPS { rounded + 1.0 } else { rounded } + }; + (pitch(w + gx + clearance.x) - w, pitch(h + gy + clearance.y) - h) + } else { + (gx, gy) + }; + let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| { + let raw = Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0); + let mut origin = Vec2::new(whole(raw.x), whole(raw.y)); + if b.x0 + origin.x < sh.x0 + m - EPS { + origin.x += 1.0; + } + if b.y0 + origin.y < sh.y0 + m - EPS { + origin.y += 1.0; + } + origin + }); let (rows, cols) = match anchor { - Some((sh, m)) => fill_counts(sh.width(), sh.height(), m, w, h, gx, gy), + Some((sh, m)) => { + let lead = origin - Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0); + let (sw, sh) = (sh.width() - lead.x - 2.0 * m, sh.height() - lead.y - 2.0 * m); + let (rows, cols) = fill_counts(sw, sh, 0.0, w, h, gx, gy); + // Turned cells have odd indices; an unturned cell may follow the last one that fits. + let alternating_count = |room, size, gap, shift, count: usize| count.min((fit_count(room - shift, size, gap) / 2 * 2).saturating_add(1)); + match alt { + Alternate::Columns => { + let cols = alternating_count(sw, w, gx, turn.x, cols); + let turned_rows = fit_count(sh - turn.y, h, gy); + if cols > 1 && turned_rows > 0 { (rows.min(turned_rows), cols) } else { (rows, cols.min(1)) } + } + Alternate::Rows => { + let rows = alternating_count(sh, h, gy, turn.y, rows); + let turned_cols = fit_count(sw - turn.x, w, gx); + if rows > 1 && turned_cols > 0 { (rows, cols.min(turned_cols)) } else { (rows.min(1), cols) } + } + Alternate::None => (rows, cols), + } + } None => (rows, cols), }; if rows == 0 || cols == 0 { @@ -182,14 +259,20 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { if objects.saturating_mul(rows * cols - 1) > MAX_COPIED_OBJECTS { return Err(bad(CMD, format!("the copies would hold more than {MAX_COPIED_OBJECTS} objects"))); } - let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0)); + let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() }; + if rows == 1 && cols == 1 && origin == Vec2::ZERO && roots.len() == 1 { + let selection = &s.doc()?.selection; + let mut next_selection = selection.clone(); + next_selection.set([roots[0]]); + if next_selection == *selection { + return Ok(json!({ "ids": [roots[0].0], "rows": 1, "columns": 1, "count": 1 })); + } + } let cells = layout(w, h, gx, gy, rows, cols, alt); - let center = b.center().to_vec2(); let place = |c: &Cell| -> Affine { let t = Affine::translate(origin + Vec2::new(c.dx, c.dy)); if c.turned { t * Affine::translate(center) * rotate_deg(180.0) * Affine::translate(-center) } else { t } }; - let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() }; let ids = s.edit("Step and Repeat", |d, sel| { if roots.len() > 1 { roots = vec![group_nodes(d, &roots)?]; diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index 133d79ff48..6114943a36 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -60,6 +60,158 @@ fn creates_the_grid_in_one_undo_step_and_undoes_cleanly() { assert!(ids[1..].iter().all(|i| d.node(NodeId(*i)).is_none())); } +#[test] +fn a_single_unchanged_cell_keeps_undo_and_redo() { + for fill in [false, true] { + let (mut s, id) = setup(); + let copies = s.execute(CMD, &json!({"columns": 2})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let steps = undo_steps(&s); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": {"x": 0, "y": 0, "width": 50, "height": 30}})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(undo_steps(&s), steps); + assert_eq!(s.doc().unwrap().history.redo.len(), redo); + s.execute("edit.redo", &json!({})).unwrap(); + let copy = copies["ids"][1].as_u64().unwrap(); + assert_eq!(bounds(&s, copy), (50.0, 0.0, 100.0, 30.0)); + } +} + +#[test] +fn a_single_unchanged_cell_clears_the_layer_target_in_one_undo_step() { + for fill in [false, true] { + let (mut s, id) = setup(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + assert_eq!(before.objects, [NodeId(id)]); + assert_eq!(before.target, Some(layer)); + let steps = undo_steps(&s); + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + let mut expected = before.clone(); + expected.set([NodeId(id)]); + assert_eq!(s.doc().unwrap().selection, expected); + assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection, before); + assert_eq!(undo_steps(&s), steps); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection, expected); + assert_eq!(undo_steps(&s), steps + 1); + } +} + +#[test] +fn a_single_unchanged_cell_records_the_resolved_patterns_setting() { + for fill in [false, true] { + for patterns in [false, true] { + let (mut s, id) = setup(); + s.execute("object.pattern.make", &json!({"name": "Dots", "width": 50, "height": 30})).unwrap(); + s.execute("object.pattern.done", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "swatch": "Dots"})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.prefs.transform_pattern_tiles = patterns; + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + for explicit in [false, true] { + let mut params = json!({"fill": fill, "sheet": sheet}); + let expected = if explicit { !patterns } else { patterns }; + if explicit { + params["patterns"] = json!(expected); + } + let start = s.journal.len(); + let steps = undo_steps(&s); + let r = s.execute(CMD, ¶ms).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + params["patterns"] = json!(expected); + assert_eq!(s.journal_for_action(start), [(CMD.to_string(), params)]); + assert_eq!(undo_steps(&s), steps); + } + } + } +} + +#[test] +fn a_single_unchanged_cell_selects_the_compound_in_one_undo_step() { + for fill in [false, true] { + let (mut s, member) = setup(); + let inner_params = json!({"x": 10, "y": 5, "width": 20, "height": 10}); + let inner = s.execute("shape.rectangle", &inner_params).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [member, inner]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let before = bounds(&s, compound); + s.execute(CMD, &json!({"columns": 2})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.select(|_, sel| sel.set([NodeId(member)])).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(member)]); + let steps = undo_steps(&s); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [compound], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(compound)]); + assert_eq!(bounds(&s, compound), before); + assert_eq!(undo_steps(&s), steps + 1); + assert!(s.doc().unwrap().history.redo.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(member)]); + assert_eq!(bounds(&s, compound), before); + assert_eq!(undo_steps(&s), steps); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(compound)]); + assert_eq!(bounds(&s, compound), before); + assert_eq!(undo_steps(&s), steps + 1); + } +} + +#[test] +fn a_single_unchanged_cell_selects_the_whole_path_in_one_undo_step() { + for fill in [false, true] { + let (mut s, id) = setup(); + let id = NodeId(id); + s.select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 0), (0, 1)].into_iter().collect()); + }) + .unwrap(); + let before = s.doc().unwrap().selection.clone(); + let steps = undo_steps(&s); + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [id.0], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert!(s.doc().unwrap().selection.anchors.is_empty()); + assert!(s.doc().unwrap().selection.segments.is_empty()); + assert_eq!(bounds(&s, id.0), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection, before); + assert_eq!(undo_steps(&s), steps); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert!(s.doc().unwrap().selection.anchors.is_empty()); + assert_eq!(undo_steps(&s), steps + 1); + } +} + +#[test] +fn a_single_moved_cell_records_an_undo_step() { + let (mut s, id) = setup(); + let steps = undo_steps(&s); + let r = s.execute(CMD, &json!({"fill": true, "sheet": {"x": 5, "y": 5, "width": 50, "height": 30}})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(bounds(&s, id), (5.0, 5.0, 55.0, 35.0)); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0)); +} + #[test] fn fill_sheet_with_margin_moves_the_first_copy_to_the_corner() { let (mut s, _) = setup(); @@ -211,6 +363,285 @@ fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_ assert!((pitch - pitch.round()).abs() < 1e-9); } +#[test] +fn pixel_aligned_pitch_preserves_requested_gaps_near_whole_points() { + for gap in [0.0, 0.25, -0.25] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let params = json!({"x": 0, "y": 0, "width": 50.0000005 - gap, "height": 30.0000005 - gap}); + let cut = s.execute("shape.rectangle", ¶ms).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 2, "gap": gap, "cutId": cut})).unwrap(); + assert_eq!(r["count"], json!(4)); + let d = &s.doc().unwrap().doc; + let cut_bounds = |id: &Value| { + let group = d.node(NodeId(id.as_u64().unwrap())).unwrap(); + group.children().unwrap()[0].geometric_bounds().unwrap() + }; + let ids = r["ids"].as_array().unwrap(); + for row in 0..2 { + let left = cut_bounds(&ids[row * 2]); + let right = cut_bounds(&ids[row * 2 + 1]); + assert!(right.x0 - left.x1 >= gap - EPS, "the horizontal gap shrank: {left:?} {right:?}"); + let pitch = right.x0 - left.x0; + assert!((pitch - pitch.round()).abs() < EPS); + } + for col in 0..2 { + let top = cut_bounds(&ids[col]); + let bottom = cut_bounds(&ids[col + 2]); + assert!(bottom.y0 - top.y1 >= gap - EPS, "the vertical gap shrank: {top:?} {bottom:?}"); + let pitch = bottom.y0 - top.y0; + assert!((pitch - pitch.round()).abs() < EPS); + } + } +} + +#[test] +fn a_pixel_aligned_cut_keeps_its_place_against_its_artwork_in_every_copy() { + let (mut s, cut) = setup(); + s.execute("object.setPixelAligned", &json!({"ids": [cut], "on": true})).unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 48, "height": 28})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 3, "gapX": 0.6, "gapY": 1.3, "cutId": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let inset = |id: &Value| { + let mut rects = vec![]; + d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| { + if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) { + rects.push(c.geometric_bounds().unwrap()); + } + }); + (rects[1].x0 - rects[0].x0, rects[1].y0 - rects[0].y0) + }; + let ids = r["ids"].as_array().unwrap(); + let first = inset(&ids[0]); + for id in &ids[1..] { + let (x, y) = inset(id); + assert!((x - first.0).abs() < 1e-9 && (y - first.1).abs() < 1e-9, "the artwork moved against the cut: {:?} against {first:?}", (x, y)); + } +} + +#[test] +fn pixel_aligned_art_stays_registered_in_turned_cells_and_gaps_never_shrink() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50.25, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"columns": 3, "gapX": 0.1, "rotate": "columns", "cutId": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let rects = |id: &Value| { + let mut rects = vec![]; + d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| { + if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) { + rects.push(c.geometric_bounds().unwrap()); + } + }); + (rects[0], rects[1]) + }; + let ids = r["ids"].as_array().unwrap(); + let (c0, a0) = rects(&ids[0]); + let (c1, a1) = rects(&ids[1]); + let (c2, a2) = rects(&ids[2]); + // The turned cell mirrors the art inside its cut; the next unturned cell repeats it. + assert!(((c1.x1 - a1.x1) - (a0.x0 - c0.x0)).abs() < 1e-9, "turned art moved against its cut: {c1:?} {a1:?}"); + assert!(((a2.x0 - c2.x0) - (a0.x0 - c0.x0)).abs() < 1e-9); + assert!(c2.x0 - c0.x0 > 2.0 * (50.25 + 0.1) - 1e-9, "the pitch was rounded down: {c2:?}"); + assert!(c1.x0 - c0.x1 >= 0.1 - 1e-9 && c2.x0 - c1.x1 >= 0.1 - 1e-9, "a gap next to the turned cell shrank: {c0:?} {c1:?} {c2:?}"); +} + +#[test] +fn turned_pixel_aligned_cells_stay_on_the_sheet() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.75})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": 101, "height": 30.75}); + let steps = undo_steps(&s); + let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!(r["columns"], json!(1)); + assert_eq!(r["count"], json!(1)); + assert_eq!(undo_steps(&s), steps + 1); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + assert!(matches!(s.doc().unwrap().doc.node(group).unwrap().kind, vectorcraft_doc::NodeKind::Group { .. })); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": 102, "height": 31.75}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!(r["columns"], json!(2)); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + assert!(b.x0 >= -1e-9 && b.y0 >= -1e-9 && b.x1 <= 102.0 + 1e-9 && b.y1 <= 31.75 + 1e-9, "a cell runs past the sheet: {b:?}"); + } +} + +#[test] +fn fill_keeps_rounded_turn_offsets_inside_the_sheet_near_whole_points() { + for (height, columns) in [(30.0000005, 1), (31.0000005, 2)] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.0000005})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": 100, "height": height}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(1), json!(columns), json!(columns))); + for id in r["ids"].as_array().unwrap() { + let (x0, y0, x1, y1) = bounds(&s, id.as_u64().unwrap()); + assert!(x0 >= -1e-9 && y0 >= -1e-9 && x1 <= 100.0 + 1e-9 && y1 <= height + 1e-9, "a cell runs past the sheet"); + } + } +} + +#[test] +fn fill_accepts_exact_fit_when_the_doubled_turn_center_has_roundoff() { + for (rotate, x, y, width, height, sw, sh, rows, columns) in + [("columns", 0.0, 0.1, 50.0, 29.8, 100.0, 29.8, 1, 2), ("rows", 0.1, 0.0, 29.8, 50.0, 29.8, 100.0, 2, 1)] + { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let params = json!({"x": x, "y": y, "width": width, "height": height}); + let cut = s.execute("shape.rectangle", ¶ms).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let b = s.doc().unwrap().doc.node(NodeId(cut)).unwrap().geometric_bounds().unwrap(); + let c2 = if rotate == "columns" { b.center().y * 2.0 } else { b.center().x * 2.0 }; + assert!(c2 > c2.round() && c2 - c2.round() < EPS); + let sheet = json!({"x": x, "y": y, "width": sw, "height": sh}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": rotate, "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(rows), json!(columns), json!(2))); + for id in r["ids"].as_array().unwrap() { + let (x0, y0, x1, y1) = bounds(&s, id.as_u64().unwrap()); + assert!(x0 >= x - EPS && y0 >= y - EPS && x1 <= x + sw + EPS && y1 <= y + sh + EPS, "a cell runs past the sheet"); + } + } +} + +#[test] +fn fill_reserves_turn_clearance_only_for_turned_cells() { + for (rotate, width, height, rows, columns) in [ + ("columns", 101.25, 31.0, 1, 1), + ("columns", 102.0, 31.0, 1, 2), + ("columns", 152.25, 31.0, 1, 3), + ("columns", 152.25, 30.75, 1, 1), + ("rows", 51.0, 61.75, 1, 1), + ("rows", 51.0, 62.0, 2, 1), + ("rows", 51.0, 92.75, 3, 1), + ("rows", 50.25, 92.75, 1, 1), + ] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50.25, "height": 30.75})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": width, "height": height}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": rotate, "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(rows), json!(columns)), "{rotate} on {width} by {height}"); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + assert!(b.x0 >= -1e-9 && b.y0 >= -1e-9 && b.x1 <= width + 1e-9 && b.y1 <= height + 1e-9, "a cell runs past the sheet: {b:?}"); + } + } +} + +#[test] +fn turned_columns_keep_the_vertical_pitch_without_turn_clearance() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.75})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 2, "gapY": 0.2, "rotate": "columns", "cutId": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let cut_bounds = |id: &Value| { + let mut rects = vec![]; + d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| { + if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) { + rects.push(c.geometric_bounds().unwrap()); + } + }); + rects[0] + }; + let ids = r["ids"].as_array().unwrap(); + for col in 0..2 { + let first = cut_bounds(&ids[col]); + let second = cut_bounds(&ids[col + 2]); + assert!((second.y0 - first.y0 - 31.0).abs() < 1e-9, "the vertical pitch includes turn clearance: {first:?} {second:?}"); + assert!(second.y0 - first.y1 >= 0.2 - 1e-9, "the vertical gap shrank: {first:?} {second:?}"); + } +} + +#[test] +fn fill_counts_only_the_pixel_aligned_copies_that_stay_on_the_sheet() { + let (mut s, id) = setup(); + // The 1 pt stroke puts the snapped rectangle at (0.5, 0.5), 50 by 30. + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + assert_eq!(bounds(&s, id), (0.5, 0.5, 50.5, 30.5)); + let steps = undo_steps(&s); + let r = s.execute(CMD, &json!({"fill": true, "gapX": 0.6, "sheet": {"x": 0.5, "y": 0.5, "width": 100.6, "height": 30}})).unwrap(); + assert_eq!(r["columns"], json!(1)); + assert_eq!(undo_steps(&s), steps); + let (mut s, id) = setup(); + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + let r = s.execute(CMD, &json!({"fill": true, "gapX": 0.6, "sheet": {"x": 0.5, "y": 0.5, "width": 101, "height": 30}})).unwrap(); + assert_eq!(r["columns"], json!(2)); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + assert!(b.x1 <= 101.5 + 1e-9, "a copy runs past the sheet: {b:?}"); + } +} + +#[test] +fn fill_rounds_pixel_aligned_origins_inside_the_sheet_near_whole_points() { + for (dx, dy) in [(0.0000005, 0.0), (0.0, 0.0000005), (-0.9999995, -0.9999995)] { + let (mut s, id) = setup(); + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + let (x, y, _, _) = bounds(&s, id); + let (sx, sy) = (x + dx, y + dy); + let steps = undo_steps(&s); + let tight = json!({"x": sx, "y": sy, "width": 50, "height": 30}); + assert!(s.execute(CMD, &json!({"fill": true, "sheet": tight})).is_err()); + assert_eq!(undo_steps(&s), steps); + let sheet = json!({"x": sx, "y": sy, "width": 51, "height": 31}); + let r = s.execute(CMD, &json!({"fill": true, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + let (x0, y0, x1, y1) = bounds(&s, id); + assert!(x0 >= sx && y0 >= sy && x1 <= sx + 51.0 && y1 <= sy + 31.0); + } +} + +#[test] +fn fill_accepts_exact_fit_when_the_origin_subtraction_has_roundoff() { + for (x, y, sx, sy) in [(1.2, 0.0, 2.2, 0.0), (0.0, 1.2, 0.0, 2.2), (1.2, 1.2, 2.2, 2.2)] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut_params = json!({"x": x, "y": y, "width": 50, "height": 30}); + let cut = s.execute("shape.rectangle", &cut_params).unwrap()["id"].as_u64().unwrap(); + let art_params = json!({"x": 10, "y": 5, "width": 20, "height": 20}); + let art = s.execute("shape.rectangle", &art_params).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": sx, "y": sy, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": true, "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(1), json!(1), json!(1))); + let (x0, y0, x1, y1) = bounds(&s, cut); + assert!((x0 - sx).abs() < EPS && (y0 - sy).abs() < EPS); + assert!((x1 - (sx + 50.0)).abs() < EPS && (y1 - (sy + 30.0)).abs() < EPS); + } +} + #[test] fn fill_picks_the_artboard_of_the_selection_not_of_the_cut_contour() { let first_x = |sheet: Option| { diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e1d64b2112..4ee4f01c10 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|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}", + "{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?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), 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/swatch.rs b/crates/engine/src/cmd/swatch.rs index 9916ba569c..4e8b25f3f4 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -977,6 +977,13 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result { Ok(relinked) })?; relink.defaults(s)?; + if to != name && !s.previewing { + let uid = s.doc()?.uid; + if s.swatch_renames.len() == crate::MAX_SWATCH_RENAMES { + s.swatch_renames.remove(0); + } + s.swatch_renames.push((uid, name, to.clone())); + } Ok(json!({"name": to, "relinked": relinked})) } diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 1a79fbfbc9..1d15de3a3b 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -509,6 +509,17 @@ impl<'a> ThreadIndex<'a> { pub(crate) fn threaded(&self, id: NodeId) -> bool { self.first.get(&id).and_then(|i| self.live.get(*i)).is_some_and(|n| *n >= 2) && text_of(self.doc, id).is_some() } + + /// The index in the document's threads of the first thread that lists `id`. + pub(crate) fn first_thread_index(&self, id: NodeId) -> Option { + self.first.get(&id).copied() + } + + /// [`story_of`] for `id`, its thread found through the index. + pub(crate) fn story(&self, id: NodeId) -> Vec { + let Some(thread) = self.first.get(&id).and_then(|i| self.doc.text_threads.get(*i)) else { return vec![] }; + story_in(self.doc, thread, id) + } } /// `ids` followed by the other frames of the threads they are in, each once, in thread order. diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 228d23a0f0..753c315a9a 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -37,7 +37,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 37] = [ +const REPLAY_ONLY: [(&str, &str); 38] = [ ("edit.copy", "artboard"), ("edit.cut", "artboard"), ("file.new", "created"), @@ -67,6 +67,7 @@ const REPLAY_ONLY: [(&str, &str); 37] = [ ("artboard.distribute", "activeArtboard"), ("artboard.distributeSpacing", "selectedArtboards"), ("artboard.distributeSpacing", "activeArtboard"), + ("addon.document.floodFillArtboards", "activeArtboard"), ("edit.copy", "selectedArtboards"), ("edit.copy", "art"), ("edit.cut", "selectedArtboards"), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index a3bc2b5876..8fe914a87f 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -151,6 +151,13 @@ impl AutomationRoots { Arc::new(Self { read: both(&self.read, &other.read), write: both(&self.write, &other.write) }) } + /// Whether these roots grant everything `other` grants: each root of `other` lies inside one of + /// these roots of the same kind. + pub(crate) fn contains(&self, other: &Self) -> bool { + let within = |mine: &[Root], theirs: &[Root]| theirs.iter().all(|o| mine.iter().any(|r| inside(&o.resolved, &r.resolved))); + within(&self.read, &other.read) && within(&self.write, &other.write) + } + /// The roots for people: `read A, B; write C` (`none` for a kind without any). pub fn describe(&self) -> String { let list = |roots: &[Root]| { @@ -283,6 +290,42 @@ impl ScopeHandle { Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } + /// Whether this scope allows everything `other` allows: its roots are none, or each root of + /// `other` lies inside one of its roots of the same kind, and its script gate is none or the + /// same gate. + fn covers(&self, other: &Self) -> bool { + let gate = match (&self.1, &other.1) { + (None, _) => true, + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (Some(_), None) => false, + }; + gate && self.roots_cover(other) + } + + /// Whether this scope's roots are none, or each root of `other` lies inside one of its roots + /// of the same kind. + fn roots_cover(&self, other: &Self) -> bool { + match (self.roots(), other.roots()) { + (None, _) => true, + (Some(a), Some(b)) => Arc::ptr_eq(&a, &b) || a.contains(&b), + (Some(_), None) => false, + } + } + + /// Whether this scope allows everything the calling thread's scope allows + /// ([`ScopeHandle::covers`]) and the calling thread's roots cover this scope's roots too, so + /// work run in the calling thread's scope reaches the same files this scope reaches. + pub(crate) fn matches_current(&self) -> bool { + let current = Self::capture(); + self.covers(¤t) && current.roots_cover(self) + } + + /// Whether this scope and `other` allow the same: each covers the other, and reads are exempt + /// from the gate in both or in neither. + pub fn same(&self, other: &Self) -> bool { + self.2 == other.2 && self.covers(other) && other.covers(self) + } + /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { let Self(scope, gate, exempt) = self; @@ -510,10 +553,43 @@ pub fn check_write(path: &str) -> Result<(), String> { Ok(()) } -/// [`check_write`] without recording `path` as written. +/// A check every write on this thread must pass as well, given the path as written or, at the +/// moment a checked write commits on Unix, the opened folder's real path with the file's name +/// ([`with_write_guard`]). +pub(crate) type WriteGuard = std::rc::Rc Result<(), String>>; + +thread_local! { + static WRITE_GUARD: RefCell> = const { RefCell::new(None) }; +} + +/// Puts the write guard it replaced back when dropped (also when `f` panics). +struct RestoreWriteGuard(Option); + +impl Drop for RestoreWriteGuard { + fn drop(&mut self) { + let previous = self.0.take(); + WRITE_GUARD.with(|g| *g.borrow_mut() = previous); + } +} + +/// Runs `f` with `guard` checked on every write it makes on this thread, again at the moment each +/// checked write commits, so a destination that is changed after an earlier check is checked as it +/// is then. +pub(crate) fn with_write_guard(guard: WriteGuard, f: impl FnOnce() -> T) -> T { + let _restore = RestoreWriteGuard(WRITE_GUARD.with(|g| g.replace(Some(guard)))); + f() +} + +fn check_write_guard(path: &Path) -> Result<(), String> { + WRITE_GUARD.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g(path)) +} + +/// [`check_write`] without adding `path` to the files a script run reports as written, for a +/// check made before anything is written. pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { current().map_or(Ok(()), |r| r.check(path, Access::Write))?; - check_gate(path, Access::Write) + check_gate(path, Access::Write)?; + check_write_guard(Path::new(path)) } /// [`check_write_unrecorded`] for `real`, the path of a file in a folder whose links have been @@ -522,12 +598,14 @@ pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { #[cfg(unix)] pub(crate) fn check_write_real(real: &Path) -> Result<(), String> { current().map_or(Ok(()), |r| r.check_real(real, Access::Write))?; - GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write)) + GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write))?; + check_write_guard(real) } -/// Whether a write here is checked: roots are in force, or a script's command runs. +/// Whether a write here is checked: roots are in force, a script's command runs, or a write guard +/// is in force ([`with_write_guard`]). pub(crate) fn writes_checked() -> bool { - current().is_some() || in_script_command() + current().is_some() || in_script_command() || WRITE_GUARD.with(|g| g.borrow().is_some()) } /// A file's modification time and length; `None` when there is no file at `path`. @@ -1571,4 +1649,31 @@ mod tests { assert_eq!(roots.check(&s(base.join("out/x.svg")), Access::Write), Ok(())); let _ = std::fs::remove_dir_all(base); } + + /// A checked write to a real path passes a script gate only inside the gate's write folder, and + /// only when every gate chained to it passes the path too. + #[cfg(unix)] + #[test] + fn a_checked_write_to_a_real_path_passes_every_chained_gate() { + let (base, _) = folders("check-real"); + let base = std::fs::canonicalize(&base).unwrap(); + let gate = |dir: &str| ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::of_folder(&base.join(dir)), + documents: vec![], + held: vec![], + linked: LinkedFiles::default(), + also: None, + }; + let (inside, outside) = (base.join("out/new.svg"), base.join("outside/new.svg")); + let denied = |p: &Path| Err(format!("Script file access denied: {}", p.display())); + assert_eq!(gate("out").check_real(&inside, Access::Write), Ok(())); + assert_eq!(gate("out").check_real(&outside, Access::Write), denied(&outside)); + assert_eq!(with_script_gate(gate("out"), || check_write_real(&inside)), Ok(()), "the running command's gate passes it"); + assert_eq!(with_script_gate(gate("out"), || check_write_real(&outside)), denied(&outside), "the running command's gate refuses it"); + let chained = gate("out").followed_by(Arc::new(gate("outside"))); + assert_eq!(chained.check_real(&inside, Access::Write), denied(&inside), "the chained gate refuses it"); + assert_eq!(chained.check_real(&outside, Access::Write), denied(&outside), "the first gate refuses it"); + let _ = std::fs::remove_dir_all(base); + } } diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index d921008611..1ede3c2509 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -19,11 +19,26 @@ pub struct Interaction { /// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an /// interaction runs its commands inside it. pub(crate) tool: bool, + /// A tool began or joined this interaction through `Action::Begin`. + pub(crate) tool_joined: bool, /// A replaced or canceled preview restores these new-art paints from before the interaction. pub(crate) paint: vectorcraft_tools::PaintDefaults, /// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put /// `paint` back, whichever preview is the latest. pub(crate) used_defaults_only: bool, + /// A Flood Fill Artboards preview ran: a cancel puts `paint` back and does not take the + /// selection's appearance as the new-art paints. + pub(crate) preserve_paint_on_cancel: bool, + /// The preview inherited new-art paints from a selection absent at interaction start: the + /// new-art paints from before that, which the next preview starts from. + pub(crate) inherited_preview_paint: Option, + /// A successful preview started from `inherited_preview_paint`: the new-art paints changed + /// during the interaction, so a cancel, or a commit after a failed preview, puts `paint` back. + pub(crate) inherited_preview_paint_used: bool, + /// The new-art paints before the successful previews that built on each other, with the + /// changes made outside the previews, and the paints the last of them left. A failed preview + /// puts back the first where a field still holds what the previews left. + pub(crate) last_preview_paint: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, /// An accepted batch preview uses these final paints after changing the document color mode. pub(crate) preview_paint: Option, /// Conversion of new-art paints waits until a color-mode preview is accepted. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5ceccf5920..31cfe000de 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5,6 +5,7 @@ //! server all go through [`Session::execute`]. Tools (pointer gestures) are hosted here too and //! reduce to commands, so every gesture is journaled and replayable. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod cmd; pub mod file_access; @@ -14,6 +15,7 @@ pub mod journal; pub mod link_watch; #[cfg(not(target_arch = "wasm32"))] pub mod packs; +pub mod plugin_events; pub mod schemas; pub mod steps; pub mod store; @@ -53,6 +55,9 @@ pub use vectorcraft_tools as tools; pub use vectorcraft_doc::MAX_COORD; const _: () = assert!(vectorcraft_doc::MAX_DEPTH == 32, "TOO_DEEP (and its catalog rows) names the cap"); +/// The maximum number of newest swatch renames a session keeps until they are taken. +pub(crate) const MAX_SWATCH_RENAMES: usize = 64; + pub struct Session { docs: Vec, active: Option, @@ -65,6 +70,10 @@ pub struct Session { pub fill_active: bool, /// Internal clipboard: the copied objects and the document resources they use. pub clipboard: Clipboard, + /// How many times Copy or Cut has put art, guides or artboards on [`Self::clipboard`]. + pub(crate) copies: u64, + /// [`Self::clipboard`] holds what the last Copy or Cut put there, not what an import put there. + pub(crate) clipboard_copied: bool, /// Executed commands (for actions and debugging), the most recent ones kept ([`Journal`]). pub journal: Journal, /// About the most memory the undo steps of all the open documents may keep together @@ -304,6 +313,9 @@ pub struct Session { /// appearance: the documents ([`DocState::uid`]) whose newest history step takes the colors the /// command finally left. pub(crate) batch_paint_docs: Vec, + /// Committed swatch renames as (document uid, old name, new name), in execution order until taken by the frontend. + /// The uid is [`DocState::uid`]; the record is never saved in documents or history. + pub(crate) swatch_renames: Vec<(u64, String, String)>, /// The composite fonts (lowercase names) that the open documents defined when the font /// database was last brought in step with them ([`cmd::compositefonts::sync`]). pub(crate) composite_names: Vec, @@ -317,6 +329,10 @@ pub struct Session { /// While [`Session::place_read`] runs `file.place`: the file read for it, which the command /// places instead of reading the file; `None` otherwise. pub(crate) place_hand_off: Option, + /// While a script places or relinks a file as an image: `Some(true)`, and `file.place` or + /// `links.relink` refuses a file that holds no image before the document changes, setting it to + /// `Some(false)`; `None` otherwise. + pub(crate) image_only: std::cell::Cell>, /// While [`Session::place_queue_read`] runs `file.place.queue`: the files read for it, which /// the command loads the place cursor with instead of reading them; `None` otherwise. pub(crate) queue_hand_off: Option, @@ -384,6 +400,12 @@ pub struct Session { pub(crate) script_style_trail: script::StyleTrail, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, + /// The ScriptUI palettes the named engines' runs showed, and the events that wait for a run + /// ([`script::palettes`]). + pub(crate) script_palettes: script::palettes::Palettes, + /// A script's `file.new` asked for Overprint Preview, which is turned on when the run ends and + /// is not turned on when the run fails. + pub(crate) overprint_after_run: bool, /// The one command a member of the script object model runs past /// [`script::refused_to_scripts`] while it is set: `file.print` for `Document.print`, after the /// member checked its options and its file. @@ -404,6 +426,13 @@ pub struct Session { /// While the active tool's actions run: their commands aren't "a command from outside the /// tool" ([`Session::after_command`]). pub(crate) in_tool_actions: bool, + /// The events plug-ins react to that wait for delivery, and how the documents were at the last + /// check ([`plugin_events`]). + pub(crate) plugin_events: plugin_events::PluginEvents, + /// The frontend delivers plug-in events by the frame ([`Session::deliver_plugin_events`]). Off, + /// each top-level command delivers them when it ends. When on, the frontend calls + /// [`Session::begin_plugin_event_frame`] once before each frame's deliveries. + pub plugin_event_frames: bool, /// The warnings of the previews that settling an interaction applied, while a top-level command /// or the tool's actions collect them ([`Session::collect_settled_warnings`]). settled_warnings: Option>, @@ -530,7 +559,7 @@ use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; pub(crate) use interaction::{HeldInteraction, PreviewCopies}; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; -pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs}; +pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs, ScriptPreference}; pub use sanity::TOO_DEEP; pub(crate) use sanity::{deselect_hidden, is_guide_path}; #[cfg(test)] diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs new file mode 100644 index 0000000000..4a85763667 --- /dev/null +++ b/crates/engine/src/plugin_events.rs @@ -0,0 +1,1029 @@ +//! Events plug-ins react to ([`vectorcraft_plugins::events`]): the session notices a changed +//! selection, current layer or set of layers by comparing each open document with how it was at the +//! last check, and hears of each successful open and save ([`Session::note_plugin_event`]). It then +//! calls the `vc_event` handler of each installed plug-in whose manifest names the event, after the +//! change has finished and outside any undo step. +//! +//! - A check runs after each top-level command, or when a frontend that sets +//! [`Session::plugin_event_frames`] delivers ([`Session::deliver_plugin_events`]), by the frame. +//! Changes between two checks are one event: a burst of selection changes is one +//! `selection.changed` with the final selection. No check or delivery runs while an interaction +//! is open (a drag being previewed); waiting events wait for it to end. A document opened or +//! created since the last check is compared with how it was when it was added +//! ([`Session::plugin_events_see_new_documents`]). +//! A check after commit or cancel records the settled state for plug-ins installed during the interaction. +//! - At most [`MAX_PENDING`] events wait; past that the oldest is dropped. An event raised while a +//! handler runs waits for the next delivery: handlers never run inside one another. +//! A frontend frame runs at most [`MAX_FRAME_HANDLERS`] handlers across all its deliveries, +//! after [`Session::begin_plugin_event_frame`] resets the budget. Runnable recipients still +//! waiting request another frame through the delivery's return value. +//! - A handler only reads. The host applies nothing it returns, and it may call only the commands +//! in [`super::cmd::plugin_call::EVENT_READS`]; any other call is refused with an error that names +//! the event, and what a call changes is put back ([`super::cmd::plugin_call::event_call`]). +//! - A handler that fails is reported once a streak; after +//! [`vectorcraft_plugins::events::MAX_EVENT_FAILURES`] failures in a row the plug-in's events stop +//! until the session ends, or until a module is installed under its id again. +//! - When no installed plug-in reacts to events, a check returns before comparing anything. + +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; +use std::hash::Hash; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, Selection}; +use vectorcraft_plugins::events::{Event, MAX_EVENT_FAILURES, MAX_EVENT_IDS}; +use vectorcraft_plugins::permissions::Permission; +use vectorcraft_plugins::{LogLevel, Plugin, registry}; + +use crate::Session; + +/// Most events that wait for delivery. +pub const MAX_PENDING: usize = 32; + +/// Most events kept after the queue dropped them for room, until the next delivery, for a +/// rollback to put back. +const MAX_EVICTED: usize = 1024; + +/// Most handlers called across all deliveries in one frontend frame. +pub const MAX_FRAME_HANDLERS: usize = 4; + +/// Most notices kept for the frontend to show; older ones are dropped. +pub const MAX_NOTICES: usize = 64; + +/// The reasons a `layer.changed` event gives, in the order it lists them. +pub const LAYER_REASONS: [&str; 5] = ["current", "added", "deleted", "reordered", "options"]; + +/// A document as the last check saw it. +struct Seen { + uid: u64, + doc: Arc, + selection: Selection, + layer: Option, +} + +/// A plug-in an event is for: its id, the hash of its module and its installation +/// ([`Plugin::serial`]), so a module removed and installed again is another recipient. +type Recipient = (String, String, u64); + +#[cfg(test)] +std::thread_local! { + pub(crate) static RECIPIENT_IDENTITIES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The recipient `p` is. +fn recipient(p: &Plugin) -> Recipient { + #[cfg(test)] + RECIPIENT_IDENTITIES.with(|count| count.set(count.get() + 1)); + (p.id().to_string(), p.hash().to_string(), p.serial()) +} + +/// An event waiting for delivery: what changed, in which document, and the plug-ins it is for +/// (those installed when it happened), each with the reasons of a `layer.changed` it was given. +#[derive(Clone, Debug, PartialEq)] +struct Pending { + event: Event, + document: u64, + to: Vec<(Recipient, Vec<&'static str>)>, + /// When it was queued ([`PluginEvents::queued`] then). + seq: u64, + /// The [`Pending::seq`] of the event that pushed this one out of the waiting queue, and whether + /// that event was a `document.opened`. + pushed_out_by: Option<(u64, bool)>, + /// Queued by a command of the running script, whose run has not ended yet + /// ([`Session::plugin_events_script_ended`]). + by_script: bool, +} + +impl Pending { + /// Whether this event is for `r`. + #[cfg(test)] + fn is_for(&self, r: &Recipient) -> bool { + self.to.iter().any(|(x, _)| x == r) + } + + /// The reasons of a `layer.changed` that `r` is given. + #[cfg(test)] + fn reasons_for(&self, r: &Recipient) -> &[&'static str] { + self.to.iter().find(|(x, _)| x == r).map_or(&[], |(_, reasons)| reasons.as_slice()) + } +} + +/// One plug-in's failed handlers in a row, for the installation `serial` of the module with `hash`. +#[derive(Clone, Debug, Default)] +struct Failures { + hash: String, + serial: u64, + count: u32, + disabled: bool, + last_error: Option, +} + +/// A line a handler wrote with `vc_log`, or a handler's failure, for the frontend to show. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Notice { + /// The plug-in's id and name. + pub plugin: String, + pub name: String, + /// The event its handler was given. + pub event: &'static str, + pub level: LogLevel, + /// The text, in English for a failure. + pub text: String, + /// For a failure, what failed, for the frontend to word in the interface language; `None` for + /// a line the handler wrote. + pub failure: Option, +} + +/// A failure a [`Notice`] reports. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Failure { + /// A handler failed with `error`, the first time in a row. + Handler { error: String }, + /// The plug-in's events stopped after `count` failed handlers in a row. + EventsOff { count: u32 }, +} + +impl Failure { + /// The English message with `{event}`, `{error}` and `{n}` placeholders, `one` or `other` by + /// the count. + pub const HANDLER: &'static str = "its {event} handler failed: {error}"; + pub const EVENTS_OFF_ONE: &'static str = + "its events are off until it is installed again or VectorCraft starts again, after {n} failed handler in a row"; + pub const EVENTS_OFF_OTHER: &'static str = + "its events are off until it is installed again or VectorCraft starts again, after {n} failed handlers in a row"; +} + +/// The session's plug-in event state. +#[derive(Default)] +pub struct PluginEvents { + seen: Vec, + /// The plug-ins that reacted to events when `seen` was taken. + seen_by: Vec, + pending: VecDeque, + /// The events dropped from `pending` since the last delivery, oldest first, which + /// [`Session::forget_plugin_opens_since`] puts back when a rollback frees room. + evicted: VecDeque, + /// The [`Pending::seq`] of each `document.opened` the running script's commands queued. + script_opens: HashSet, + /// How many events have been queued as their own entry. + queued: u64, + dispatching: bool, + frame_handlers: usize, + interaction_ended: bool, + failures: BTreeMap, + notices: VecDeque, + /// The installed plug-ins that react to events, as of a registry revision. + subscribers: Option<(u64, Vec>)>, + #[cfg(test)] + pub(crate) test_subscribers: Option>>, +} + +impl PluginEvents { + /// The installed plug-ins that react to events (none in Safe Mode). + fn subscribers(&mut self) -> Vec> { + #[cfg(test)] + if let Some(subs) = &self.test_subscribers { + return subs.clone(); + } + if vectorcraft_plugins::safe_mode::active() { + return Vec::new(); + } + let revision = registry::revision(); + if let Some((at, subs)) = &self.subscribers + && *at == revision + { + return subs.clone(); + } + let subs: Vec> = registry::list().into_iter().filter(|p| !p.manifest().events.is_empty()).collect(); + self.subscribers = Some((revision, subs.clone())); + subs + } + + /// Queues `event` for document `uid`, for the plug-ins `to`, with the reasons of a + /// `layer.changed`. A `selection.changed` or `layer.changed` already waiting for that document + /// takes it in: each plug-in in `to` is added, or adds the new reasons to the ones it was given, + /// so a plug-in is given only the reasons of the changes it was given. Past [`MAX_PENDING`] the + /// oldest event is dropped. + fn queue(&mut self, event: Event, uid: u64, reasons: Vec<&'static str>, to: Vec) { + if matches!(event, Event::SelectionChanged | Event::LayerChanged) + && let Some(p) = self.pending.iter_mut().find(|p| p.event == event && p.document == uid) + { + for r in to { + let i = match p.to.iter().position(|(x, _)| *x == r) { + Some(i) => i, + None => { + p.to.push((r, Vec::new())); + p.to.len() - 1 + } + }; + let given = &mut p.to[i].1; + for reason in &reasons { + if !given.contains(reason) { + given.push(*reason); + } + } + given.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r)); + } + return; + } + if self.pending.len() >= MAX_PENDING + && let Some(mut dropped) = self.pending.pop_front() + { + dropped.pushed_out_by = Some((self.queued, event == Event::DocumentOpened)); + log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); + // Kept until the next delivery, in case a rollback frees room for it again. + // When that store is full, an open goes first, since only opens are rolled back. + if self.evicted.len() >= MAX_EVICTED { + let at = self.evicted.iter().position(|p| p.event == Event::DocumentOpened).unwrap_or(0); + self.evicted.remove(at); + } + self.evicted.push_back(dropped); + } + let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); + self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, pushed_out_by: None, by_script: false }); + self.queued += 1; + self.prune_script_opens(); + } + + /// Drops the `document.opened` events, waiting or pushed out, whose [`Pending::seq`] `undone` + /// picks. The events those opens pushed out of the waiting queue return in their original + /// order, ahead of the events still waiting, while there is room. + fn drop_opens(&mut self, undone: impl Fn(u64) -> bool) { + let dropped = |p: &Pending| p.event == Event::DocumentOpened && undone(p.seq); + self.pending.retain(|p| !dropped(p)); + self.evicted.retain(|p| !dropped(p)); + let first = self.evicted.iter().filter(|p| p.pushed_out_by.is_some_and(|(seq, open)| open && undone(seq))).map(|p| p.seq).min(); + while self.pending.len() < MAX_PENDING + && let Some(at) = self.evicted.iter().rposition(|p| first.is_some_and(|seq| p.seq >= seq)) + && let Some(mut p) = self.evicted.remove(at) + { + p.pushed_out_by = None; + self.pending.push_front(p); + } + self.prune_script_opens(); + } + + /// Forgets the running script's opens that no waiting or pushed-out event refers to. + fn prune_script_opens(&mut self) { + if self.script_opens.is_empty() { + return; + } + let referenced: HashSet = + self.pending.iter().chain(self.evicted.iter()).flat_map(|p| std::iter::once(p.seq).chain(p.pushed_out_by.map(|(seq, _)| seq))).collect(); + self.script_opens.retain(|seq| referenced.contains(seq)); + } + + fn notice(&mut self, n: Notice) { + if self.notices.len() >= MAX_NOTICES { + self.notices.pop_front(); + } + self.notices.push_back(n); + } + + /// The failures of plug-in `p`, started again when a module was installed under its id since + /// they were recorded, the same module again included. + fn failures_of(&mut self, p: &Plugin) -> &mut Failures { + let f = self.failures.entry(p.id().to_string()).or_default(); + if !f.is_of(p) { + *f = Failures { hash: p.hash().to_string(), serial: p.serial(), ..Failures::default() }; + } + f + } +} + +impl Failures { + /// Whether these are the failures of `p` as it is installed now. + fn is_of(&self, p: &Plugin) -> bool { + self.hash == p.hash() && self.serial == p.serial() + } +} + +/// A layer or sublayer: its id, its parent (`None` at the top), the layer itself without its +/// contents (for comparing its options) and the ids of the rows directly in it, in order. +type LayerRow = (Id, Option, vectorcraft_doc::Node, Vec); + +/// Each layer and sublayer of `doc`, in order. +fn layer_rows(doc: &Document) -> Vec { + let mut out = Vec::new(); + let mut stack: Vec<(&Arc, Option)> = doc.layers.iter().rev().map(|l| (l, None)).collect(); + while let Some((n, parent)) = stack.pop() { + let NodeKind::Layer { children, .. } = &n.kind else { continue }; + stack.extend(children.iter().rev().filter(|c| c.is_layer()).map(|c| (c, Some(n.id)))); + let rows = children.iter().map(|c| c.id).collect(); + let mut bare = (**n).clone(); + if let Some(c) = bare.children_mut() { + c.clear(); + } + out.push((n.id, parent, bare, rows)); + } + out +} + +/// Whether a layer's place among the rows beside it differs between `old` (of `before`) and `new` +/// (of `after`), counting only the rows on both sides, so an object added or deleted next to a +/// sublayer is not a move. +fn layers_moved_among_rows(before: &Document, old: &[LayerRow], after: &Document, new: &[LayerRow]) -> bool { + use std::collections::{HashMap, HashSet}; + let layers: HashSet = old.iter().map(|r| r.0).collect(); + let lists = |doc: &Document, rows: &[LayerRow]| { + let mut m: HashMap, Vec> = rows.iter().map(|r| (Some(r.0), r.3.clone())).collect(); + m.insert(None, doc.layers.iter().map(|l| l.id).collect()); + m + }; + let (a, b) = (lists(before, old), lists(after, new)); + a.iter().any(|(parent, xs)| { + let Some(ys) = b.get(parent) else { return false }; + let (in_x, in_y): (HashSet, HashSet) = (xs.iter().copied().collect(), ys.iter().copied().collect()); + let places = |list: &[NodeId], other: &HashSet| { + list.iter().filter(|id| other.contains(id)).enumerate().filter(|(_, id)| layers.contains(id)).map(|(i, id)| (i, *id)).collect::>() + }; + places(xs, &in_y) != places(ys, &in_x) + }) +} + +/// Why the layers of `after` (with current layer `layer_after`) differ from those of `before` +/// (with `layer_before`), in [`LAYER_REASONS`] order; empty when they don't. +fn layer_reasons(before: &Arc, layer_before: Option, after: &Arc, layer_after: Option) -> Vec<&'static str> { + let mut reasons = Vec::new(); + if layer_before != layer_after { + reasons.push("current"); + } + if Arc::ptr_eq(before, after) { + return reasons; + } + let (old, new) = (layer_rows(before), layer_rows(after)); + reasons.extend(layer_row_reasons(&old, &new, || layers_moved_among_rows(before, &old, after, &new))); + reasons +} + +/// Compares layer membership, order and options by id. +fn layer_row_reasons(old: &[LayerRow], new: &[LayerRow], moved: impl FnOnce() -> bool) -> Vec<&'static str> { + let mut reasons = Vec::new(); + let old_by_id: HashMap> = old.iter().map(|r| (r.0, r)).collect(); + let new_by_id: HashMap> = new.iter().map(|r| (r.0, r)).collect(); + if new.iter().any(|r| !old_by_id.contains_key(&r.0)) { + reasons.push("added"); + } + if old.iter().any(|r| !new_by_id.contains_key(&r.0)) { + reasons.push("deleted"); + } + let kept = |rows: &[LayerRow], other: &HashMap>| { + rows.iter().filter(|r| other.contains_key(&r.0)).map(|r| (r.0, r.1)).collect::>() + }; + if kept(old, &new_by_id) != kept(new, &old_by_id) || moved() { + reasons.push("reordered"); + } + if old.iter().any(|r| new_by_id.get(&r.0).is_some_and(|o| o.2 != r.2)) { + reasons.push("options"); + } + reasons +} + +impl Session { + /// Hears that `event` (`document.opened` or `document.saved`) happened to document `uid`, which + /// the next delivery hands the plug-ins that react to it. Nothing is kept when none does. + pub(crate) fn note_plugin_event(&mut self, event: Event, uid: u64) { + let to: Vec = self.plugin_events.subscribers().iter().filter(|p| p.manifest().reacts_to(event)).map(|p| recipient(p)).collect(); + if to.is_empty() { + return; + } + self.plugin_events.queue(event, uid, Vec::new(), to); + // An open or a save is queued as its own entry, the newest. + if self.script_in_run + && let Some(p) = self.plugin_events.pending.back_mut() + { + p.by_script = true; + if event == Event::DocumentOpened { + self.plugin_events.script_opens.insert(p.seq); + } + } + } + + /// At the end of a script's run. The opens and saves its commands queued wait until then, also + /// through deliveries between its slices ([`Session::deliver_plugin_events`]). When the run + /// failed (`kept` false), drops the waiting `document.opened` events its commands queued, since + /// the documents they opened were discarded with its working copy. Its saves stay, since the + /// files they wrote stay written, and so do the events of documents a frontend opened while the + /// run was paused. Events those opens pushed out of the waiting queue come back, as after + /// [`Session::forget_plugin_opens_since`]. The next delivery gives what is left in the order it was queued. + pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) { + let events = &mut self.plugin_events; + let opens = std::mem::take(&mut events.script_opens); + if !kept { + events.drop_opens(|seq| opens.contains(&seq)); + } + for p in events.pending.iter_mut().chain(events.evicted.iter_mut()) { + p.by_script = false; + } + } + + /// A mark for [`Session::forget_plugin_opens_since`]: the events queued so far. + pub(crate) fn plugin_events_mark(&self) -> u64 { + self.plugin_events.queued + } + + /// Drops the waiting `document.opened` events queued since `mark`, for opens that a rollback + /// undid (a failed `command.batch`, or a failed command of a script or a plug-in call). The + /// saves stay, since the files they wrote stay written ([`PluginEvents::drop_opens`]). + pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) { + self.plugin_events.drop_opens(|seq| seq >= mark); + } + + /// Compares each open document with how the last check saw it and queues the events its changes + /// give the installed plug-ins: `selection.changed` and `layer.changed`. A document neither the + /// last check nor [`Session::plugin_events_see_new_documents`] saw gives none, and a plug-in + /// installed since the last check is given none: the + /// change may have come before it. A waiting event is no longer for a plug-in that is not + /// installed now, so a module removed and installed again is not given it. Nothing is compared + /// while an interaction is open, nor when no plug-in reacts to events. + fn check_plugin_events(&mut self, interaction_ended: bool) { + if self.script_in_run { + return; + } + let subs = self.plugin_events.subscribers(); + if subs.is_empty() { + self.plugin_events.seen.clear(); + self.plugin_events.seen_by.clear(); + self.plugin_events.pending.clear(); + self.plugin_events.evicted.clear(); + return; + } + let installed: Vec = subs.iter().map(|p| recipient(p)).collect(); + self.plugin_events.pending.retain_mut(|p| { + p.to.retain(|(r, _)| installed.contains(r)); + !p.to.is_empty() + }); + if self.holds_interaction() || (self.in_tool_actions && !interaction_ended) || self.docs.iter().any(|d| d.interaction.is_some()) { + return; + } + let mut events = std::mem::take(&mut self.plugin_events); + let before = std::mem::take(&mut events.seen); + let before_by = std::mem::take(&mut events.seen_by); + let to = |e: Event| -> Vec { + subs.iter().filter(|p| p.manifest().reacts_to(e)).map(|p| recipient(p)).filter(|r| before_by.contains(r)).collect() + }; + let (selection, layers) = (to(Event::SelectionChanged), to(Event::LayerChanged)); + let mut seen = Vec::with_capacity(self.docs.len()); + for st in &self.docs { + if let Some(old) = before.iter().find(|s| s.uid == st.uid) { + if !selection.is_empty() && old.selection != st.selection { + events.queue(Event::SelectionChanged, st.uid, Vec::new(), selection.clone()); + } + if !layers.is_empty() { + let reasons = layer_reasons(&old.doc, old.layer, &st.doc, st.active_layer); + if !reasons.is_empty() { + events.queue(Event::LayerChanged, st.uid, reasons, layers.clone()); + } + } + } + seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer }); + } + events.seen = seen; + events.seen_by = subs.iter().map(|p| recipient(p)).collect(); + events.pending.retain(|p| p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document)); + self.plugin_events = events; + } + + /// Resets the handler budget for a frontend frame. Call once before the frame's deliveries, + /// including background work and all UI passes, when [`Session::plugin_event_frames`] is on. + pub fn begin_plugin_event_frame(&mut self) { + self.plugin_events.frame_handlers = 0; + } + + /// Checks the open documents for changes ([`Session::check_plugin_events`]) and calls the + /// handlers of the events waiting, oldest first, one handler at a time. While a handler runs, + /// this returns at once: what the handler's calls change waits for the next delivery. While an + /// interaction is open, the events wait for the first delivery after it ends. + /// A set-aside interaction also holds events. A frontend frame calls at most + /// [`MAX_FRAME_HANDLERS`] handlers across all deliveries since [`Session::begin_plugin_event_frame`] + /// and keeps the remaining recipients for later frames. Returns whether runnable handlers + /// remain queued, so the frontend can request another frame even when no handler wrote a notice. + pub fn deliver_plugin_events(&mut self) -> bool { + if self.plugin_events.dispatching { + return false; + } + self.check_plugin_events(false); + if self.plugin_events.pending.is_empty() + || self.holds_interaction() + || self.in_tool_actions + || self.docs.iter().any(|d| d.interaction.is_some()) + { + return false; + } + let subs: HashMap> = self.plugin_events.subscribers().into_iter().map(|p| (recipient(&p), p)).collect(); + self.plugin_events.dispatching = true; + // Events pushed out by the opens of a running script stay until its run ends, which puts + // them back if the run fails. + let events = &mut self.plugin_events; + let opens = &events.script_opens; + let restorable = |p: &Pending| p.pushed_out_by.is_some_and(|(seq, open)| open && opens.contains(&seq)); + let first = events.evicted.iter().filter(|p| restorable(p)).map(|p| p.seq).min(); + events.evicted.retain(|p| { + restorable(p) + || (first.is_some_and(|seq| p.seq >= seq) + && (!p.by_script || p.event != Event::DocumentOpened || p.to.iter().any(|(r, _)| subs.contains_key(r)))) + }); + let frontend_barrier = events.evicted.iter().filter(|p| !p.by_script).map(|p| p.seq).min(); + events.prune_script_opens(); + // A handler's calls are checked as calls from outside, also when the command that ended + // played saved steps ([`Session::replay`] puts its flag back only after this delivery). + let replaying = self.set_replaying(false); + // The commands a handler calls run nested, never journaled; a panic in one leaves the depth + // as it was found. + let depth = self.depth; + self.depth += 1; + // An open or a save a running script queued waits for the end of the run + // ([`Session::plugin_events_script_ended`]), also when a frontend delivers between its + // slices: a run that fails discards the documents it opened. + let mut held = VecDeque::new(); + let mut budget = if self.plugin_event_frames { MAX_FRAME_HANDLERS.saturating_sub(self.plugin_events.frame_handlers) } else { usize::MAX }; + let waiting = self.plugin_events.pending.len(); + for _ in 0..waiting { + let Some(mut p) = self.plugin_events.pending.pop_front() else { break }; + if p.by_script { + held.push_back(p); + continue; + } + if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { + continue; + } + p.to.retain(|(r, _)| subs.get(r).is_some_and(|plugin| plugin.manifest().reacts_to(p.event))); + if !p.to.is_empty() && frontend_barrier.is_some_and(|seq| p.seq > seq) { + held.push_back(p); + continue; + } + let mut served = 0; + for (i, (r, reasons)) in p.to.iter().enumerate() { + let Some(plugin) = subs.get(r).filter(|s| s.manifest().reacts_to(p.event)) else { + served = i + 1; + continue; + }; + if self.plugin_events.failures_of(plugin).disabled { + served = i + 1; + continue; + } + if budget == 0 { + break; + } + self.run_handler(plugin, &p, reasons); + served = i + 1; + budget -= 1; + if self.plugin_event_frames { + self.plugin_events.frame_handlers += 1; + } + } + p.to.drain(..served); + if !p.to.is_empty() { + held.push_back(p); + } + if budget == 0 { + break; + } + } + // The held events are older than any a handler's calls queued meanwhile. + while let Some(p) = held.pop_back() { + self.plugin_events.pending.push_front(p); + } + self.depth = depth; + self.set_replaying(replaying); + self.plugin_events.dispatching = false; + self.plugin_events.prune_script_opens(); + self.plugin_events.pending.iter().any(|p| { + !p.by_script + && frontend_barrier.is_none_or(|seq| p.seq < seq) + && (p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document)) + && p.to.iter().any(|(r, _)| subs.get(r).is_some_and(|plugin| !self.plugin_event_status(plugin).0)) + }) + } + + /// The JSON event `p` as plug-in `plugin` is given it: the selected object ids of a + /// `selection.changed` only with `doc.read`, and `reasons`, the reasons of a `layer.changed` + /// it was given. + fn event_json(&self, plugin: &Plugin, p: &Pending, reasons: &[&'static str]) -> Value { + let mut v = json!({ "type": p.event.name(), "document": p.document }); + let Some(st) = self.docs.iter().find(|d| d.uid == p.document) else { return v }; + match p.event { + Event::SelectionChanged => { + let objects = &st.selection.objects; + v["count"] = json!(objects.len()); + v["truncated"] = json!(false); + v["ids"] = Value::Null; + if plugin.manifest().permissions().contains(&Permission::DocRead) { + v["ids"] = json!(objects.iter().take(MAX_EVENT_IDS).map(|i| i.0).collect::>()); + v["truncated"] = json!(objects.len() > MAX_EVENT_IDS); + } + } + Event::LayerChanged => { + v["layer"] = json!(st.active_layer.map(|l| l.0)); + v["reasons"] = json!(reasons); + } + Event::DocumentOpened | Event::DocumentSaved => {} + } + v + } + + /// Calls `plugin`'s handler with event `p`, given `reasons`, and records what it wrote and + /// whether it failed. + fn run_handler(&mut self, plugin: &Arc, p: &Pending, reasons: &[&'static str]) { + let event = p.event.name(); + let text = serde_json::to_vec(&self.event_json(plugin, p, reasons)).unwrap_or_default(); + let m = plugin.manifest(); + let may = m.permissions(); + let (r, report) = if may.contains(&Permission::Commands) && !m.command_allowlist.is_empty() { + let calls = crate::cmd::plugin_call::Calls::of(self, may.contains(&Permission::DocRead), false); + let mut bridge = |id: &str, args: &Value| crate::cmd::plugin_call::event_call(self, &calls, event, id, args); + plugin.run_event(&text, Some(&mut bridge)) + } else { + plugin.run_event(&text, None) + }; + let (id, name) = (plugin.id().to_string(), m.name.clone()); + for line in report.lines { + self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: line.level, text: line.text, failure: None }); + } + let failures = self.plugin_events.failures_of(plugin); + let e = match r { + Ok(()) => { + failures.count = 0; + return; + } + Err(e) => e.to_string(), + }; + failures.count += 1; + failures.last_error = Some(e.clone()); + let (count, first) = (failures.count, failures.count == 1); + log::warn!("plug-in {id}: its {event} handler failed: {e}"); + if first { + let text = Failure::HANDLER.replace("{event}", event).replace("{error}", &e); + let failure = Some(Failure::Handler { error: e }); + self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: LogLevel::Error, text, failure }); + } + if count >= MAX_EVENT_FAILURES { + self.plugin_events.failures_of(plugin).disabled = true; + let text = if count == 1 { Failure::EVENTS_OFF_ONE } else { Failure::EVENTS_OFF_OTHER }.replace("{n}", &count.to_string()); + let failure = Some(Failure::EventsOff { count }); + self.plugin_events.notice(Notice { plugin: id, name, event, level: LogLevel::Error, text, failure }); + } + } + + /// Takes each open document the last check didn't see, one opened or created since, as it is + /// now, so the next check compares it with this state: a change made to it before the next + /// delivery gives its event. Called when a document is added and after each top-level command. + /// When no check has seen a plug-in that reacts to events, the first check runs now for the + /// plug-ins installed. Nothing is kept when none is installed, nor for a document in an + /// interaction. + pub(crate) fn plugin_events_see_new_documents(&mut self) { + if self.plugin_events.seen_by.is_empty() { + // No check has run since plug-ins that react to events were installed: one now takes + // every open document as it is, for the plug-ins installed now. + if !self.plugin_events.subscribers().is_empty() { + self.check_plugin_events(false); + } + return; + } + for st in &self.docs { + if st.interaction.is_none() && !self.plugin_events.seen.iter().any(|s| s.uid == st.uid) { + self.plugin_events.seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer }); + } + } + } + + /// Delivers the events of a top-level command that just ended, unless the frontend delivers + /// them once a frame ([`Session::plugin_event_frames`]) or a script is running. + pub(crate) fn plugin_events_after_command(&mut self) { + self.plugin_events_see_new_documents(); + if std::mem::take(&mut self.plugin_events.interaction_ended) { + self.plugin_events_interaction_ended(); + } + if !self.plugin_event_frames && !self.script_in_run { + self.deliver_plugin_events(); + } + } + + /// After a plug-in was installed or removed, compares the open documents with the last check + /// ([`Session::check_plugin_events`]): what changed before is given only to the plug-ins that + /// were installed then, and what changes from now on to every plug-in installed now, also + /// before the next delivery. + pub(crate) fn plugins_changed_for_events(&mut self) { + if !self.plugin_events.dispatching { + self.check_plugin_events(false); + } + } + + /// Before a batch's steps run: checks the documents when the batch settled an interaction + /// (`settled`), or when the installed plug-ins differ from the last check's, so that a plug-in + /// installed since then is given the batch's changes. Otherwise the last check stays the + /// baseline. + pub(crate) fn plugin_events_batch_settled(&mut self, settled: bool) { + if self.plugin_events.dispatching || self.batch_stash.is_some() || self.script_in_run { + return; + } + if !settled { + let installed: Vec = self.plugin_events.subscribers().iter().map(|p| recipient(p)).collect(); + if installed == self.plugin_events.seen_by { + // Events for plug-ins removed, or for documents closed, since then still leave the + // queue first. + let set: HashSet<&Recipient> = installed.iter().collect(); + let docs = &self.docs; + self.plugin_events.pending.retain_mut(|p| { + p.to.retain(|(r, _)| set.contains(r)); + !p.to.is_empty() && (p.event.outlives_document() || docs.iter().any(|d| d.uid == p.document)) + }); + self.plugin_events.seen.retain(|s| docs.iter().any(|d| d.uid == s.uid)); + return; + } + } + self.check_plugin_events(true); + } + + /// Records the settled document state after an interaction ends, including subscribers + /// installed during its previews. Tool actions may still be finishing; handlers wait for them. + pub(crate) fn plugin_events_interaction_ended(&mut self) { + if !self.plugin_events.dispatching { + if self.depth == 0 { + self.check_plugin_events(true); + } else { + self.plugin_events.interaction_ended = true; + } + } + } + + /// The handlers' log lines and failures since the last call, oldest first. + pub fn take_plugin_event_notices(&mut self) -> Vec { + self.plugin_events.notices.drain(..).collect() + } + + /// Whether this session stopped delivering events to plug-in `p` after its handlers failed, and + /// the last failure's error. + pub fn plugin_event_status(&self, p: &Plugin) -> (bool, Option) { + match self.plugin_events.failures.get(p.id()).filter(|f| f.is_of(p)) { + Some(f) => (f.disabled, f.last_error.clone()), + None => (false, None), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layer_comparison_indexes_ids_instead_of_scanning_each_snapshot() { + use std::cell::Cell; + use std::hash::Hasher; + + #[derive(Clone, Copy)] + struct Counted<'a> { + value: u64, + comparisons: &'a Cell, + } + impl PartialEq for Counted<'_> { + fn eq(&self, other: &Self) -> bool { + self.comparisons.set(self.comparisons.get() + 1); + self.value == other.value + } + } + impl Eq for Counted<'_> {} + impl Hash for Counted<'_> { + fn hash(&self, state: &mut H) { + self.value.hash(state); + } + } + + let comparisons = Cell::new(0); + let doc = Document::new(100.0, 100.0); + let node = (*doc.layers[0]).clone(); + let old: Vec>> = + (0..1024).map(|value| (Counted { value, comparisons: &comparisons }, None, node.clone(), Vec::new())).collect(); + let mut new = old.clone(); + new.last_mut().unwrap().2.name = Some("Notes".into()); + assert_eq!(layer_row_reasons(&old, &new, || false), ["options"]); + assert!(comparisons.get() < old.len() * 32, "{} id comparisons for {} layers", comparisons.get(), old.len()); + } + + /// Waiting selection and layer events of a document merge; each plug-in keeps the reasons of + /// the changes it was given. + #[test] + fn waiting_selection_and_layer_events_of_a_document_merge() { + let (a, b): (Recipient, Recipient) = (("a".into(), "1".into(), 1), ("b".into(), "2".into(), 2)); + let mut e = PluginEvents::default(); + e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]); + e.queue(Event::LayerChanged, 1, vec!["options"], vec![a.clone()]); + e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]); + e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![a.clone()]); + e.queue(Event::LayerChanged, 1, vec!["deleted", "current"], vec![a.clone(), b.clone()]); + e.queue(Event::SelectionChanged, 2, vec![], vec![a.clone()]); + e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]); + e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]); + let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons_for(&a).to_vec())).collect(); + assert_eq!( + got, + [ + (Event::SelectionChanged, 1, vec![]), + (Event::LayerChanged, 1, vec!["current", "deleted", "options"]), + (Event::SelectionChanged, 2, vec![]), + (Event::DocumentSaved, 1, vec![]), + (Event::DocumentSaved, 1, vec![]), + ] + ); + assert_eq!(e.pending[1].reasons_for(&b), ["current", "deleted"], "only the change it was given"); + assert!(!e.pending[0].is_for(&b)); + } + + /// While a handler runs, a delivery returns at once; the change waits for the next one, which + /// hands it over once. + #[test] + fn an_event_raised_while_a_handler_runs_waits_for_the_next_delivery() { + use serde_json::json; + use vectorcraft_plugins::wat as tpl; + let id = "test.events.nested"; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.allow_plugin_grants_from_requests(); + let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone(); + s.execute("select.none", &json!({})).unwrap(); + let manifest = + format!(r#"{{"id":"{id}","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"events":["selection.changed"]}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + let grant = json!(["progress", "events"]); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + s.plugin_event_frames = true; + let given = |s: &mut Session| s.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).count(); + s.plugin_events.dispatching = true; + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.deliver_plugin_events(); + assert_eq!(given(&mut s), 0, "not inside the running handler"); + s.plugin_events.dispatching = false; + s.deliver_plugin_events(); + assert_eq!(given(&mut s), 1); + s.deliver_plugin_events(); + assert_eq!(given(&mut s), 0, "once"); + s.execute("plugin.remove", &json!({"id": id})).unwrap(); + } + + #[test] + fn at_most_32_events_wait() { + let mut e = PluginEvents::default(); + for uid in 0..(MAX_PENDING as u64 + 5) { + e.queue(Event::DocumentOpened, uid, vec![], vec![]); + } + assert_eq!(e.pending.len(), MAX_PENDING); + assert_eq!(e.pending.front().map(|p| p.document), Some(5), "the oldest are dropped"); + } + + #[test] + fn a_rollback_of_opens_brings_back_the_events_they_pushed_out() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=3 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + let mark = s.plugin_events_mark(); + for uid in 0..(2 * MAX_PENDING) as u64 { + s.plugin_events.queue(Event::DocumentOpened, 100 + uid, vec![], vec![r.clone()]); + } + assert!(s.plugin_events.pending.iter().all(|p| p.event == Event::DocumentOpened), "the save was pushed out"); + s.plugin_events.queue(Event::DocumentSaved, 999, vec![], vec![r]); + s.forget_plugin_opens_since(mark); + let left: Vec<_> = s.plugin_events.pending.iter().map(|p| (p.event.name(), p.document)).collect(); + assert_eq!( + left, + [ + (Event::DocumentSaved.name(), 1), + (Event::DocumentSaved.name(), 2), + (Event::DocumentSaved.name(), 3), + (Event::DocumentSaved.name(), 999) + ] + ); + } + + #[test] + fn a_failed_script_run_brings_back_the_events_its_opens_pushed_out() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=3 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + let before = s.plugin_events.pending.clone(); + // Enough opens to fill the store of pushed-out events, which then drops opens first. + for uid in 0..(MAX_PENDING + MAX_EVICTED + 8) as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + assert_eq!(s.plugin_events.evicted.len(), MAX_EVICTED); + assert_eq!(s.plugin_events.pending.len(), MAX_PENDING); + assert!(s.plugin_events.pending.iter().all(|p| p.event == Event::DocumentOpened), "the saves were pushed out"); + s.plugin_events_script_ended(false); + assert_eq!(s.plugin_events.pending, before); + } + + #[test] + fn a_failed_script_keeps_the_newest_saves_when_its_open_displaced_a_save() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=MAX_PENDING as u64 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + queue_script_open(&mut s, 100, &r); + s.plugin_events.queue(Event::DocumentSaved, MAX_PENDING as u64 + 1, vec![], vec![r]); + s.plugin_events.pending.back_mut().unwrap().by_script = true; + s.plugin_events_script_ended(false); + let saves: Vec<_> = s.plugin_events.pending.iter().map(|p| (p.event, p.document)).collect(); + let expected: Vec<_> = (2..=MAX_PENDING as u64 + 1).map(|uid| (Event::DocumentSaved, uid)).collect(); + assert_eq!(saves, expected); + } + + #[test] + fn a_frontend_save_waits_for_its_restorable_open_between_script_slices() { + use vectorcraft_plugins::wat as tpl; + + let mut s = Session::new(); + let manifest = concat!( + r#"{"id":"test.events.frontend_order","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"#, + r#""events":["document.opened","document.saved"]}"# + ); + let wasm = wat::parse_str(tpl::reacting(manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + let plugin = Arc::new(Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap()); + let r = recipient(&plugin); + s.plugin_events.test_subscribers = Some(vec![plugin]); + s.plugin_events.queue(Event::DocumentOpened, 1, vec![], vec![r.clone()]); + s.script_in_run = true; + for uid in 0..MAX_PENDING as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + s.plugin_events.queue(Event::DocumentSaved, 1, vec![], vec![r]); + assert!(!s.deliver_plugin_events(), "the blocked save must not request another frame"); + assert!(s.take_plugin_event_notices().is_empty(), "the save must wait for the earlier frontend open"); + s.script_in_run = false; + s.plugin_events_script_ended(false); + s.deliver_plugin_events(); + let given: Vec = s.take_plugin_event_notices().iter().map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + let events: Vec<_> = given.iter().map(|event| (event["type"].as_str().unwrap(), event["document"].as_u64().unwrap())).collect(); + assert_eq!(events, [("document.opened", 1), ("document.saved", 1)]); + } + + #[test] + fn script_open_tracking_is_bounded_after_batch_rollbacks_and_queue_overflow() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 0..2 * MAX_PENDING as u64 { + let mark = s.plugin_events_mark(); + queue_script_open(&mut s, uid, &r); + s.forget_plugin_opens_since(mark); + assert!(s.plugin_events.script_opens.is_empty(), "a rolled-back open has no remaining references"); + } + for uid in 0..2 * (MAX_PENDING + MAX_EVICTED) as u64 { + queue_script_open(&mut s, uid, &r); + let events = &s.plugin_events; + assert!(events.script_opens.len() <= 2 * (events.pending.len() + events.evicted.len())); + } + s.plugin_events_script_ended(false); + assert!(s.plugin_events.pending.is_empty()); + assert!(s.plugin_events.evicted.is_empty()); + assert!(s.plugin_events.script_opens.is_empty()); + } + + #[test] + fn a_delivery_between_script_slices_keeps_the_events_its_opens_pushed_out() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=3 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + let before = s.plugin_events.pending.clone(); + s.script_in_run = true; + for uid in 0..MAX_PENDING as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + // A save a frontend queued while the run is paused pushes out the first open. + s.plugin_events.queue(Event::DocumentSaved, 50, vec![], vec![r]); + s.deliver_plugin_events(); + assert_eq!(s.plugin_events.evicted.len(), 3, "kept while the run goes on"); + s.script_in_run = false; + s.plugin_events_script_ended(false); + assert_eq!(s.plugin_events.pending, before); + } + + /// Queues a `document.opened` as a command of a running script does. + fn queue_script_open(s: &mut Session, uid: u64, r: &Recipient) { + s.plugin_events.queue(Event::DocumentOpened, uid, vec![], vec![r.clone()]); + if let Some(p) = s.plugin_events.pending.back_mut() { + p.by_script = true; + s.plugin_events.script_opens.insert(p.seq); + } + } + + #[test] + fn a_rollback_of_an_open_that_displaced_nothing_does_not_restore_an_earlier_save() { + let mut s = Session::new(); + for uid in 0..=MAX_PENDING as u64 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![]); + } + assert_eq!(s.plugin_events.evicted.front().unwrap().document, 0); + s.plugin_events.pending.pop_front(); + let waiting = s.plugin_events.pending.clone(); + let mark = s.plugin_events_mark(); + s.plugin_events.queue(Event::DocumentOpened, 100, vec![], vec![]); + s.forget_plugin_opens_since(mark); + assert_eq!(s.plugin_events.pending, waiting); + assert_eq!(s.plugin_events.evicted.front().unwrap().document, 0); + } +} diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 3c2f3e3299..f5528f0471 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -243,6 +243,9 @@ pub struct Prefs { /// User Interface › Show Tool Group Labels: the toolbar's group names (Select, Shapes, Draw…); /// off (as it ships, #1736), the tools run on from group to group with nothing between them. pub tool_group_labels: bool, + /// User Interface › Tool Icons: "classic" (the default), the pictures the tools had in 0.24, + /// or "current", this version's pictures, which the toolbar, its flyouts, tool cards and the command palette show. + pub ui_tool_icons: String, pub open_documents_as_tabs: bool, pub large_tabs: bool, pub ui_scaling: f64, @@ -463,6 +466,34 @@ pub struct Prefs { /// preferences keeps it. #[serde(skip_serializing_if = "Vec::is_empty")] pub import_matches: Vec, + /// The values scripts store with `app.preferences` under keys that are not VectorCraft + /// preferences. Not a Preferences dialog field: it has no [`cmd::prefscmds::PREF_SPECS`] row, + /// and resetting the preferences keeps it. + #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub script_preferences: std::collections::BTreeMap, +} + +/// A value a script stored with `app.preferences`, with the type it was stored as. Two real +/// values are equal when their bits are, so 0 and -0 differ. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ScriptPreference { + Boolean(bool), + Integer(i64), + Real(f64), + String(String), +} + +impl PartialEq for ScriptPreference { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::Boolean(a), Self::Boolean(b)) => a == b, + (Self::Integer(a), Self::Integer(b)) => a == b, + (Self::Real(a), Self::Real(b)) => a.to_bits() == b.to_bits(), + (Self::String(a), Self::String(b)) => a == b, + _ => false, + } + } } /// The default Hold Shortcut Delay, in seconds (VectorCraft's own value). @@ -636,6 +667,7 @@ impl Default for Prefs { canvas_color: s("matchUi"), auto_collapse_icon_panels: false, tool_group_labels: false, + ui_tool_icons: s("classic"), open_documents_as_tabs: true, large_tabs: false, ui_scaling: 1.0, @@ -712,6 +744,7 @@ impl Default for Prefs { blend_options: None, perspective_widget: Default::default(), import_matches: vec![], + script_preferences: Default::default(), } } } diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 2abb290cf7..9224ab6030 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -222,13 +222,18 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { 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(); + // A palette's handler that a palette's `update()` runs plays the actions of the run that showed + // the palette, as the handler's own run would. + let handler = h.palette_actions.borrow(); + let actions = handler.as_deref().unwrap_or(&h.actions); + let found: Vec<&Playable> = 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)))), + [p] => (*p).clone(), + [] if !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)))), }; + drop(handler); if p.steps.is_empty() { return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name)))); } @@ -253,7 +258,18 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { 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 }; + // A document whose active artboard the script chose uses that choice, not the one the run + // started with, nor the Artboard tool's selection from the start of the run. + let chosen = h.session.borrow().active().and_then(|st| { + h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?; + Some((st.uid, super::dom::active_artboard(st))) + }); + let active = match &chosen { + Some(chosen) => std::slice::from_ref(chosen), + None => h.active_artboards.as_slice(), + }; + let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !chosen.as_ref().is_some_and(|(c, _)| c == uid)); + let start = Start { active, picks, 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); diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index c635db0585..86b3030f9a 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -200,6 +200,13 @@ fn known_answer(o: &Map) -> Result { } } +/// What the app does when the person answers Yes to a confirm it opens for a script ([`Dialogs::ask`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum OnYes { + /// Turn off the warning before a script picked with File › Scripts › Other Script… runs. + ExternalScriptWarningOff, +} + /// The dialogs of one run: the answers left for a run with nobody to ask, the dialog that waits /// for the person's answer, and the list the report gives. pub(crate) struct Dialogs { @@ -209,8 +216,15 @@ pub(crate) struct Dialogs { can_wait: Rc>, answers: RefCell>, waiting: RefCell>, + /// What Yes to the waiting dialog does, when the app opened it with [`Dialogs::ask`]. + on_yes: Cell>, + /// What the person approved with Yes, until [`Dialogs::take_approved`] takes it. + approved: Cell>, /// The error that ended the run when an answer could not reach the script. failed: RefCell>, + /// An answer could not reach the script, so a dialog still open when the run ends is listed + /// with the answer `"error"`. + answer_failed: Cell, records: RefCell>, record_bytes: Cell, count: Cell, @@ -233,7 +247,10 @@ impl Dialogs { can_wait: realm.wait_flag(), answers: RefCell::new(answers.into()), waiting: RefCell::default(), + on_yes: Cell::new(None), + approved: Cell::new(None), failed: RefCell::default(), + answer_failed: Cell::new(false), records: RefCell::default(), record_bytes: Cell::new(0), count: Cell::new(0), @@ -282,6 +299,7 @@ impl Dialogs { self.window_waiting.set(false); if let Err(e) = realm.answer(event.data()) { *self.failed.borrow_mut() = Some(e); + self.answer_failed.set(true); } Ok(()) } @@ -434,30 +452,71 @@ impl Dialogs { } /// Gives the waiting dialog `answer`, which must be for its kind and, for a prompt, at most - /// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits. + /// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits. The report lists the dialog + /// with the answer, or with `"error"` when the answer could not reach the script. pub(crate) fn answer(&self, realm: &mut Realm, answer: DialogAnswer) -> bool { let fits = match &answer { DialogAnswer::Prompt(Some(t)) => t.len() <= MAX_PROMPT_BYTES, _ => true, }; let mut waiting = self.waiting.borrow_mut(); - let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false }; - self.record(d, answer.json()); - *waiting = None; - if let Err(e) = realm.answer(answer.data()) { - *self.failed.borrow_mut() = Some(e); + if !waiting.as_ref().is_some_and(|d| d.kind == answer.kind() && fits) { + return false; + } + let Some(d) = waiting.take() else { return false }; + drop(waiting); + let on_yes = self.on_yes.take(); + // A confirm the app opened returns `undefined` to the call that opened it. + let data = if on_yes.is_some() { Data::Undefined } else { answer.data() }; + if answer == DialogAnswer::Confirm(true) { + self.approved.set(on_yes); + } + match realm.answer(data) { + Ok(()) => self.record(&d, answer.json()), + Err(e) => { + self.record(&d, json!("error")); + *self.failed.borrow_mut() = Some(e); + self.answer_failed.set(true); + } } true } - /// The run ends while a dialog waits: the report lists it with the answer `"stop"`. + /// Opens `dialog`, a confirm the app shows for the script, whose Yes does `on_yes`; the call + /// that opens it then waits ([`HostError::Wait`]) and returns `undefined`. Only a person answers + /// it, never `script.run`'s `answers`. → false when it cannot open: the run has nobody to ask, + /// or the call comes from a callback, a getter, a conversion or a file `$.evalFile` runs. + pub(crate) fn ask(&self, dialog: ScriptDialog, on_yes: OnYes) -> bool { + if !self.framed || !self.can_wait.get() { + return false; + } + *self.waiting.borrow_mut() = Some(dialog); + self.on_yes.set(Some(on_yes)); + true + } + + /// Whether the waiting dialog is the confirm [`Dialogs::ask`] opened to turn off the external + /// script warning, whatever a script's own dialogs say. + pub(crate) fn asks_warning_off(&self) -> bool { + self.waiting.borrow().is_some() && self.on_yes.get() == Some(OnYes::ExternalScriptWarningOff) + } + + /// What the person approved with Yes to a confirm from [`Dialogs::ask`], once. + pub(crate) fn take_approved(&self) -> Option { + self.approved.take() + } + + /// The run ends while a dialog waits: the report lists it with the answer `"stop"`, or + /// `"error"` when an answer could not reach the script. pub(crate) fn stopped(&self) { + self.on_yes.set(None); + let answer = if self.answer_failed.replace(false) { json!("error") } else { json!("stop") }; if let Some(d) = self.waiting.borrow_mut().take() { - self.record(&d, json!("stop")); + self.record(&d, answer.clone()); } self.window_waiting.set(false); if let Some(showing) = self.window.borrow_mut().take() { - self.end_record(&showing, json!("stop")); + self.end_record(&showing, answer); } } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b29b037908..1dda97ad95 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -18,7 +18,8 @@ //! //! Collections are counted from 0, and `pageItems` lists art topmost first, as //! reads the frontmost path as -//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName` +//! `pathItems[0]`; the `layers` module gives the order of a layer's, a group's and a compound +//! path's lists. A collection read with a name, `pageItems["name"]`, gives the object `getByName` //! gives, and a script may name the application's members without `app.`, as //! describes; here //! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active @@ -52,8 +53,8 @@ //! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at //! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an //! error. A run that fails leaves the tool as it was. -//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path -//! in the object. +//! - `controlBounds` is the visible bounds, widened to take in the anchors and direction points of +//! the shown paths in the object; a clip group or clipping layer takes in only its clipping path's. //! - `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: @@ -97,17 +98,34 @@ use vectorcraft_js::{ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; +mod clipboard; +mod colors; +mod defaults; +mod images; +pub(super) mod layers; +mod matrix; +mod paths; +pub mod preferences; mod print; +mod raster_capture; +#[cfg(test)] +pub(crate) use raster_capture::BEFORE_CAPTURE_EXPORT; mod save_open; mod tags; mod text; +mod tracing; +mod transform; mod variables; +#[cfg(test)] +pub(crate) use paths::POINT_LOOKS; + pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; /// What [`after_command`] compares with, taken before each command a script runs /// ([`variables::before_command`]). pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + tracing::before_command(h); variables::before_command(h, id) } @@ -116,17 +134,14 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec = const { Cell::new(0) }; + /// How many lists of art the art collections have built on this thread. + pub(crate) static ART_SCANS: Cell = const { Cell::new(0) }; +} + /// What the object model keeps for one run: its coordinate system, the lists of page items and the /// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, /// each kept while its document is unchanged, the lists of paths, the point changes of a path not @@ -197,9 +221,6 @@ pub(super) struct State { /// Each path whose points the run read, as the run last saw it, by document uid and then path /// id ([`paths`]). point_nodes: RefCell>>>, - /// The path whose points the object model is writing with `path.setAnchors`, the only path - /// that command changes ([`paths`]). - one_path: Cell>, /// Each document, by uid, as it was when the run last looked at all the paths in it whose /// points it read ([`paths`]). point_docs: RefCell>>, @@ -208,6 +229,21 @@ pub(super) struct State { editing: Cell>, locked: RefCell>, saving: Cell, + /// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently + /// used first, each kept while its document is unchanged. + art: RefCell>, + /// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used + /// first, each kept while its document is unchanged. + layers: RefCell>, + /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. + pub(super) active_artboards: RefCell>, + /// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it. + pub(super) chosen_artboards: RefCell>, + /// Each open document's uid and the index of its active artboard when the run started. + pub(super) boards_at_start: Vec<(u64, usize)>, + /// Each document made during the run whose active artboard `setActiveArtboardIndex` chose, + /// with the index it chose the first time. + pub(super) boards_chosen_in_new: RefCell>, /// `app.userInteractionLevel` ([`save_open`]). save_options: save_open::State, /// The print option objects ([`print`]). @@ -217,13 +253,17 @@ pub(super) struct State { preset_bytes: Cell, preset_limit: u64, vars: variables::Handles, + /// What the placed and raster items keep ([`images::State`]). + images: images::State, + /// What the tracings keep ([`tracing::State`]). + tracing: tracing::State, tool: Cell>, } impl State { - /// The state of a run whose heap is `heap_bytes`. - pub(super) fn new(heap_bytes: usize) -> Self { - Self { preset_limit: heap_bytes as u64, ..Self::default() } + /// The state of a run that starts with the documents `docs` open and whose heap is `heap_bytes`. + pub(super) fn new(docs: &[DocState], heap_bytes: usize) -> Self { + Self { boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), preset_limit: heap_bytes as u64, ..Self::default() } } /// Whether a call's own savepoint is open: its commands take none of their own. @@ -252,11 +292,13 @@ impl State { /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every /// document, the selection and the undo histories are as they were before it, with no undo step /// and no change to the document's saved state, and the growth its commands were charged is not -/// counted. +/// counted. Point changes that wait in [`State`] are written first, so a failure in `f` does not +/// put them back. fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { if h.dom.saving.get() { return f(h); } + flush(h)?; let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); let styles = text::styles::mark(h); let mark = h.growth_mark(); @@ -386,7 +428,7 @@ pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> { /// Notes the changes a command made to the points of the paths the run has read /// ([`paths::see_all_points`]). -pub(super) fn see_points(h: &Host) { +pub(super) fn see_points(h: &Host) -> std::result::Result<(), HostError> { paths::see_all_points(h) } @@ -419,7 +461,7 @@ fn point_method(link: &Link, f: Member) -> HostMember { 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 { +pub(super) fn typed(data_type: &str) -> MemberInfo { MemberInfo { data_type: data_type.into(), ..MemberInfo::default() } } @@ -430,7 +472,8 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document, page item, path point or text range `this` is still there. +/// the check that a document, layer, page item, path point, text range or `GroupItems` collection +/// `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 { @@ -443,7 +486,10 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" | "PathItem" | "TextFrame" => { + "Layer" => { + layers::layer_of(&h, arg(&a, 0))?; + } + c if c == "PageItem" || ITEM_CLASSES.contains(&c) => { item_of(&h, arg(&a, 0))?; } "PathPoint" => { @@ -452,6 +498,9 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des "TextRange" => { text::check_range(&h, arg(&a, 0))?; } + "GroupItems" => { + layers::check_groups(&h, arg(&a, 0))?; + } _ => {} } Err(HostError::Error(message.clone())) @@ -583,16 +632,25 @@ fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> { Some((doc, id_of(high, low)?)) } -/// The page item `d` names, which must still be in its document. +/// The page item `d` names, which must still be in its document and still be of its class (an +/// embedded `PlacedItem` is a `RasterItem` after, and its old object is stale). fn item_of(h: &Host, d: &Data) -> std::result::Result { - let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; - if handle.len() != 5 { + let Some((class, handle)) = host_ref_parts(d).filter(|(c, _)| ITEM_CLASSES.contains(c)) else { return Err(HostError::Type("this is not a page item".into())); - } - let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + }; + let (doc, id) = match handle.as_slice() { + [_, _, _, _, _] => node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?, + &[run, uid, _, _, _, slot] => { + let id = images::pending_id(h, run, uid, slot)?; + (find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?, id) + } + _ => return Err(HostError::Type("this is not a page item".into())), + }; + let original = id; + let id = if class == "PluginItem" { tracing::follow(h, doc.uid, id) } else { id }; let s = h.session.borrow(); let st = &s.documents()[doc.index]; - if st.doc.node(id).is_none_or(|n| typename(n).is_none()) { + if st.doc.node(id).is_none_or(|n| typename(n) != Some(class) || (class == "PluginItem" && !tracing::same_source(h, doc.uid, original, n))) { return Err(HostError::Error(STALE_ITEM.into())); } Ok(Item { doc, id }) @@ -603,6 +661,7 @@ fn typename(n: &crate::doc::Node) -> Option<&'static str> { Some(match &n.kind { NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => return None, NodeKind::Group { .. } if n.extras().graph.is_some() => "GraphItem", + NodeKind::Group { .. } if crate::cmd::is_trace_group(n) => "PluginItem", NodeKind::Group { .. } => "GroupItem", NodeKind::Path { .. } => "PathItem", NodeKind::Compound { .. } => "CompoundPathItem", @@ -626,6 +685,11 @@ fn doc_ref(h: &Host, uid: u64) -> Data { fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { match st.doc.node(id) { Some(n) => match typename(n) { + Some("PlacedItem") => images::bound_ref(h, st, id).unwrap_or_else(|| host_ref("PlacedItem", &node_handle(h, st, id))), + Some("PluginItem") => { + tracing::remember_source(h, st.uid, n); + host_ref("PluginItem", &node_handle(h, st, tracing::origin(h, st.uid, id))) + } Some(t) => host_ref(t, &node_handle(h, st, id)), None => host_ref("Layer", &node_handle(h, st, id)), }, @@ -649,7 +713,10 @@ fn page_items(h: &Host, st: &DocState) -> std::result::Result>, H _ => { out.push(n.id); if let Some(children) = n.children() { - walk(children, out); + // The source image an Image Trace object keeps hidden as its first child is + // reached through that object's `tracing`. + let source = usize::from(crate::cmd::is_trace_group(n)); + walk(children.get(source..).unwrap_or_default(), out); } } } @@ -686,9 +753,11 @@ fn top_items(d: &Document) -> Vec { out } -/// Whether `n` and every object inside it are shown and unlocked. +/// Whether `n` and every object inside it are shown and unlocked. The source image an Image Trace +/// object keeps hidden as its first child is part of that object and is not counted. fn all_editable(n: &crate::doc::Node) -> bool { - n.visible && !n.locked && n.children().is_none_or(|c| c.iter().all(|c| all_editable(c))) + let source = usize::from(crate::cmd::is_trace_group(n)); + n.visible && !n.locked && n.children().is_none_or(|c| c.iter().skip(source).all(|c| all_editable(c))) } /// Whether the object and every layer and group it is in are shown and unlocked. @@ -881,7 +950,8 @@ fn restore_layer(h: &Host, uid: u64, layer: Option, rows: &[NodeId]) -> /// commands changed it (commands given ids select them first), direct-selected anchors, segments, /// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic /// symbol instance or an Objects on Path group included, less the objects that are now deleted, -/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together +/// hidden or locked; the current layer, which selecting art changes, is put back too while it is +/// still a layer that can be edited. `f`'s commands and the steps that put things back succeed or fail together /// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s /// changes are undone as well. fn on_doc( @@ -890,14 +960,27 @@ fn on_doc( keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - atomically(h, |h| on_doc_steps(h, uid, keep_selection, f)) + on_doc_layer(h, uid, keep_selection, true, f) } -/// The steps of [`on_doc`]. +/// [`on_doc`], with `keep_layer` false for `f`s that choose the current layer (`layers.add()`, +/// `activeLayer = layer`): the selection is put back, and the layer `f` left current stays current. +fn on_doc_layer( + h: &Host, + uid: u64, + keep_selection: bool, + keep_layer: bool, + f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + atomically(h, |h| on_doc_steps(h, uid, keep_selection, keep_layer, f)) +} + +/// The steps of [`on_doc_layer`]. fn on_doc_steps( h: &Host, uid: u64, keep_selection: bool, + keep_layer: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { let (index, active, before, layer, activated) = { @@ -911,6 +994,12 @@ fn on_doc_steps( command(h, "document.activate", &json!({"index": index}))?; } let r = f(h); + let layer = if keep_layer { + layer + } else { + let s = h.session.borrow(); + s.active().filter(|st| st.uid == uid).map_or(layer, |st| (st.active_layer, st.highlighted_rows())) + }; let mut restored = Ok(()); if keep_selection { let doc = { @@ -982,7 +1071,7 @@ fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Res /// is made active, so bounds it reads take in type that the switch measured again (in the /// document's own composite fonts, [`Session::set_active`]). fn edit_item_with(h: &Host, item: Item, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { - paths::see_all_points(h); + paths::see_all_points(h)?; let kept = h.dom.editing.replace(Some(item)); let r = atomically(h, |h| on_doc(h, item.doc.uid, true, f)); h.dom.editing.set(kept); @@ -2133,22 +2222,35 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { } fn items_length(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_length(h, a); + } let doc = items_doc(h, a)?; let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?; Ok(num(float(n as u64))) } fn items_typename(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_typename(h, a); + } items_doc(h, a)?; Ok(text("PageItems")) } fn items_to_string(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + layers::scoped_typename(h, a)?; + return Ok(text("[PageItems]")); + } items_doc(h, a)?; Ok(text("[PageItems]")) } fn items_parent(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_parent(h, a); + } let doc = items_doc(h, a)?; Ok(doc_ref(h, doc.uid)) } @@ -2168,6 +2270,9 @@ fn position(n: f64) -> Option { /// 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 { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_at(h, a); + } let doc = items_doc(h, a)?; match arg(a, 1) { Data::String(_) => match items_by_name(h, a) { @@ -2191,6 +2296,9 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Answer { } fn items_by_name(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_by_name(h, a); + } 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) @@ -2207,6 +2315,9 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { } fn items_index(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_index(h, a); + } match arg(a, 1) { Data::String(_) => items_by_name(h, a), Data::Number(n) => { @@ -2224,14 +2335,21 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { /// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted, /// and so does an object on a locked artboard. fn items_remove_all(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_remove_all(h, a); + } let doc = items_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(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) + // A clipping layer emptied of its art releases its mask, so art added later is not made its + // clipping path. + let released = masks_cleared_by(&st.doc, &ids); + let tracing = release_makes_tracing(&st.doc, &released, &ids); + (ids, refused, on_locked, released, tracing) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -2241,8 +2359,11 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + if tracing { + return Err(HostError::Error(NOT_A_TRACING.into())); + } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + on_doc(h, doc.uid, true, |h| clear_releasing(h, &released, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } Ok(Data::Undefined) } @@ -2307,6 +2428,28 @@ fn item_set_name(h: &Host, a: &[Data]) -> Answer { if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } + // An Image Trace object is known by its name, so renaming one would end the tracing, and giving + // an ordinary group that holds an image first the tracing's name would make it one. + let item = this_item(h, a)?; + let refused = with_doc(h, item.doc, |_, st| { + st.doc.node(item.id).and_then(|n| { + let tracing = crate::cmd::is_trace_group(n); + let would_trace = !tracing + && name == crate::cmd::TRACE_NAME + && matches!(n.kind, crate::doc::NodeKind::Group { clip: false, .. }) + && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, crate::doc::NodeKind::Image(_)))); + if tracing && n.name.as_deref() != Some(&**name) { + Some(TRACING_NAME) + } else if would_trace { + Some(NOT_A_TRACING) + } else { + None + } + }) + }); + if let Some(msg) = refused { + return Err(HostError::Error(msg.into())); + } set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name})) } @@ -2376,8 +2519,14 @@ fn item_set_locked(h: &Host, a: &[Data]) -> Answer { set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } +/// The percentage a page item's or a layer's `opacity` reports for `opacity`, rounded to four +/// decimals. +fn reported_opacity(opacity: f32) -> f64 { + (f64::from(opacity) * 100.0 * 1e4).round() / 1e4 +} + fn item_opacity(h: &Host, a: &[Data]) -> Answer { - read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) + read_item(h, a, |_, n| Ok(num(reported_opacity(n.opacity)))) } fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { @@ -2394,7 +2543,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { let (now, keeps_other) = with_doc(h, item.doc, |_, st| { let d = &st.doc; // Only the exact number the getter reports counts as the same opacity. - let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v); + let now = d.node(item.id).filter(|n| reported_opacity(n.opacity) == v).map(|n| f64::from(n.opacity) * 100.0); let keeps_other = crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]); (now, keeps_other) @@ -2477,8 +2626,12 @@ fn item_set_selected(h: &Host, a: &[Data]) -> Answer { /// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the /// document's [`Frame`]. An object with nothing in it, such as an empty group or a compound path /// whose paths moved out, has no bounds: its bounds read as zeros, and moving or resizing it does -/// nothing. +/// nothing. Type in a document in the back that is not measured yet is measured first, as the +/// switch to that document would measure it. fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Option, Frame), HostError> { + if h.session.borrow().active_index() != Some(item.doc.index) && rests_on_type(h, item) { + h.session.borrow_mut().measure_back_type(item.doc.uid); + } with_doc(h, item.doc, |_, st| Ok((st.doc.bounds_of(&[item.id], visual), frame(st)?))) } @@ -2498,26 +2651,41 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } -/// `controlBounds`: the visible bounds, widened to take in the direction points of every path in -/// the object. +/// `controlBounds`: the visible bounds, taking in the anchors and direction handles of the paths +/// in the item. fn item_control(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; // An object with nothing in it reads zeros, as its other bounds do. let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) }; - let r = with_doc(h, item.doc, |_, st| { - let mut r = r; - if let Some(n) = st.doc.node(item.id) { - n.walk(&mut |c| { - if let Some(handles) = c.path_data().and_then(vectorcraft_geom::PathData::control_bounds) { - r = r.union(handles); - } - }); - } - r - }); + // Each object and anchor the walk visits is charged, so reading a large group's bounds again + // and again counts against the run. + let mut steps = 0u64; + let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r, &mut steps))); + h.charge_call(steps)?; Ok(f.bounds(h.dom.coords.get(), r)) } +/// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and +/// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as +/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping +/// path's. +fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect { + *steps += 1; + if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) { + return r; + } + for a in n.path_data().iter().flat_map(|p| p.subpaths.iter()).flat_map(|s| s.anchors.iter()) { + *steps += 1; + r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out); + } + let children = n.children().map_or(&[][..], Vec::as_slice); + let children = if n.clips() { &children[..children.len().min(1)] } else { children }; + for c in children { + r = take_in_handles(c, r, steps); + } + r +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; match item_rect(h, item, false)? { @@ -2550,20 +2718,41 @@ fn item_height(h: &Host, a: &[Data]) -> Answer { Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.height()))) } +/// Whether the item's bounds can rest on laid-out type: it holds type, a symbol instance or a +/// placed document. Such bounds in a document in the back may be laid out in another document's +/// composite fonts, so the setters measure them only after the switch to the document. +fn rests_on_type(h: &Host, item: Item) -> bool { + with_doc(h, item.doc, |_, st| { + st.doc.node(item.id).is_none_or(|n| { + let mut found = false; + n.walk(&mut |c| found |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. } | NodeKind::PlacedDocument(_))); + found + }) + }) +} + /// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one /// stays). fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { let item = this_item(h, a)?; refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - // Measured once the document is active. - edit_item_with(h, item, |h| { - let (Some(r), f) = item_rect(h, item, false)? else { return Ok(()) }; + // The distance to move, or `None` when the item is already there or has no bounds. + let delta = |h: &Host| -> std::result::Result, HostError> { + let (Some(r), f) = item_rect(h, item, false)? else { return Ok(None) }; let c = h.dom.coords.get(); let now = f.to_script(c, Point::new(r.x0, r.y0)); let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); let (dx, dy) = (to.x - r.x0, to.y - r.y0); - if dx.abs() > 1e-9 || dy.abs() > 1e-9 { + Ok((dx.abs() > 1e-9 || dy.abs() > 1e-9).then_some((dx, dy))) + }; + // An item already in place stays, and its document stays in the back. + if h.session.borrow().active_index() != Some(item.doc.index) && !rests_on_type(h, item) && delta(h)?.is_none() { + return Ok(Data::Undefined); + } + // Measured again once the document is active. + edit_item_with(h, item, |h| { + if let Some((dx, dy)) = delta(h)? { command(h, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?; } Ok(()) @@ -2601,19 +2790,27 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer { } refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - // Measured once the document is active, so the ratio applies to the bounds the scale works on. - edit_item_with(h, item, |h| { - let (Some(r), _) = item_rect(h, item, false)? else { return Ok(()) }; + // The bounds to scale and the percentage, or `None` when the item already has that size or has + // no bounds. + let scale = |h: &Host| -> std::result::Result, HostError> { + let (Some(r), _) = item_rect(h, item, false)? else { return Ok(None) }; let now = if width { r.width() } else { r.height() }; if now <= 0.0 { return Err(HostError::Error(format!("the object has no {what} to scale"))); } - if (now - size).abs() < 1e-9 { - return Ok(()); + Ok(((now - size).abs() >= 1e-9).then_some((r, size / now * 100.0))) + }; + // An item already that size stays, and its document stays in the back. + if h.session.borrow().active_index() != Some(item.doc.index) && !rests_on_type(h, item) && scale(h)?.is_none() { + return Ok(Data::Undefined); + } + // Measured again once the document is active, so the ratio applies to the bounds the scale + // works on. + edit_item_with(h, item, |h| { + if let Some((r, pct)) = scale(h)? { + let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; + command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?; } - let pct = size / now * 100.0; - let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; - command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?; Ok(()) })?; Ok(Data::Undefined) @@ -2655,11 +2852,59 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } + // An image left first in an ordinary group named as a tracing would make that group one. + if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } + let released = with_doc(h, item.doc, |_, st| masks_cleared_by(&st.doc, &[item.id])); + // A clip group named as a tracing, released with an image left first, would become one too. + if with_doc(h, item.doc, |_, st| release_makes_tracing(&st.doc, &released, &[item.id])) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } // A compound path whose last path this is stays, empty, as it does after `move`. - edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?; + let params = json!({"ids": [item.id.0], "keepEmpty": true}); + paths::see_all_points(h)?; + let kept = h.dom.editing.replace(Some(item)); + let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| clear_releasing(h, &released, ¶ms))); + h.dom.editing.set(kept); + r?; Ok(Data::Undefined) } +/// The clip groups and clipping layers whose clipping path is one of `ids`. Deleting a clipping +/// path releases its mask, so the object above it does not become the clipping path. +pub(super) fn masks_cleared_by(d: &Document, ids: &[NodeId]) -> Vec { + ids.iter() + .filter_map(|i| { + let p = d.parent_of(*i)?; + let n = d.node(p)?; + (n.clips() && n.children()?.first().is_some_and(|c| c.id == *i)).then_some(p) + }) + .collect() +} + +/// Whether releasing the masks of `released` and deleting `removed` would leave one of those groups +/// an ordinary group named as a tracing with an image first in it, which would make it a tracing. +pub(super) fn release_makes_tracing(d: &Document, released: &[NodeId], removed: &[NodeId]) -> bool { + if released.is_empty() { + return false; + } + let removed: std::collections::HashSet = removed.iter().copied().collect(); + released.iter().filter_map(|g| d.node(*g)).any(|g| { + matches!(g.kind, NodeKind::Group { .. }) + && g.name.as_deref() == Some(crate::cmd::TRACE_NAME) + && g.children().and_then(|c| c.iter().find(|n| !removed.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) + }) +} + +/// Releases the masks of `released` ([`masks_cleared_by`]), then runs `edit.clear` with `params`. +pub(super) fn clear_releasing(h: &Host, released: &[NodeId], params: &Value) -> std::result::Result { + for g in released { + command(h, "layer.clippingMask.toggle", &json!({"id": g.0}))?; + } + command(h, "edit.clear", params) +} + /// The error of `remove()` and `removeAll()` for an object on a locked artboard. pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; @@ -2708,14 +2953,20 @@ struct Destination { fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); - let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); - let Some(handle) = handle.filter(|parts| parts.len() == 5) else { - if handle_of(target, "Document").is_some() { - return Err(HostError::Error("a document as the relative object is not available yet".into())); - } - return Err(HostError::Type("the relative object must be a page item or a layer".into())); + // A page item is looked up as its class names it (a wrapper whose object changed class is + // stale), a layer by its handle. + let (doc, target) = if handle_of(target, "PageItem").is_some() { + let t = item_of(h, target)?; + (t.doc, t.id) + } else { + let Some(handle) = handle_of(target, "Layer").filter(|parts| parts.len() == 5) else { + if handle_of(target, "Document").is_some() { + return Err(HostError::Error("a document as the relative object is not available yet".into())); + } + return Err(HostError::Type("the relative object must be a page item or a layer".into())); + }; + node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))? }; - let (doc, target) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } @@ -2728,7 +2979,11 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s } let (parent, beside) = match how { Placement::Top | Placement::Bottom => { - if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { + if matches!(t.kind, NodeKind::Compound { .. }) { + if !d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })) { + return Err(HostError::Error("a compound path holds only paths".into())); + } + } else if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { return Err(HostError::Error(format!("{} cannot hold objects", typename(t).unwrap_or("Layer")))); } (target, None) @@ -2755,17 +3010,79 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s let name = d.node(item.id).and_then(typename).unwrap_or("page item"); return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0))); } + // Checked here as well as in `place`, so `duplicate` refuses before it makes the copy. A + // tracing's source image moved out keeps the error `place` gives it. + let image = d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))); + if image && (copy || !crate::cmd::is_trace_source(d, item.id)) && named_as_tracing(d, parent) { + // Where the image comes from: its index in `parent` when it is already there. + let own = d.position(item.id).and_then(|(p, i, _)| (p == Some(parent)).then_some(i)).filter(|_| !copy); + let count = d.children(Some(parent)).map_or(0, Vec::len); + let first = match how { + Placement::Bottom => true, + Placement::Top => count == usize::from(own.is_some()), + Placement::Below => beside.and_then(|b| d.position(b)).is_some_and(|(_, i, _)| i == 0 || (i == 1 && own == Some(0))), + Placement::Above => false, + }; + if first { + return Err(HostError::Error(NOT_A_TRACING.into())); + } + } Ok(Destination { parent, beside, how }) }) } +/// Whether `id` is an ordinary group named as an Image Trace object that is not one: an image put +/// first in it would make it a tracing. +fn named_as_tracing(d: &Document, id: NodeId) -> bool { + d.node(id).is_some_and(|p| { + !crate::cmd::is_trace_group(p) && matches!(p.kind, NodeKind::Group { clip: false, .. }) && p.name.as_deref() == Some(crate::cmd::TRACE_NAME) + }) +} + +/// Whether taking the object `id` out of `parent` and, with `at`, putting it back at that index of +/// what is left would make `parent`, an ordinary group named as a tracing, one: an image first in it. +fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option) -> bool { + if !named_as_tracing(d, parent) { + return false; + } + let image = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Image(_)); + let rest = d.children(Some(parent)).map(|c| c.iter().filter(|n| n.id != id).collect::>()).unwrap_or_default(); + match at { + Some(0) => d.node(id).is_some_and(image), + _ => rest.first().is_some_and(|n| image(n)), + } +} + +/// Whether deleting every object in `removed` together would leave one of their parents, an +/// ordinary group named as a tracing, with an image first in it, which would make it a tracing. +pub(super) fn removal_makes_tracing(d: &Document, removed: &[NodeId]) -> bool { + let going: std::collections::HashSet = removed.iter().copied().collect(); + let mut parents: Vec = removed.iter().filter_map(|i| d.parent_of(*i)).collect(); + parents.sort_unstable_by_key(|p| p.0); + parents.dedup(); + parents + .into_iter() + .filter(|p| named_as_tracing(d, *p)) + .any(|p| d.children(Some(p)).and_then(|c| c.iter().find(|n| !going.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)))) +} + /// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { let index = with_doc(h, doc, |_, st| { let d = &st.doc; let from = d.position(id); let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); - let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0; + // A clip group's first child is its clipping path, and an Image Trace object's its source + // image: both stay first, and the source image moved within its own tracing stays where it is. + if crate::cmd::is_trace_source(d, id) { + if d.parent_of(id) == Some(to.parent) { + return Ok(0); + } + return Err(HostError::Error("a tracing's source image cannot leave its tracing".into())); + } + let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0; + // The clipping path itself, put back where it is, stays the clipping path. + let mask_stays = from.is_some_and(|(p, j, _)| p == Some(to.parent) && j == 0); let at = match (to.how, to.beside) { (Placement::Top, _) => count, (Placement::Bottom, _) => 0, @@ -2777,11 +3094,34 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul { i -= 1; } - if how == Placement::Above { i + 1 } else { i } + let at = if how == Placement::Above { i + 1 } else { i }; + // A place behind a clipping path is refused; an object put into the clip group + // itself goes directly above the clipping path. + if clips && at == 0 && !mask_stays { + return Err(HostError::Error("an object cannot go below a clipping mask".into())); + } + at } (_, None) => count, }; - Ok::<_, HostError>(if clips { at.max(1) } else { at }) + // Any other place for the clipping path is left to `node.move`, which refuses it. + let stays = mask_stays && at == 0; + let at = if clips && !stays { at.max(1) } else { at }; + // The index `node.move` puts the object at: art stays below the ruler guides. + // This is `Node::insert_index` on the parent's children without the object, read in place + // so that no list of them is copied. + let node = d.node(id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let rest = || d.children(Some(to.parent)).into_iter().flatten().filter(|n| n.id != id); + let start = rest().enumerate().filter(|(_, n)| !n.is_ruler_guide()).last().map_or(0, |(i, _)| i + 1); + let i = at.min(rest().count()); + let at = if node.is_ruler_guide() { i.max(start) } else { i.min(start) }; + // An image left or put first in an ordinary group named as a tracing would make that group + // one, in the group it leaves as in the group it goes into. + let left = from.and_then(|(p, ..)| p).filter(|p| *p != to.parent); + if makes_tracing(d, to.parent, id, Some(at)) || left.is_some_and(|p| makes_tracing(d, p, id, None)) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } + Ok::<_, HostError>(at) })?; let now = with_doc(h, doc, |_, st| st.doc.position(id)); if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) { @@ -2876,41 +3216,56 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { selection_ids(h, item.doc, arg(a, 0))?; // The Arrange commands keep a clipping path at the bottom of its parent and the art below the // parent's ruler guides, so the item's place is counted among the art above the clipping path. - let (before, floor, art) = with_doc(h, item.doc, |_, st| { + // The source image an Image Trace object keeps first stays first, and the other objects in it + // stay above it. + let (before, floor, art, parent, source, in_trace) = with_doc(h, item.doc, |_, st| { let d = &st.doc; let at = d.position(item.id); let parent = at.and_then(|(p, ..)| p); - let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips)); + let in_trace = parent.and_then(|p| d.node(p)).is_some_and(crate::cmd::is_trace_group); + let clips = parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips); + let floor = usize::from(clips || in_trace); let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c)); - (at.map(|(_, i, _)| i), floor, art) + (at.map(|(_, i, _)| i), floor, art, parent, crate::cmd::is_trace_source(d, item.id), in_trace) }); let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) }; + if source { + return Ok(Data::Undefined); + } let unchanged = i < floor || match id { "object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art, _ => i <= floor, }; - if !unchanged { - edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + if unchanged { + return Ok(Data::Undefined); + } + // Where the Arrange command puts the item among its parent's art, worked out as + // `object.arrange` works it out for one object. An image put first, or another object moved + // from above an image that becomes first, in an ordinary group named as a tracing would make + // that group one. + let to = match id { + "object.arrange.bringToFront" => art - 1, + "object.arrange.bringForward" => i + 1, + "object.arrange.sendBackward" => i - 1, + _ => floor, + }; + if parent.is_some_and(|p| with_doc(h, item.doc, |_, st| makes_tracing(&st.doc, p, item.id, Some(to)))) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } + match parent { + Some(p) if in_trace && id == "object.arrange.sendToBack" => { + edit_item(h, item, "node.move", &json!({"id": item.id.0, "parent": p.0, "index": floor}))?; + } + _ => { + edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + } } Ok(Data::Undefined) } -fn layer_name(h: &Host, a: &[Data]) -> Answer { - let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, _, _, _] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; - find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) -} - -fn layer_typename(h: &Host, a: &[Data]) -> Answer { - layer_name(h, a)?; - Ok(text("Layer")) -} - /// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name. -fn named_text(class: &str, name: Answer) -> Answer { +pub(super) fn named_text(class: &str, name: Answer) -> Answer { match name? { Data::String(n) => Ok(text(format!("[{class} {n}]"))), _ => Ok(text(format!("[{class} ]"))), @@ -2925,10 +3280,6 @@ fn doc_to_string(h: &Host, a: &[Data]) -> Answer { named_text("Document", doc_name(h, a)) } -fn layer_to_string(h: &Host, a: &[Data]) -> Answer { - named_text("Layer", layer_name(h, a)) -} - /// `toString()` of an object without a name: `[Class]`. fn class_text(name: &'static str) -> HostMember { HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]"))))) @@ -2971,6 +3322,7 @@ const ENUMS: &[(&str, &[&str])] = &[ ("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]), ("DocumentColorSpace", &["CMYK", "RGB"]), ("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]), + ("Transformation", &["BOTTOM", "BOTTOMLEFT", "BOTTOMRIGHT", "CENTER", "DOCUMENTORIGIN", "LEFT", "RIGHT", "TOP", "TOPLEFT", "TOPRIGHT"]), ("ScreenMode", &["DESKTOP", "FULLSCREEN", "MULTIWINDOW"]), ("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]), ("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]), @@ -2996,8 +3348,12 @@ const ENUMS: &[(&str, &[&str])] = &[ /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { text::install_enums(realm)?; - for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS) { - let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + for (name, members) in + ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(raster_capture::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) + { + let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name); + items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}")))))); realm.define_host_object(name, items)?; } let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect(); @@ -3034,6 +3390,9 @@ fn classes(link: &Link) -> Vec { ]); application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") })); application.push(later(l, "Application", "beep")); + application.extend(preferences::app_members()); + application.extend(matrix::app_members(l)); + application.extend(clipboard::app_members(l)); application.extend(save_open::application_members(l)); application.extend(print::application_members(l)); application.extend(super::actions::app_members(l)); @@ -3053,6 +3412,7 @@ fn classes(link: &Link) -> Vec { }; let mut classes = vec![ class("Application", None, application, None), + preferences::class(l), preset, class( "Documents", @@ -3114,11 +3474,14 @@ fn classes(link: &Link) -> Vec { ]); document.extend(defaults::document_members(l)); document.extend(text::styles::doc_members(l)); - document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m))); + document.extend(["swatches", "symbols"].into_iter().map(|m| later(l, "Document", m))); + document.extend(layers::document_members(l)); document.extend(variables::document_members(l)); document.extend(save_open::document_members(l)); document.extend(print::document_members(l)); + document.extend(images::document_members(l)); document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") })); + document.extend(raster_capture::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "Views", @@ -3152,7 +3515,7 @@ fn classes(link: &Link) -> Vec { named(vec![ ("typename", get(l, items_typename), typed("string")), ("length", get(l, items_length), typed("number")), - ("parent", get(l, items_parent), typed("Document")), + ("parent", get(l, items_parent), typed("*")), ("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])), ("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])), ("removeAll", method(l, items_remove_all), returns("undefined", &[])), @@ -3192,32 +3555,82 @@ fn classes(link: &Link) -> Vec { ("remove", method(l, item_remove), returns("undefined", &[])), ("zOrder", method(l, item_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])), ("toString", method(l, item_to_string), returns("string", &[])), - ]); - page_item.extend( - [ - "artworkKnockout", - "isIsolated", - "layer", - "pixelAligned", - "sliced", - "uRL", - "uuid", - "wrapInside", - "wrapOffset", - "wrapped", - "bringInPerspective", - "resize", - "rotate", - "transform", + ( "translate", - ] - .into_iter() - .map(|m| later(l, "PageItem", m)), + method(l, transform::translate), + returns( + "undefined", + &[ + ("deltaX", "number"), + ("deltaY", "number"), + ("transformObjects", "boolean"), + ("transformFillPatterns", "boolean"), + ("transformFillGradients", "boolean"), + ("transformStrokePatterns", "boolean"), + ], + ), + ), + ( + "rotate", + method(l, transform::rotate), + returns( + "undefined", + &[ + ("angle", "number"), + ("changePositions", "boolean"), + ("changeFillPatterns", "boolean"), + ("changeFillGradients", "boolean"), + ("changeStrokePattern", "boolean"), + ("rotateAbout", "Transformation"), + ], + ), + ), + ( + "resize", + method(l, transform::resize), + returns( + "undefined", + &[ + ("scaleX", "number"), + ("scaleY", "number"), + ("changePositions", "boolean"), + ("changeFillPatterns", "boolean"), + ("changeFillGradients", "boolean"), + ("changeStrokePattern", "boolean"), + ("changeLineWidths", "number"), + ("scaleAbout", "Transformation"), + ], + ), + ), + ( + "transform", + method(l, transform::transform), + returns( + "undefined", + &[ + ("transformationMatrix", "Matrix"), + ("changePositions", "boolean"), + ("changeFillPatterns", "boolean"), + ("changeFillGradients", "boolean"), + ("changeStrokePattern", "boolean"), + ("changeLineWidths", "number"), + ("transformAbout", "Transformation"), + ], + ), + ), + ]); + page_item.extend(layers::page_item_members(l)); + page_item.extend( + ["artworkKnockout", "isIsolated", "pixelAligned", "sliced", "uRL", "uuid", "wrapInside", "wrapOffset", "wrapped", "bringInPerspective"] + .into_iter() + .map(|m| later(l, "PageItem", m)), ); page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| { - let mut members = variables::item_members(l, c); + let own = |c: &&&str| **c == "TextFrame" || images::CLASSES.contains(c) || tracing::CLASSES.contains(c); + classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| { + let mut members = layers::members(c, l); + members.extend(variables::item_members(l, c)); if *c == "PathItem" { members.extend(paths::path_item_members(l)); } @@ -3227,18 +3640,13 @@ fn classes(link: &Link) -> Vec { classes.extend(colors::classes(l)); classes.extend(text::classes(l)); classes.extend(variables::classes(l)); + classes.extend(layers::classes(l)); + classes.extend(images::classes(l)); + tracing::add_trace(&mut classes, l); + classes.extend(tracing::classes(l)); classes.extend(save_open::classes(l)); classes.extend(print::classes(l)); - classes.push(class( - "Layer", - None, - named(vec![ - ("typename", get(l, layer_typename), typed("string")), - ("name", get(l, layer_name), typed("string")), - ("toString", method(l, layer_to_string), returns("string", &[])), - ]), - None, - )); + classes.extend(raster_capture::classes(l)); classes.extend(tags::classes(l)); classes } diff --git a/crates/engine/src/script/dom/clipboard.rs b/crates/engine/src/script/dom/clipboard.rs new file mode 100644 index 0000000000..a6fb102f03 --- /dev/null +++ b/crates/engine/src/script/dom/clipboard.rs @@ -0,0 +1,56 @@ +//! `app.copy()`, `app.cut()` and `app.paste()`, as the help page +//! describes them: Edit › Copy, Cut +//! and Paste on the active document, run as `edit.copy`, `edit.cut` and `edit.paste` in the run's +//! transaction. +//! +//! VectorCraft's own rules, which the help page does not state: with nothing selected, or no +//! document open, `copy` and `cut` do nothing; with the clipboard empty `paste` does nothing; and +//! `paste` with no document open throws `No active document`. `paste` takes the session's +//! clipboard, not art another app copied since. A run that finishes after a Copy or Cut, by any +//! command, with the clipboard still holding what it copied, reports `copied`, and the desktop app +//! then offers the clipboard to other apps. + +use serde_json::json; +use vectorcraft_js::{Data, HostError}; + +use super::{Answer, Described, Host, Link, NO_ACTIVE_DOCUMENT, command, method, named, returns}; + +/// The clipboard functions of `Application`. +pub(super) fn app_members(link: &Link) -> Vec { + named(vec![ + ("copy", method(link, copy), returns("undefined", &[])), + ("cut", method(link, cut), returns("undefined", &[])), + ("paste", method(link, paste), returns("undefined", &[])), + ]) +} + +/// Runs `id` when the active document has something it acts on. +fn on_selection(h: &Host, id: &str) -> Answer { + let ready = crate::cmd::has_selection_guides_or_artboard_tool(&h.session.borrow()).is_ok(); + if ready { + command(h, id, &json!({}))?; + } + Ok(Data::Undefined) +} + +fn copy(h: &Host, _: &[Data]) -> Answer { + on_selection(h, "edit.copy") +} + +fn cut(h: &Host, _: &[Data]) -> Answer { + on_selection(h, "edit.cut") +} + +fn paste(h: &Host, _: &[Data]) -> Answer { + let ready = { + let s = h.session.borrow(); + if s.active().is_none() { + return Err(HostError::Error(NO_ACTIVE_DOCUMENT.into())); + } + !s.clipboard.is_empty() + }; + if ready { + command(h, "edit.paste", &json!({}))?; + } + Ok(Data::Undefined) +} diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index b9f0bb3a30..4de02e881b 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -39,7 +39,7 @@ const CLASSES: &[(&str, &[&str])] = &[ ("PatternColor", &[]), ]; -fn color_object(class: &str, values: &[(&str, f64)]) -> Data { +pub(super) fn color_object(class: &str, values: &[(&str, f64)]) -> Data { let mut items = vec![("typename".to_string(), text(class))]; items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v)))); Data::Object(items) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs new file mode 100644 index 0000000000..60f322e79f --- /dev/null +++ b/crates/engine/src/script/dom/images.rs @@ -0,0 +1,744 @@ +//! Placed and raster art in the script object model: `Document.placedItems` and +//! `Document.rasterItems`, and the members of `PlacedItem` and `RasterItem`, as the help pages +//! , +//! , +//! and +//! describe them. +//! +//! A `PlacedItem` is an image linked to its file, and a `RasterItem` an image whose pixels are in +//! the document. Placing runs `file.place` with `link`, relinking `links.relink` and embedding +//! `links.embed`, so each joins the run's transaction. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `PlacedItems.add()` gives a placed item with no file. Its `file` may be assigned once, which +//! places the file linked; after that, and on every other placed item, `file` is read-only and +//! `relink(file)` changes it. Every other member of an item with no file throws +//! [`FILE_REQUIRED`]; an item with no file is not in the document and is dropped when the run +//! ends. +//! - A file to place or relink is a `File` the script may read ([`crate::file_access::ScriptGate`]) +//! that holds an image, of at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is. +//! - `PlacedItem.file` throws `Script file access denied`, without the path, when the script may +//! not read the linked file. +//! - `embed()` turns the placed item into a raster item with the same id: the placed item is stale +//! after it, and `rasterItems` lists the raster item. An image whose file is missing throws +//! [`MISSING_LINK`] and stays linked. +//! - `bitsPerChannel`, `channels`, `imageColorSpace` and `transparent` come from the header of the +//! image's encoded pixels; `transparent` is true for an image with an alpha channel or a +//! transparent palette entry. `RasterItem.file` is `null`, `embedded` is true and takes only +//! `true`, and `status` is `RasterLinkState.NODATA`, since a raster item has no linked file. +//! - `matrix` maps the image's pixels (row 0 at the top) to script coordinates, as a record of +//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`, +//! and assigning the matrix it reads runs nothing; a matrix with no area, one that puts a +//! corner of the image outside the canvas, or one a nearly singular image cannot reach exactly +//! is refused. +//! `boundingBox` is the pixel rectangle at one point a pixel, in the run's coordinate system. + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_geom::{Affine, Point}; +use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, file_ref, file_ref_path, host_ref, host_ref_parts}; + +use super::{ + Answer, Coords, Described, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, command_value, + doc_of, doc_ref, edit_item, editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, + returns, text, typed, typename_of, variables, whole, with_doc, +}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The error of a member of a `PlacedItems.add()` result whose `file` was not assigned. +pub const FILE_REQUIRED: &str = "PlacedItem.file is required"; +/// The error of assigning `file` to a placed item that has one. +pub const FILE_READ_ONLY: &str = "PlacedItem.file is read-only: use relink"; +/// The error of embedding an image whose linked file cannot be found. +pub const MISSING_LINK: &str = "Linked image is missing"; +/// The error of placing or relinking a file that is not an image. +pub const NOT_AN_IMAGE: &str = "The file is not an image"; +/// The largest file a script places or relinks, in bytes. +pub const MAX_PLACED_BYTES: u64 = 256 << 20; +/// The most `PlacedItems.add()` results one run keeps. +pub const MAX_PENDING: usize = 1024; +/// The error of the `matrix` of an image drawn distorted. +const DISTORTED: &str = "the image is distorted and has no matrix"; +/// The smallest determinant a `matrix` takes, in square points a square pixel. +const MIN_DETERMINANT: f64 = 1e-12; +/// The members of a `Matrix` record, in the order of an affine matrix's six numbers. +const MATRIX_KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"]; + +/// The enumerations the members here give values of, as the help page +/// lists them. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("ImageColorSpace", &["CMYK", "DeviceN", "Grayscale", "Indexed", "LAB", "RGB", "Separation"]), + ("RasterLinkState", &["DATAFROMFILE", "DATAMODIFIED", "NODATA"]), +]; + +/// The classes this module defines, in place of the plain page item classes. +pub(super) const CLASSES: &[&str] = &["PlacedItem", "RasterItem"]; + +/// A document's uid, the document as it was, and the ids of its linked and embedded images then. +type Lists = (u64, Arc, Rc>, Rc>); + +/// What a run keeps for placed and raster items: the `PlacedItems.add()` results and the last +/// lists of a document's images. +#[derive(Default)] +pub(super) struct State { + pending: RefCell>, + lists: RefCell>, +} + +/// A `PlacedItems.add()` result: its document, how many times that document had been reverted then, +/// and its image once `file` placed one. +struct Pending { + uid: u64, + reverts: u64, + bound: Option, +} + +pub(super) fn bound_ref(h: &Host, st: &DocState, id: NodeId) -> Option { + let pending = h.dom.images.pending.borrow(); + let slot = pending.iter().position(|p| p.uid == st.uid && p.reverts == st.reverts && p.bound == Some(id))?; + Some(host_ref("PlacedItem", &[float(h.run), float(st.uid), 0.0, 0.0, float(st.reverts), float(slot as u64)])) +} + +/// The slot of a `PlacedItems.add()` result in this run, from its handle. A result whose document +/// was closed or reverted since is stale. +fn slot_of(h: &Host, run: f64, uid: f64, slot: f64) -> Result { + let stale = || HostError::Error(STALE_ITEM.into()); + let doc = find_doc(h, run, uid).ok_or_else(stale)?; + let reverts = h.session.borrow().documents().get(doc.index).map(|st| st.reverts); + let k = whole(slot).and_then(|k| usize::try_from(k).ok()).ok_or_else(stale)?; + match h.dom.images.pending.borrow().get(k) { + Some(p) if p.uid == doc.uid && Some(p.reverts) == reverts => Ok(k), + _ => Err(stale()), + } +} + +/// The id of the image a `PlacedItems.add()` result placed. +pub(super) fn pending_id(h: &Host, run: f64, uid: f64, slot: f64) -> Result { + let k = slot_of(h, run, uid, slot)?; + match h.dom.images.pending.borrow().get(k).and_then(|p| p.bound) { + Some(id) => Ok(id), + None => Err(HostError::Error(FILE_REQUIRED.into())), + } +} + +/// The handle's run, uid and slot when `d` is a `PlacedItems.add()` result. Its handle has six +/// numbers, where a page item's has five. +fn pending_handle(d: &Data) -> Option<[f64; 3]> { + match host_ref_parts(d) { + Some(("PlacedItem", handle)) => match handle.as_slice() { + [run, uid, _, _, _, slot] => Some([*run, *uid, *slot]), + _ => None, + }, + _ => None, + } +} + +/// The ids of a document's linked (`placed`) or embedded images, topmost first as [`page_items`] +/// lists them. +fn images(h: &Host, st: &DocState, placed: bool) -> Result>, HostError> { + let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() }; + if let Some(l) = &*h.dom.images.lists.borrow() + && l.0 == st.uid + && Arc::ptr_eq(&l.1, &st.doc) + { + return Ok(pick(l)); + } + let all = page_items(h, st)?; + h.charge_call(all.len() as u64)?; + let (mut linked, mut embedded) = (Vec::new(), Vec::new()); + for id in all.iter() { + if let Some(NodeKind::Image(im)) = st.doc.node(*id).map(|n| &n.kind) { + if im.link.is_some() { linked.push(*id) } else { embedded.push(*id) } + } + } + let l = (st.uid, st.doc.clone(), Rc::new(linked), Rc::new(embedded)); + let out = pick(&l); + *h.dom.images.lists.borrow_mut() = Some(l); + Ok(out) +} + +fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> { + match d { + Data::Object(o) => o.iter().find(|(n, _)| n == k).map(|(_, v)| v), + _ => None, + } +} + +// ---- PlacedItems and RasterItems ---- + +fn collection(placed: bool) -> &'static str { + if placed { "PlacedItems" } else { "RasterItems" } +} + +fn list_doc(h: &Host, a: &[Data], placed: bool) -> Result { + doc_of(h, arg(a, 0), collection(placed)) +} + +fn list_length(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + let n = with_doc(h, doc, |_, st| images(h, st, placed).map(|l| l.len()))?; + Ok(num(float(n as u64))) +} + +fn list_at(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + 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) }; + with_doc(h, doc, |_, st| Ok(images(h, st, placed)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn list_by_name(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + 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 = images(h, st, placed)?; + 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 list_index(h: &Host, a: &[Data], placed: bool) -> Answer { + match arg(a, 1) { + Data::String(_) => list_by_name(h, a, placed), + Data::Number(_) => match list_at(h, a, placed)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `removeAll()`: deletes every image of the collection in one command. A hidden or locked one, or +/// one in a hidden or locked layer or group, stops it before anything is deleted, and so does one on +/// a locked artboard. +fn list_remove_all(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let ids = images(h, st, placed)?; + let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !whole(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(); + Ok::<_, HostError>((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 objects: {list}"))); + } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } + 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) +} + +/// `PlacedItems.add()`: a placed item with no file yet, which assigning `file` places. +fn placed_add(h: &Host, a: &[Data]) -> Answer { + let doc = list_doc(h, a, true)?; + let reverts = h.session.borrow().documents().get(doc.index).map_or(0, |st| st.reverts); + let mut pending = h.dom.images.pending.borrow_mut(); + if pending.len() >= MAX_PENDING { + return Err(HostError::Range(format!("a run makes at most {MAX_PENDING} placed items with PlacedItems.add"))); + } + pending.push(Pending { uid: doc.uid, reverts, bound: None }); + Ok(host_ref("PlacedItem", &[float(h.run), float(doc.uid), 0.0, 0.0, float(reverts), float(pending.len() as u64 - 1)])) +} + +macro_rules! both { + ($($placed:ident, $raster:ident => $f:ident;)*) => { + $( + fn $placed(h: &Host, a: &[Data]) -> Answer { + $f(h, a, true) + } + fn $raster(h: &Host, a: &[Data]) -> Answer { + $f(h, a, false) + } + )* + }; +} + +both! { + placed_length, raster_length => list_length; + placed_at, raster_at => list_at; + placed_by_name, raster_by_name => list_by_name; + placed_index, raster_index => list_index; + placed_remove_all, raster_remove_all => list_remove_all; +} + +fn placed_parent(h: &Host, a: &[Data]) -> Answer { + Ok(doc_ref(h, list_doc(h, a, true)?.uid)) +} + +fn raster_parent(h: &Host, a: &[Data]) -> Answer { + Ok(doc_ref(h, list_doc(h, a, false)?.uid)) +} + +fn doc_placed(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("PlacedItems", &[float(h.run), float(doc.uid)])) +} + +fn doc_raster(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("RasterItems", &[float(h.run), float(doc.uid)])) +} + +// ---- files ---- + +/// Whether the script may read `path` now by its own read scope and the read roots +/// ([`crate::file_access::ScriptGate`]), without the open documents' files, or the files they link +/// to, that a command may also read. +fn may_read(h: &Host, path: &str) -> bool { + let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default()); + crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok() +} + +/// The real path of the `File` `d` gives as an image to place or relink: one the script may read +/// ([`super::super::files::Disk::open_target`], as `app.open` reads its file), a regular file of +/// at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is, and no error names the path. +/// What the file holds is checked by the command that places or relinks it, which reads it once. +fn image_path(h: &Host, d: &Data, what: &str) -> Result { + let path = file_ref_path(d).ok_or_else(|| HostError::Type(format!("{what} must be a File")))?; + if path.len() > super::super::files::MAX_PATH_CHARS { + return Err(HostError::Range(super::super::files::PATH_TOO_LONG.into())); + } + let unc = path.starts_with("\\\\") || path.starts_with("//"); + if path.is_empty() || path.contains('\0') || unc || path.split(['/', '\\']).any(|c| c == "..") { + return Err(HostError::Error(super::super::files::ACCESS_DENIED.into())); + } + let real = h.disk.borrow().open_target(path).map_err(|m| HostError::Error(m.into()))?; + let meta = std::fs::metadata(&real).map_err(|_| HostError::Error(super::super::files::NOT_FOUND.into()))?; + if !meta.is_file() { + return Err(HostError::Error(super::super::files::NOT_REGULAR.into())); + } + if meta.len() > MAX_PLACED_BYTES { + return Err(HostError::Range(format!("{what} is larger than {} MiB", MAX_PLACED_BYTES >> 20))); + } + Ok(crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()) +} + +/// Runs `f`, which places or relinks a file `image_path` gave, with `file.place` and `links.relink` +/// refusing a file that holds no image before the document changes: that refusal is +/// [`NOT_AN_IMAGE`], which does not name the path. The command reads the file once, for its check +/// and for the image it places. +fn image_only(h: &Host, f: impl FnOnce(&Host) -> Result) -> Result { + let kept = h.session.borrow().image_only.replace(Some(true)); + let r = f(h); + let refused = h.session.borrow().image_only.replace(kept) == Some(false); + match r { + Err(HostError::Error(_)) if refused => Err(HostError::Error(NOT_AN_IMAGE.into())), + r => r, + } +} + +// ---- PlacedItem ---- + +/// The item `this` names when it is a `cls` (`PlacedItem` or `RasterItem`). +fn this_of(h: &Host, a: &[Data], cls: &str) -> Result { + match host_ref_parts(arg(a, 0)) { + Some((c, _)) if c == cls => item_of(h, arg(a, 0)), + _ => Err(HostError::Type(format!("this is not a {cls}"))), + } +} + +/// Reads the image of the `cls` `this` names with `f`. +fn read_image(h: &Host, a: &[Data], cls: &str, f: impl FnOnce(&DocState, &crate::doc::Node, &crate::doc::ImageObject) -> Answer) -> Answer { + let item = this_of(h, a, cls)?; + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => match &n.kind { + NodeKind::Image(im) => f(st, n, im), + _ => Err(HostError::Error(STALE_ITEM.into())), + }, + None => Err(HostError::Error(STALE_ITEM.into())), + }) +} + +fn placed_file(h: &Host, a: &[Data]) -> Answer { + if let Some([run, uid, slot]) = pending_handle(arg(a, 0)) { + let k = slot_of(h, run, uid, slot)?; + if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_none()) { + // Null while its document is open; stale once that document is closed. + find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + return Ok(Data::Null); + } + } + let path = read_image(h, a, "PlacedItem", |st, _, im| { + let path = im.link.as_ref().and_then(|link| { + let base = crate::cmd::links::LinkBase::of(st); + crate::cmd::links::located_path(link, base).or_else(|| crate::cmd::fileio::document_path(&link.path, base.doc).ok()) + }); + let path = path.ok_or_else(|| HostError::Error(super::super::files::ACCESS_DENIED.into()))?; + Ok(text(path)) + })?; + let Data::String(path) = path else { return Ok(Data::Null) }; + if !may_read(h, &path) { + return Err(HostError::Error(super::super::files::ACCESS_DENIED.into())); + } + Ok(file_ref(&path)) +} + +/// `file = File`: places the file, linked, for a `PlacedItems.add()` result that has none. +fn placed_set_file(h: &Host, a: &[Data]) -> Answer { + let Some([run, uid, slot]) = pending_handle(arg(a, 0)) else { + if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PlacedItem") { + this_of(h, a, "PlacedItem")?; + return Err(HostError::Error(FILE_READ_ONLY.into())); + } + return Err(HostError::Type("this is not a PlacedItem".into())); + }; + let k = slot_of(h, run, uid, slot)?; + if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_some()) { + this_of(h, a, "PlacedItem")?; + return Err(HostError::Error(FILE_READ_ONLY.into())); + } + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let path = image_path(h, arg(a, 1), "PlacedItem.file")?; + // The ids are read from the command's own result, where every id is exact (a script number + // holds integers exactly only up to 2^53). + // The placement and its check run under one savepoint, so an error after the place leaves + // no linked image behind. + let id = super::atomically(h, |h| { + let (_, placed) = image_only(h, |h| on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true}))))?; + let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64)); + let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId); + let linked = + |id: NodeId| with_doc(h, doc, |_, st| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some())); + id.filter(|id| linked(*id)).ok_or_else(|| HostError::Error(NOT_AN_IMAGE.into())) + })?; + if let Some(p) = h.dom.images.pending.borrow_mut().get_mut(k) { + p.bound = Some(id); + } + Ok(Data::Undefined) +} + +/// `relink(file)`: `links.relink` of the item to the image in `file`. +fn placed_relink(h: &Host, a: &[Data]) -> Answer { + let item = this_of(h, a, "PlacedItem")?; + let path = image_path(h, arg(a, 1), "relink's file")?; + image_only(h, |h| edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path})))?; + Ok(Data::Undefined) +} + +/// `embed()`: `links.embed` of the item, which becomes a raster item. +fn placed_embed(h: &Host, a: &[Data]) -> Answer { + let item = this_of(h, a, "PlacedItem")?; + let info = on_doc(h, item.doc.uid, false, |h| command(h, "links.info", &json!({"id": item.id.0})))?; + if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") { + return Err(HostError::Error(MISSING_LINK.into())); + } + edit_item(h, item, "links.embed", &json!({"ids": [item.id.0]}))?; + let embedded = with_doc(h, item.doc, |_, st| matches!(st.doc.node(item.id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none())); + if !embedded { + return Err(HostError::Error(MISSING_LINK.into())); + } + Ok(Data::Undefined) +} + +// ---- both ---- + +/// `matrix`: the image's pixels to script coordinates. +fn matrix(h: &Host, a: &[Data], cls: &str) -> Answer { + read_image(h, a, cls, |st, n, im| { + if n.is_distorted_image() { + return Err(HostError::Error(DISTORTED.into())); + } + let f = frame(st)?; + let [a0, b0, c0, d0, e0, f0] = im.xf.as_coeffs(); + let m = match h.dom.coords.get() { + Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0], + Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top], + }; + let mut items = vec![("typename".to_string(), text("Matrix"))]; + items.extend(MATRIX_KEYS.iter().zip(m).map(|(k, v)| (k.to_string(), num(v)))); + Ok(Data::Object(items)) + }) +} + +/// The six numbers of the `Matrix` record `d`, `mValueA` to `mValueTY`, each finite. +fn matrix_value(d: &Data) -> Result<[f64; 6], HostError> { + let mut m = [0.0; 6]; + for (k, out) in MATRIX_KEYS.iter().zip(m.iter_mut()) { + *out = match field(d, k) { + Some(Data::Number(n)) if n.is_finite() => *n, + _ => return Err(HostError::Type(format!("matrix must be a Matrix with a finite {k}"))), + }; + } + Ok(m) +} + +/// Whether `m` gives a pixel an area of at least [`MIN_DETERMINANT`]. +fn area_of(m: Affine) -> bool { + let det = m.determinant(); + !det.is_nan() && det.abs() >= MIN_DETERMINANT +} + +/// `matrix = Matrix`: `object.transform` of the image by what takes its pixels to the new matrix. +/// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted +/// image is refused before anything changes, and so is a locked or hidden image or one on a locked +/// artboard, as the transform methods refuse them; the matrix the image has already changes nothing. +fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { + let item = this_of(h, a, cls)?; + let m = matrix_value(arg(a, 1))?; + let delta = with_doc(h, item.doc, |_, st| { + let Some((n, im)) = st.doc.node(item.id).and_then(|n| if let NodeKind::Image(im) = &n.kind { Some((n, im)) } else { None }) else { + return Err(HostError::Error(STALE_ITEM.into())); + }; + if n.is_distorted_image() { + return Err(HostError::Error(DISTORTED.into())); + } + // The transform methods' refusals: a locked or hidden image, one inside a locked or hidden + // layer or group, and one on a locked artboard, whether or not the matrix changes. + let d = &st.doc; + let line = d.ancestry(item.id); + let any = |f: fn(&vectorcraft_doc::Node) -> bool| { + line.as_ref().is_none_or(|l| l.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(f))) + }; + if any(|n| n.locked) { + return Err(HostError::Error(format!("{}: {}", super::transform::LOCKED, item.id.0))); + } + if any(|n| !n.visible) { + return Err(HostError::Error(format!("{}: {}", super::transform::HIDDEN, item.id.0))); + } + if super::on_locked_artboard(h, st, item.id) { + return Err(HostError::Error(format!("{}: {}", super::transform::ON_LOCKED_ARTBOARD, item.id.0))); + } + let f = frame(st)?; + let target = Affine::new(match h.dom.coords.get() { + Coords::Document => [m[0], -m[1], m[2], -m[3], m[4] + f.left0, f.bottom0 - m[5]], + Coords::Artboard => [m[0], m[1], m[2], m[3], m[4] + f.left, m[5] + f.top], + }); + if !area_of(target) { + return Err(HostError::Range("the matrix gives the image no area".into())); + } + let (w, ht) = (f64::from(im.width), f64::from(im.height)); + let limit = crate::MAX_COORD * 2.0; + let corners = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].map(|(x, y)| target * Point::new(x, y)); + if corners.iter().any(|p| !(p.x.abs() <= limit && p.y.abs() <= limit)) { + return Err(HostError::Range("the matrix puts the image outside the canvas".into())); + } + let old = im.xf; + // Unchanged means the numbers the `matrix` getter reports, compared exactly, so a small + // change such as `mValueTX` from 0 to 5e-10 still moves the image. A change that the + // conversion to document space rounds away leaves the image's matrix as it is and runs nothing. + // A coefficient the script left as the getter reports keeps the image's own value, so the + // conversion back does not shift an untouched axis. + let olds = old.as_coeffs(); + let [a0, b0, c0, d0, e0, f0] = olds; + let reported = match h.dom.coords.get() { + Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0], + Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top], + }; + let mut wanted = target.as_coeffs(); + for ((w, o), (r, v)) in wanted.iter_mut().zip(olds).zip(reported.iter().zip(m.iter())) { + if r == v { + *w = o; + } + } + if wanted == olds { + return Ok(None); + } + if !area_of(old) { + return Err(HostError::Error("the image has no area to transform".into())); + } + let target = Affine::new(wanted); + let [ta, tb, tc, td, te, tf] = wanted; + if [ta, tb, tc, td] == [a0, b0, c0, d0] { + // A move alone: the offset difference, without the error an inverse adds. + return Ok(Some([1.0, 0.0, 0.0, 1.0, te - e0, tf - f0])); + } + // A nearly singular image loses precision through the inverse; refuse a change that would + // not land where the script asked rather than move the image somewhere else. + let delta = target * old.inverse(); + let landed = delta * old; + if landed.as_coeffs() == olds { + return Ok(None); + } + let close = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].iter().all(|&(x, y)| { + let (p, q) = (landed * Point::new(x, y), target * Point::new(x, y)); + (p.x - q.x).abs() <= 1e-6 && (p.y - q.y).abs() <= 1e-6 + }); + if !close || !area_of(landed) { + return Err(HostError::Range("the matrix cannot be applied exactly to this image".into())); + } + Ok(Some(delta.as_coeffs())) + })?; + if let Some(d) = delta { + edit_item(h, item, "object.transform", &json!({"ids": [item.id.0], "matrix": d, "strokes": false}))?; + } + Ok(Data::Undefined) +} + +/// `boundingBox`: the pixel rectangle at one point a pixel, `[left, top, right, bottom]`. +fn bounding_box(h: &Host, a: &[Data], cls: &str) -> Answer { + read_image(h, a, cls, |_, _, im| { + let (w, ht) = (f64::from(im.width), f64::from(im.height)); + Ok(Data::Array(match h.dom.coords.get() { + Coords::Document => vec![num(0.0), num(ht), num(w), num(0.0)], + Coords::Artboard => vec![num(0.0), num(0.0), num(w), num(ht)], + })) + }) +} + +fn placed_matrix(h: &Host, a: &[Data]) -> Answer { + matrix(h, a, "PlacedItem") +} + +fn raster_matrix(h: &Host, a: &[Data]) -> Answer { + matrix(h, a, "RasterItem") +} + +fn placed_set_matrix(h: &Host, a: &[Data]) -> Answer { + set_matrix(h, a, "PlacedItem") +} + +fn raster_set_matrix(h: &Host, a: &[Data]) -> Answer { + set_matrix(h, a, "RasterItem") +} + +fn placed_box(h: &Host, a: &[Data]) -> Answer { + bounding_box(h, a, "PlacedItem") +} + +fn raster_box(h: &Host, a: &[Data]) -> Answer { + bounding_box(h, a, "RasterItem") +} + +// ---- RasterItem ---- + +/// The header of the raster item's encoded pixels. +fn header(h: &Host, a: &[Data], f: impl FnOnce(&craft_image_codecs::RasterInspection) -> Data) -> Answer { + read_image(h, a, "RasterItem", |st, _, im| { + let blob = st.doc.images.get(&im.key).ok_or_else(|| HostError::Error("the image's pixels are not in the document".into()))?; + match craft_image_codecs::inspect_raster(&blob.bytes) { + Ok(Some(i)) => Ok(f(&i)), + _ => Err(HostError::Error("the image's header does not describe its pixels".into())), + } + }) +} + +fn raster_bits(h: &Host, a: &[Data]) -> Answer { + header(h, a, |i| num(f64::from(i.bits_per_sample))) +} + +fn raster_channels(h: &Host, a: &[Data]) -> Answer { + header(h, a, |i| num(f64::from(i.channels))) +} + +fn raster_transparent(h: &Host, a: &[Data]) -> Answer { + use craft_image_codecs::RasterColorType as T; + header(h, a, |i| Data::Bool(matches!(i.color_type, T::GrayAlpha | T::Rgba | T::CmykAlpha) || i.transparent_index.is_some())) +} + +fn raster_color_space(h: &Host, a: &[Data]) -> Answer { + use craft_image_codecs::RasterColorType as T; + let space = header(h, a, |i| { + text(match i.color_type { + T::Bitmap | T::Gray | T::GrayAlpha => "ImageColorSpace.Grayscale", + T::Rgb | T::Rgba => "ImageColorSpace.RGB", + T::Cmyk | T::CmykAlpha => "ImageColorSpace.CMYK", + T::Indexed => "ImageColorSpace.Indexed", + T::Lab => "ImageColorSpace.LAB", + T::Other => "", + }) + })?; + match space { + Data::String(s) if s.is_empty() => Err(HostError::Error("the image's header does not describe its color space".into())), + d => Ok(d), + } +} + +fn raster_colorized(h: &Host, a: &[Data]) -> Answer { + read_image(h, a, "RasterItem", |st, n, im| { + let gray = st.doc.images.get(&im.key).is_some_and(|b| b.gray_source().is_some()); + Ok(Data::Bool(gray && n.extras().colorize.is_some())) + }) +} + +fn raster_embedded(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + Ok(Data::Bool(true)) +} + +/// `embedded = true` changes nothing; a raster item cannot be linked by assigning `false`. +fn raster_set_embedded(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + match arg(a, 1) { + Data::Bool(true) => Ok(Data::Undefined), + Data::Bool(false) => Err(HostError::Error("a raster item cannot be linked by setting embedded to false".into())), + _ => Err(HostError::Type("embedded must be true or false".into())), + } +} + +fn raster_file(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + Ok(Data::Null) +} + +fn raster_status(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + Ok(text("RasterLinkState.NODATA")) +} + +/// `Document.placedItems` and `Document.rasterItems`. +pub(super) fn document_members(l: &Link) -> Vec { + named(vec![ + ("placedItems", get(l, doc_placed), MemberInfo { collection: true, ..typed("PlacedItems") }), + ("rasterItems", get(l, doc_raster), MemberInfo { collection: true, ..typed("RasterItems") }), + ]) +} + +/// The collections, `PlacedItem` and `RasterItem`, after `PageItem`. +pub(super) fn classes(l: &Link) -> Vec { + let placed_list = named(vec![ + ("typename", typename_of("PlacedItems"), typed("string")), + ("length", get(l, placed_length), typed("number")), + ("parent", get(l, placed_parent), typed("Document")), + ("index", method(l, placed_index), returns("PlacedItem", &[("itemKey", "*")])), + ("getByName", method(l, placed_by_name), returns("PlacedItem", &[("name", "string")])), + ("removeAll", method(l, placed_remove_all), returns("undefined", &[])), + ("add", method(l, placed_add), returns("PlacedItem", &[])), + ]); + let raster_list = named(vec![ + ("typename", typename_of("RasterItems"), typed("string")), + ("length", get(l, raster_length), typed("number")), + ("parent", get(l, raster_parent), typed("Document")), + ("index", method(l, raster_index), returns("RasterItem", &[("itemKey", "*")])), + ("getByName", method(l, raster_by_name), returns("RasterItem", &[("name", "string")])), + ("removeAll", method(l, raster_remove_all), returns("undefined", &[])), + ]); + let mut placed = named(vec![ + ("file", property(l, placed_file, placed_set_file), typed("File")), + ("relink", method(l, placed_relink), returns("undefined", &[("relinkFrom", "File")])), + ("embed", method(l, placed_embed), returns("undefined", &[])), + ("matrix", property(l, placed_matrix, placed_set_matrix), typed("Matrix")), + ("boundingBox", get(l, placed_box), typed("Array")), + ]); + placed.extend(variables::item_members(l, "PlacedItem")); + let mut raster = named(vec![ + ("bitsPerChannel", get(l, raster_bits), typed("number")), + ("channels", get(l, raster_channels), typed("number")), + ("colorizedGrayscale", get(l, raster_colorized), typed("boolean")), + ("embedded", property(l, raster_embedded, raster_set_embedded), typed("boolean")), + ("file", get(l, raster_file), typed("File")), + ("imageColorSpace", get(l, raster_color_space), typed("ImageColorSpace")), + ("matrix", property(l, raster_matrix, raster_set_matrix), typed("Matrix")), + ("status", get(l, raster_status), typed("RasterLinkState")), + ("transparent", get(l, raster_transparent), typed("boolean")), + ("boundingBox", get(l, raster_box), typed("Array")), + ]); + raster.extend(variables::item_members(l, "RasterItem")); + raster.extend(["colorants", "colorize", "overprint"].into_iter().map(|m| later(l, "RasterItem", m))); + vec![ + class("PlacedItems", None, placed_list, Some(super::function(l, placed_at))), + class("RasterItems", None, raster_list, Some(super::function(l, raster_at))), + class("PlacedItem", Some("PageItem"), placed, None), + class("RasterItem", Some("PageItem"), raster, None), + ] +} diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs new file mode 100644 index 0000000000..59c4ea8ccf --- /dev/null +++ b/crates/engine/src/script/dom/layers.rs @@ -0,0 +1,1695 @@ +//! Layers, groups, compound paths and artboards in the script object model, as the help pages +//! , +//! , +//! , +//! , +//! , +//! and +//! describe them. +//! +//! A layer is named by its id and an artboard by its artboard id, so a handle keeps naming the same +//! one after others are added, moved or removed, and throws once it is gone. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's +//! `pageItems`, `groupItems`, `compoundPathItems` and `textFrames`, and a compound path's +//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` +//! hold every group or compound path at any depth, in the order of the document's `pageItems`. +//! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes +//! a sublayer on top of that layer's contents. The new layer becomes the current one. +//! - `locked` true means the layer is locked. +//! - `clipped = true` makes the group's topmost object, which must be a path, a compound path or +//! type, its clipping path, as the Layers panel's clipping mask button does; `false` releases it. +//! - A layer's `color` is an `RGBColor` object with values from 0 to 255. +//! - `CompoundPathItems.add()` makes an empty compound path. The first path a script moves into it +//! gives it its paint, as Make Compound Path takes the paint of a path it joins. +//! - `artboards.add` and `artboards.insert` stop at [`super::MAX_ARTBOARDS`] artboards in a +//! document, the limit `Documents.add` uses. Two artboards may have the same name. +//! - A layer's or artboard's `name` takes a number or a boolean as `String()` writes it. +//! - `Artboard.rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down; with global +//! rulers, setting it moves the document's zero point. +//! - `setActiveArtboardIndex` changes the view's active artboard: no undo step, and the run's report +//! lists it in `activeArtboards` for the app to show. The report also lists a document whose +//! active artboard has another index at the end of the run, because artboards were inserted, +//! removed or reordered before it. + +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_parts}; + +use super::{ + Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, + arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, + later, method, named, named_text, node_of, num, number, on_doc, on_doc_layer, page_items, placement_of, probing, property, reported_opacity, + returns, text, typed, typename, whole, with_doc, +}; +use crate::script::{Host, Link}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The error for a layer that was deleted, or that came from an earlier run. +pub const STALE_LAYER: &str = "Stale layer"; +/// The error for an artboard that was deleted, or that came from an earlier run. +pub const STALE_ARTBOARD: &str = "Stale artboard"; +/// The longest name a layer takes, in characters, as Layer Options keeps it. +pub const MAX_LAYER_NAME: usize = 512; + +type Result = std::result::Result; + +/// What a collection of art lists. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + /// Every page item. + Any, + /// Groups (`GroupItem`). + Group, + /// Compound paths (`CompoundPathItem`). + Compound, + /// Paths (`PathItem`). + Path, + /// Type (`TextFrame`), whose collection's other members are in `text.rs`. + Text, +} + +impl Kind { + fn class(self) -> &'static str { + match self { + Kind::Any => "PageItems", + Kind::Group => "GroupItems", + Kind::Compound => "CompoundPathItems", + Kind::Path => "PathItems", + Kind::Text => "TextFrames", + } + } + + fn holds(self, n: &crate::doc::Node) -> bool { + match self { + Kind::Any => typename(n).is_some(), + Kind::Group => typename(n) == Some("GroupItem"), + Kind::Compound => typename(n) == Some("CompoundPathItem"), + Kind::Path => typename(n) == Some("PathItem"), + Kind::Text => typename(n) == Some("TextFrame"), + } + } +} + +fn type_error(what: &str) -> HostError { + HostError::Type(format!("this is not a {what}")) +} + +/// The whole number under `key` in a command's own result (not the script's copy, whose numbers +/// are exact only up to 2^53), such as the id of the object it made. +fn result_id(v: &Value, key: &str) -> Option { + v.get(key).and_then(Value::as_u64) +} + +// ---- Layer ---- + +/// The layer `d` names, which must still be a layer of its document. +pub(super) fn layer_of(h: &Host, d: &Data) -> Result<(Doc, NodeId)> { + let Some(handle) = handle_of(d, "Layer") else { return Err(type_error("Layer")) }; + if handle.len() != 5 { + return Err(type_error("Layer")); + } + // A layer read before File › Revert is stale like the page items read with it. + let (doc, id) = node_of(h, &handle).ok_or_else(|| { + let reverted = matches!(handle.as_slice(), [run, uid, ..] if find_doc(h, *run, *uid).is_some()); + HostError::Error(if reverted { STALE_ITEM } else { STALE_LAYER }.into()) + })?; + let ok = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::doc::Node::is_layer)); + if !ok { + return Err(HostError::Error(STALE_LAYER.into())); + } + Ok((doc, id)) +} + +fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> { + layer_of(h, arg(a, 0)) +} + +fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { + host_ref("Layer", &layer_handle(h, uid, id)) +} + +/// The handle of layer `id` of the document with uid `uid`, as `item_ref` gives it. +fn layer_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] { + let [high, low] = id_parts(id); + [float(h.run), float(uid), high, low, float(reverts_of(h, uid))] +} + +/// Reads the layer `this` names with `f`. +fn read_layer(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Node) -> Answer) -> Answer { + let (doc, id) = this_layer(h, a)?; + with_doc(h, doc, |_, st| match st.doc.node(id) { + Some(n) => f(st, n), + None => Err(HostError::Error(STALE_LAYER.into())), + }) +} + +/// Runs `id` with `params` and the layer's id on its document, unless `unchanged` says the layer +/// already has what they set. +fn set_layer(h: &Host, a: &[Data], command_id: &str, unchanged: impl FnOnce(&crate::doc::Node) -> bool, params: Value) -> Answer { + let (doc, id) = this_layer(h, a)?; + let same = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(unchanged)); + if !same { + let mut p = params; + if let Some(o) = p.as_object_mut() { + o.insert("ids".into(), json!([id.0])); + } + on_doc(h, doc.uid, true, |h| command(h, command_id, &p))?; + } + Ok(Data::Undefined) +} + +fn layer_flags(n: &crate::doc::Node) -> (bool, bool, Option, crate::doc::LayerColor) { + match &n.kind { + NodeKind::Layer { printable, preview, dim_images, color, .. } => (*printable, *preview, *dim_images, *color), + _ => (true, true, None, crate::doc::LayerColor::Preset(0)), + } +} + +fn layer_name(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(text(n.name.clone().unwrap_or_default()))) +} + +/// A name a script assigns: a string, or a number or boolean as `String()` writes it. +fn name_text(d: &Data) -> Result { + match d { + Data::String(s) => Ok(s.clone()), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + Data::Bool(b) => Ok(b.to_string()), + _ => Err(HostError::Type("name must be a string".into())), + } +} + +fn layer_set_name(h: &Host, a: &[Data]) -> Answer { + let name = name_text(arg(a, 1))?; + if name.trim().is_empty() { + return Err(HostError::Range("a layer's name cannot be empty".into())); + } + if name.chars().count() > MAX_LAYER_NAME { + return Err(HostError::Range(format!("a layer's name has at most {MAX_LAYER_NAME} characters"))); + } + let params = json!({"name": &name}); + set_layer(h, a, "layer.setProps", |n| n.name.as_deref() == Some(name.as_str()), params) +} + +fn layer_visible(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(n.visible))) +} + +fn layer_set_visible(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "visible")?; + set_layer(h, a, "layer.setProps", |n| n.visible == v, json!({"visible": v})) +} + +fn layer_locked(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(n.locked))) +} + +fn layer_set_locked(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "locked")?; + set_layer(h, a, "layer.setProps", |n| n.locked == v, json!({"locked": v})) +} + +fn layer_printable(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).0))) +} + +fn layer_set_printable(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "printable")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).0 == v, json!({"printable": v})) +} + +fn layer_preview(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).1))) +} + +fn layer_set_preview(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "preview")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).1 == v, json!({"preview": v})) +} + +fn layer_dim(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).2.is_some()))) +} + +fn layer_set_dim(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "dimPlacedImages")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).2.is_some() == v, json!({"dimImages": v})) +} + +fn layer_opacity(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(num(reported_opacity(n.opacity)))) +} + +fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "opacity")?; + if !(0.0..=100.0).contains(&v) { + return Err(HostError::Range("opacity must be from 0 to 100".into())); + } + // The number the getter reports, or one that stores as the opacity the layer has, leaves the + // layer as it is. + set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v || n.opacity == (v / 100.0) as f32, json!({"opacity": v})) +} + +fn layer_color(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| { + let [r, g, b] = layer_flags(n).3.rgb(); + Ok(super::colors::color_object("RGBColor", &[("red", f64::from(r)), ("green", f64::from(g)), ("blue", f64::from(b))])) + }) +} + +/// `color = {red, green, blue}`: each a whole number from 0 to 255. +fn layer_set_color(h: &Host, a: &[Data]) -> Answer { + let Data::Object(o) = arg(a, 1) else { return Err(HostError::Type("color must be an object with red, green and blue".into())) }; + let mut rgb = [0u8; 3]; + for (slot, key) in rgb.iter_mut().zip(["red", "green", "blue"]) { + let v = o.iter().find(|(k, _)| k == key).map(|(_, v)| v).unwrap_or(&Data::Undefined); + let n = number(v, &format!("color.{key}"))?; + if n.fract() != 0.0 || !(0.0..=255.0).contains(&n) { + return Err(HostError::Range(format!("color.{key} must be a whole number from 0 to 255"))); + } + *slot = u8::try_from(whole(n).unwrap_or(0)).unwrap_or(0); + } + let hex = format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]); + set_layer(h, a, "layer.setProps", |n| layer_flags(n).3.rgb() == rgb, json!({"color": hex})) +} + +fn layer_parent(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(with_doc(h, doc, |_, st| match st.doc.parent_of(id) { + Some(p) => layer_ref(h, st.uid, p), + None => doc_ref(h, st.uid), + })) +} + +fn layer_typename(h: &Host, a: &[Data]) -> Answer { + this_layer(h, a)?; + Ok(text("Layer")) +} + +fn layer_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Layer", layer_name(h, a)) +} + +/// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is +/// not counted. The list comes from [`layers_listed`], so reading it for each layer of a loop +/// lists the layers once. Each read is still charged for the search through the list. +fn layer_z_position(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let at = with_doc(h, doc, |_, st| { + let list = layers_listed(h, st, st.doc.parent_of(id))?; + h.charge_call(list.len() as u64)?; + Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i)) + })?; + at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into())) +} + +fn layer_has_selected(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let selected = with_doc(h, doc, |_, st| { + // The scan is charged by every selected object it looks at. + let objects = &st.selection.objects; + let found = objects.iter().position(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id))); + h.charge_call(found.map_or(objects.len(), |i| i + 1) as u64)?; + Ok::<_, HostError>(found.is_some()) + })?; + Ok(Data::Bool(selected)) +} + +/// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every +/// child visited, including skipped children. +fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec) -> u64 { + let mut count = 0; + for child in n.children().into_iter().flatten() { + count += 1; + if child.is_ruler_guide() || !child.visible || child.locked || child.is_template() { + continue; + } + if child.is_layer() { + count += collect_editable_art(child, out); + } else { + out.push(child.id); + } + } + count +} + +/// `hasSelectedArtwork = false` deselects the layer's art with `select.toggle`; `true` adds its +/// visible, unlocked art with `select.add`. The rest of the selection, ruler guides included, stays, +/// and no command runs when there is nothing to deselect or add. +fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { + let on = boolean(arg(a, 1), "hasSelectedArtwork")?; + let (doc, id) = this_layer(h, a)?; + let (ids, over) = with_doc(h, doc, |s, st| { + let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); + let selected = &st.selection.objects; + h.charge_call(selected.len() as u64)?; + if !on { + return Ok::<_, HostError>((selected.iter().copied().filter(inside).collect::>(), false)); + } + let locks = st.doc.locked_artboards(); + let mut art = Vec::new(); + let count = st.doc.node(id).map_or(0, |n| collect_editable_art(n, &mut art)); + // The walk is charged by every node it looks at, hidden and locked ones included, whether + // or not anything is added. + h.charge_call(count)?; + // While an object is isolated, the art that holds it is replaced by the isolated object, + // or by what an isolated group or other container holds, as Select All takes it. + let isolated = st.isolation.and_then(|i| st.doc.node(i)); + let path = isolated.and_then(|c| st.doc.ancestry(c.id)).unwrap_or_default(); + let editable = path.iter().all(|i| st.doc.node(*i).is_some_and(|n| n.visible && !n.locked && !n.is_template())); + let mut candidates = Vec::with_capacity(art.len()); + for o in art { + match isolated { + Some(_) if path.contains(&o) && !editable => {} + Some(c) if path.contains(&o) && c.is_container() => { + // The same walk as the layer's, through any sublayer the container holds. + let visited = collect_editable_art(c, &mut candidates); + h.charge_call(visited)?; + } + Some(c) if path.contains(&o) => candidates.push(c.id), + _ => candidates.push(o), + } + } + let mut have: std::collections::HashSet = selected.iter().copied().collect(); + let mut ids = Vec::new(); + for o in candidates { + if have.contains(&o) + || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) + || (s.guides_locked() && crate::is_guide_path(&st.doc, o)) + { + continue; + } + // Only art that would be added counts toward the limit. + if selected.len() + ids.len() >= MAX_LISTED { + return Ok((ids, true)); + } + have.insert(o); + ids.push(o); + } + Ok((ids, false)) + })?; + if over { + return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))); + } + if ids.is_empty() { + return Ok(Data::Undefined); + } + let command_id = if on { "select.add" } else { "select.toggle" }; + on_doc(h, doc.uid, false, |h| command(h, command_id, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + Ok(Data::Undefined) +} + +fn layer_is_isolated(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(Data::Bool(with_doc(h, doc, |_, st| st.isolation == Some(id)))) +} + +fn layer_remove(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": [id.0]})))?; + Ok(Data::Undefined) +} + +/// The layers of `parent` (`None`: the top level), without its ruler guides and art. +fn art_count(d: &Document, parent: Option) -> usize { + d.children(parent).map_or(0, |c| crate::doc::Node::guide_run_start(c)) +} + +/// Moves the layer `id` to `index` of `parent` with `node.move`, unless it is there already. +fn put_layer(h: &Host, doc: Doc, id: NodeId, parent: Option, index: usize) -> Result<()> { + let now = with_doc(h, doc, |_, st| st.doc.position(id)); + if now.is_some_and(|(p, i, _)| p == parent && i == index) { + return Ok(()); + } + let parent = parent.map_or(Value::Null, |p| json!(p.0)); + on_doc(h, doc.uid, true, |h| command(h, "node.move", &json!({"id": id.0, "parent": parent, "index": index})))?; + Ok(()) +} + +/// `zOrder(method)`: the layer goes to the top or the bottom of the layers beside it, or one step. +fn layer_z_order(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let method = match arg(a, 1) { + Data::String(s) => s.as_str(), + _ => "", + }; + let (parent, index) = with_doc(h, doc, |_, st| { + let d = &st.doc; + let (parent, i, _) = d.position(id).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips)); + let count = art_count(d, parent); + let last = count.saturating_sub(1); + // One step passes the next layer beside it, and the art between them. + let layer_at = |j: &usize| d.children(parent).and_then(|c| c.get(*j)).is_some_and(|n| n.is_layer()); + let to = match method { + "ZOrderMethod.BRINGTOFRONT" => last, + "ZOrderMethod.BRINGFORWARD" => (i + 1..count).find(layer_at).unwrap_or(i), + "ZOrderMethod.SENDBACKWARD" => (floor.min(i)..i).rev().find(layer_at).unwrap_or(i), + "ZOrderMethod.SENDTOBACK" => floor.min(i), + _ => return Err(HostError::Type("zOrder needs a ZOrderMethod value".into())), + }; + Ok((parent, to)) + })?; + put_layer(h, doc, id, parent, index)?; + Ok(Data::Undefined) +} + +/// `move(relativeObject, insertionLocation?)`: the layer goes into another layer (on top of its +/// contents, or at the bottom with `PLACEATEND`), to the top level of a document, or directly +/// above or below another layer. +fn layer_move(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let how = placement_of(arg(a, 2))?; + let target = arg(a, 1); + let parent = if let Some(handle) = handle_of(target, "Document") { + let [run, uid] = handle.as_slice() else { return Err(type_error("Document")) }; + let to = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + if to.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + if matches!(how, Placement::Above | Placement::Below) { + return Err(HostError::Error("a layer goes above or below another layer, not a document".into())); + } + None + } else if handle_of(target, "Layer").is_some() { + let (to, t) = layer_of(h, target)?; + if to.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + Some(t) + } else if matches!(target, Data::Undefined) { + return Err(HostError::Type("move needs a relative object".into())); + } else { + return Err(HostError::Type("a layer's relative object must be a layer or a document".into())); + }; + let (into, index) = with_doc(h, doc, |_, st| { + let d = &st.doc; + if let Some(t) = parent + && d.ancestry(t).is_some_and(|a| a.contains(&id)) + && !(t == id && matches!(how, Placement::Above | Placement::Below)) + { + return Err(HostError::Error("a layer cannot go into itself".into())); + } + let (into, beside) = match (how, parent) { + (Placement::Above | Placement::Below, Some(t)) => (d.parent_of(t), Some(t)), + (_, p) => (p, None), + }; + if into.is_some_and(|p| !editable(d, p)) { + return Err(HostError::Error("the layer is hidden or locked".into())); + } + let from = d.position(id); + let here = |p: Option| from.is_some_and(|(q, ..)| q == p); + let count = art_count(d, into) - usize::from(here(into)); + let floor = usize::from(into.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips) && count > 0); + let index = match (how, beside) { + (Placement::Above | Placement::Below, Some(b)) => { + if b == id { + return Ok((into, from.map_or(0, |(_, i, _)| i))); + } + let (_, mut i, _) = d.position(b).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + if let Some((_, j, _)) = from + && here(into) + && j < i + { + i -= 1; + } + if how == Placement::Above { i + 1 } else { i } + } + (Placement::Bottom, _) => 0, + _ => count, + }; + Ok((into, index.max(floor))) + })?; + put_layer(h, doc, id, into, index)?; + Ok(arg(a, 0).clone()) +} + +// ---- Layers ---- + +/// The document and the layer (`None`: the top level) a `Layers` object lists. +fn layers_scope(h: &Host, d: &Data) -> Result<(Doc, Option)> { + let Some(handle) = handle_of(d, "Layers") else { return Err(type_error("Layers")) }; + match handle.as_slice() { + [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)), + [run, uid, high, low, reverts] => { + let (doc, id) = layer_of(h, &host_ref("Layer", &[*run, *uid, *high, *low, *reverts]))?; + Ok((doc, Some(id))) + } + _ => Err(type_error("Layers")), + } +} + +/// The layers of `parent` (`None`: the top level), top first. +fn layer_list(d: &Document, parent: Option) -> Vec { + let list = match parent { + None => Some(&d.layers), + Some(p) => d.children(Some(p)), + }; + #[cfg(test)] + super::LAYER_SCANS.with(|c| c.set(c.get() + list.map_or(0, |l| l.len() as u64))); + list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect() +} + +/// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top +/// level) and the layers it listed then. +pub(super) type LayerList = (u64, Arc, Option, Rc>); + +/// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while +/// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list +/// is charged by the objects it looks at. +fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result>> { + { + let mut lists = h.dom.layers.borrow_mut(); + let at = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent); + if let Some(at) = at { + let list = lists.remove(at); + let ids = list.3.clone(); + lists.push(list); + return Ok(ids); + } + } + let looked_at = match parent { + None => st.doc.layers.len(), + Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len), + }; + h.charge_call(looked_at as u64)?; + let ids = Rc::new(layer_list(&st.doc, parent)); + let mut lists = h.dom.layers.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= ART_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), parent, ids.clone())); + Ok(ids) +} + +fn layers_of(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(host_ref("Layers", &layer_handle(h, doc.uid, id))) +} + +fn layers_length(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + Ok(num(float(with_doc(h, doc, |_, st| layers_listed(h, st, parent).map(|l| l.len()))? as u64))) +} + +fn layers_parent(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + Ok(parent.map_or_else(|| doc_ref(h, doc.uid), |p| layer_ref(h, doc.uid, p))) +} + +fn layers_typename(h: &Host, a: &[Data]) -> Answer { + layers_scope(h, arg(a, 0))?; + Ok(text("Layers")) +} + +/// `collection["name"]` as `getByName` reads it, or `undefined` for `"name" in collection` when +/// nothing has the name, as the document's `pageItems` does. +fn read_by_name(h: &Host, a: &[Data], by_name: fn(&Host, &[Data]) -> Answer) -> Answer { + match by_name(h, a) { + Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), + r => r, + } +} + +fn layers_at(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + if let Data::String(_) = arg(a, 1) { + return read_by_name(h, a, layers_by_name); + } + 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) }; + with_doc(h, doc, |_, st| Ok(layers_listed(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) +} + +fn layers_by_name(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + 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 = layers_listed(h, st, parent)?; + 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| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn layers_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => layers_by_name(h, a), + Data::Number(_) => match layers_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `layers.add()`: a new layer above every top-level layer, or a sublayer on top of the layer's +/// contents. → the new layer, which is the current one. +fn layers_add(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + if let Some(p) = parent { + let ok = with_doc(h, doc, |_, st| editable(&st.doc, p)); + if !ok { + return Err(HostError::Error("the layer is hidden or locked".into())); + } + } + let (_, r) = on_doc_layer(h, doc.uid, true, false, |h| match parent { + None => command_value(h, "layer.new", &json!({"top": true})), + Some(p) => command_value(h, "layer.newSublayer", &json!({"parent": p.0})), + })?; + let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the layer was not made".into()))?; + Ok(layer_ref(h, doc.uid, NodeId(id))) +} + +/// `layers.removeAll()`: deletes every layer of the collection in one command. A document keeps a +/// layer, so on the top-level layers it throws before anything is deleted. +fn layers_remove_all(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + if parent.is_none() { + return Err(HostError::Error("a document needs at least one layer".into())); + } + let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?; + // `layer.delete` takes at most this many rows; more is refused before anything is deleted. + if ids.len() > crate::cmd::layer::MAX_ROWS { + return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- GroupItems, CompoundPathItems and a container's PageItems ---- + +/// The document and the layer, group or compound path (`None`: the whole document) an art +/// collection of `class` lists. +fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { + let Some(handle) = handle_of(d, class) else { return Err(type_error(class)) }; + match handle.as_slice() { + [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)), + [run, uid, high, low, reverts] => { + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + // A collection read before File › Revert is stale like its container. + let holds = with_doc(h, doc, |_, st| { + whole(*reverts) == Some(st.reverts) + && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. })) + }); + if !holds { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok((doc, Some(id))) + } + _ => Err(type_error(class)), + } +} + +/// A document's uid, the document as it was, the [`Kind`] and the container of an art collection, +/// and the ids it listed then. +pub(super) type ArtList = (u64, Arc, u8, Option, Rc>); + +/// How many lists of art [`super::State`] keeps at once. +pub(super) const ART_LISTS: usize = 4; + +/// The objects of `kind` in `container` (directly), topmost first, or in the whole document at any +/// depth, in the order of the document's `pageItems`. The last [`ART_LISTS`] lists are kept while +/// their documents are unchanged, so a loop over groups that reads each group's `pageItems` builds +/// each list once. Each new list is charged by the objects it looks at. +fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result>> { + { + let mut lists = h.dom.art.borrow_mut(); + let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == kind as u8 && *c == container); + if let Some(at) = at { + let list = lists.remove(at); + let ids = list.4.clone(); + lists.push(list); + return Ok(ids); + } + } + #[cfg(test)] + super::ART_SCANS.with(|c| c.set(c.get() + 1)); + let ids: Vec = match container { + None => { + let all = page_items(h, st)?; + h.charge_call(all.len() as u64)?; + all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect() + } + Some(c) => { + let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); + h.charge_call(children.len() as u64)?; + children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect() + } + }; + let ids = Rc::new(ids); + let mut lists = h.dom.art.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= ART_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), kind as u8, container, ids.clone())); + Ok(ids) +} + +/// Whether a `PageItems` or `PathItems` object's handle names its container. +pub(super) fn is_scoped(a: &[Data], class: &str) -> bool { + host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == class && handle.len() == 5) +} + +fn scoped_kind(a: &[Data]) -> Kind { + if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PathItems") { Kind::Path } else { Kind::Any } +} + +/// How many times File › Revert has reloaded the document with uid `uid`. +fn reverts_of(h: &Host, uid: u64) -> u64 { + h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts) +} + +fn collection(h: &Host, kind: Kind, container: Option, uid: u64) -> Data { + match container { + Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1], float(reverts_of(h, uid))]), + None => host_ref(kind.class(), &[float(h.run), float(uid)]), + } +} + +fn art_length(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + let n = with_doc(h, doc, |_, st| art_list(h, st, kind, c).map(|l| l.len()))?; + Ok(num(float(n as u64))) +} + +fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) +} + +fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + if let Data::String(_) = arg(a, 1) { + return match art_by_name(h, a, kind) { + Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), + r => r, + }; + } + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) { + Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))), + // The text of a number that is not an array index is looked up as a name. + None => with_doc(h, doc, |_, st| { + let ids = art_list(h, st, kind, c)?; + h.charge_call(ids.len() as u64)?; + let name = vectorcraft_js::number_to_string(*n); + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id))) + }), + } +} + +fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + 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 = art_list(h, st, kind, c)?; + 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 art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { + match arg(a, 1) { + Data::String(_) => art_by_name(h, a, kind), + // A number is a position only. A stale collection throws its stale error first. + Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => { + art_scope(h, arg(a, 0), kind.class())?; + Err(HostError::Error(NOT_FOUND.into())) + } + Data::Number(_) => match art_at(h, a, kind)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `removeAll()`: deletes every object the collection lists (those inside another listed one go +/// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or +/// one on a locked artboard stops it before anything is deleted, as the document's +/// `pageItems.removeAll()` is stopped. +fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| { + let all = art_list(h, st, kind, c)?; + let d = &st.doc; + let listed: std::collections::HashSet = all.iter().copied().collect(); + let ids: Vec = + all.iter().copied().filter(|i| !d.ancestry(*i).is_some_and(|a| a.iter().any(|x| *x != *i && listed.contains(x)))).collect(); + let whole = |id: &NodeId| editable(d, *id) && d.node(*id).is_some_and(super::all_editable); + let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); + let locks = d.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + // A clipping path whose group or layer keeps other art would leave the next object clipping it. + let going: std::collections::HashSet = ids.iter().copied().collect(); + let masks: Vec = ids + .iter() + .filter(|i| { + d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| { + let kids = p.children().map_or(&[][..], Vec::as_slice); + p.clips() + && kids.first().is_some_and(|f| f.id == **i) + && kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. })) + }) + }) + .map(|i| i.0) + .take(20) + .collect(); + Ok::<_, HostError>((ids, refused, on_locked, masks)) + })?; + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); + } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } + if !masks.is_empty() { + let list = masks.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" + ))); + } + // Deleting the objects above an image in an ordinary group named as a tracing would make it one. + if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": true})))?; + } + Ok(Data::Undefined) +} + +/// The scoped art of a container, read by `PageItems` and `PathItems` ([`is_scoped`]). +pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, scoped_kind(a)) +} + +pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, scoped_kind(a)) +} + +pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, scoped_kind(a)) +} + +pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, scoped_kind(a)) +} + +pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, scoped_kind(a)) +} + +pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, scoped_kind(a)) +} + +fn groups_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Group) +} +fn groups_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Group) +} +fn groups_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Group) +} +fn groups_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Group) +} +fn groups_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Group) +} +fn groups_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Group) +} +fn compounds_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Compound) +} +fn compounds_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Compound) +} +fn compounds_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Compound) +} +fn compounds_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Compound) +} +fn compounds_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Compound) +} +fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Compound) +} + +fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { + art_scope(h, arg(a, 0), kind.class())?; + Ok(text(kind.class())) +} + +pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, scoped_kind(a)) +} +fn groups_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Group) +} +fn compounds_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Compound) +} + +/// `groupItems.add()` and `compoundPathItems.add()`: an empty group or compound path on top of the +/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. +/// → the new object. +fn container_add(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + if let Some(c) = c { + let compound = with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + if compound { + return Err(HostError::Error("a compound path holds only paths".into())); + } + } + let mut params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); + if kind == Kind::Compound + && let Some(o) = params.as_object_mut() + { + o.insert("compound".into(), json!(true)); + } + let (_, r) = on_doc(h, doc.uid, true, |h| command_value(h, "object.newGroup", ¶ms))?; + let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the object was not made".into()))?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, NodeId(id))) +} + +fn groups_add(h: &Host, a: &[Data]) -> Answer { + container_add(h, a, Kind::Group) +} + +fn compounds_add(h: &Host, a: &[Data]) -> Answer { + container_add(h, a, Kind::Compound) +} + +// ---- The art collections of a document, a layer, a group and a compound path ---- + +/// The collection of `kind` the object `this` holds: a document's (`Document`), a layer's +/// (`Layer`) or a page item's. +fn held(h: &Host, a: &[Data], kind: Kind) -> Answer { + let this = arg(a, 0); + if handle_of(this, "Document").is_some() { + let doc = doc_of(h, this, "Document")?; + return Ok(collection(h, kind, None, doc.uid)); + } + if handle_of(this, "Layer").is_some() { + let (doc, id) = layer_of(h, this)?; + return Ok(collection(h, kind, Some(id), doc.uid)); + } + let item = item_of(h, this)?; + Ok(collection(h, kind, Some(item.id), item.doc.uid)) +} + +fn held_page_items(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Any) +} + +fn held_paths(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Path) +} + +fn held_groups(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Group) +} + +fn held_compounds(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Compound) +} + +fn held_text(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Text) +} + +/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists. +pub(super) fn text_scope(h: &Host, d: &Data) -> Result<(Doc, Option)> { + art_scope(h, d, Kind::Text.class()) +} + +/// The type objects directly in `container`, topmost first. +pub(super) fn text_list(h: &Host, st: &DocState, container: NodeId) -> Result>> { + art_list(h, st, Kind::Text, Some(container)) +} + +// ---- GroupItem and CompoundPathItem ---- + +fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { + let item = item_of(h, arg(a, 0))?; + let ok = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename) == Some(what)); + if !ok { + return Err(type_error(what)); + } + Ok(item) +} + +/// The layer the object is in. +fn item_layer(h: &Host, a: &[Data]) -> Answer { + let item = item_of(h, arg(a, 0))?; + Ok(with_doc(h, item.doc, |_, st| st.doc.layer_containing(item.id).map_or(Data::Null, |l| layer_ref(h, st.uid, l)))) +} + +fn group_clipped(h: &Host, a: &[Data]) -> Answer { + let item = this_item_of(h, a, "GroupItem")?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(crate::doc::Node::clips)))) +} + +/// `clipped = true`: the group's topmost object becomes its clipping path; `false` releases the +/// clipping mask. The group keeps its id either way. A hidden or locked topmost object is refused +/// before it loses its paint. +fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { + let on = boolean(arg(a, 1), "clipped")?; + let item = this_item_of(h, a, "GroupItem")?; + let (now, ok, top) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let top = d.node(item.id).and_then(|n| n.children()).and_then(|c| c.iter().rev().find(|c| !c.is_ruler_guide())).map(|c| c.id); + (d.node(item.id).is_some_and(crate::doc::Node::clips), editable(d, item.id), top.filter(|t| !editable(d, *t))) + }); + if now == on { + return Ok(Data::Undefined); + } + super::refuse_protected_edit(h, item)?; + if !ok { + return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0))); + } + if let Some(t) = top.filter(|_| on) { + return Err(HostError::Error(format!("Cannot clip GroupItem {}: its topmost object {} is hidden or locked", item.id.0, t.0))); + } + on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?; + Ok(Data::Undefined) +} + +/// The members `layers.rs` adds to `PageItem`'s. +pub(super) fn page_item_members(l: &Link) -> Vec { + named(vec![("layer", get(l, item_layer), typed("Layer"))]) +} + +/// The members a page item class adds to `PageItem`'s. +pub(super) fn members(class: &str, l: &Link) -> Vec { + match class { + "GroupItem" => { + let mut m = named(vec![ + ("clipped", property(l, group_clipped, group_set_clipped), typed("boolean")), + ("pageItems", get(l, held_page_items), listed("PageItems")), + ("groupItems", get(l, held_groups), listed("GroupItems")), + ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("textFrames", get(l, held_text), listed("TextFrames")), + ]); + m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m + } + "CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]), + _ => Vec::new(), + } +} + +/// What `reflect` tells of a member whose value is a collection of class `data_type`. +fn listed(data_type: &str) -> MemberInfo { + MemberInfo { collection: true, ..typed(data_type) } +} + +// ---- Document ---- + +fn doc_layers(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Layers", &[float(h.run), float(doc.uid)])) +} + +fn doc_active_layer(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()).map_or(Data::Null, |l| layer_ref(h, st.uid, l)))) +} + +/// `activeLayer = layer`: the layer becomes the current one, where new art goes. +fn doc_set_active_layer(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + let (to, id) = layer_of(h, arg(a, 1))?; + if to.uid != doc.uid { + return Err(HostError::Error("the layer is in another document".into())); + } + let now = with_doc(h, doc, |_, st| st.current_layer()); + if now != Some(id) { + on_doc_layer(h, doc.uid, true, false, |h| command(h, "layer.setCurrent", &json!({"id": id.0})))?; + } + Ok(Data::Undefined) +} + +fn doc_artboards(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Artboards", &[float(h.run), float(doc.uid)])) +} + +/// The members `layers.rs` adds to `Document`'s. +pub(super) fn document_members(l: &Link) -> Vec { + named(vec![ + ("layers", get(l, doc_layers), listed("Layers")), + ("activeLayer", property(l, doc_active_layer, doc_set_active_layer), typed("Layer")), + ("groupItems", get(l, held_groups), listed("GroupItems")), + ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("artboards", get(l, doc_artboards), listed("Artboards")), + ]) +} + +// ---- Artboard and Artboards ---- + +/// The document of an artboard. +#[derive(Clone, Copy)] +struct Board { + doc: Doc, +} + +fn board_index(st: &DocState, id: u32) -> Option { + st.doc.artboards.iter().position(|a| a.id == id) +} + +fn board_of(h: &Host, d: &Data) -> Result<(Board, usize)> { + let Some(handle) = handle_of(d, "Artboard") else { return Err(type_error("Artboard")) }; + let [run, uid, id, reverts] = handle.as_slice() else { return Err(type_error("Artboard")) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; + let id = whole(*id).and_then(|i| u32::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; + // An artboard read before File › Revert is stale, as the page items read with it are. + let index = with_doc(h, doc, |_, st| board_index(st, id).filter(|_| whole(*reverts) == Some(st.reverts))) + .ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; + Ok((Board { doc }, index)) +} + +fn board_ref(h: &Host, uid: u64, id: u32) -> Data { + host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts_of(h, uid))]) +} + +fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> { + board_of(h, arg(a, 0)) +} + +/// Reads the artboard `this` names with `f`. +fn read_board(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Artboard, usize) -> Answer) -> Answer { + let (b, i) = this_board(h, a)?; + with_doc(h, b.doc, |_, st| match st.doc.artboards.get(i) { + Some(ab) => f(st, ab, i), + None => Err(HostError::Error(STALE_ARTBOARD.into())), + }) +} + +/// Runs `artboard.setProps` with `props` for the artboard, unless `unchanged` says it has them. +fn set_board(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Artboard) -> bool, props: Value) -> Answer { + let (b, i) = this_board(h, a)?; + let same = with_doc(h, b.doc, |_, st| st.doc.artboards.get(i).is_some_and(unchanged)); + if !same { + let mut p = props; + if let Some(o) = p.as_object_mut() { + o.insert("index".into(), json!(i)); + } + on_doc(h, b.doc.uid, true, |h| command(h, "artboard.setProps", &p))?; + } + Ok(Data::Undefined) +} + +fn board_rect(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |st, ab, _| Ok(frame(st)?.bounds(h.dom.coords.get(), ab.rect))) +} + +/// A rectangle `[left, top, right, bottom]` a script gave, in document coordinates, checked: finite, +/// inside the canvas, and from 1 to [`super::MAX_SIZE`] points on each side, the sides the artboard +/// commands keep. +fn rect_arg(h: &Host, st: &DocState, d: &Data, what: &str) -> Result { + let Data::Array(v) = d else { return Err(HostError::Type(format!("{what} must be an array of four numbers"))) }; + let [l, t, r, b] = v.as_slice() else { return Err(HostError::Type(format!("{what} must be an array of four numbers"))) }; + let n = |d: &Data| super::coordinate(d, what); + let (l, t, r, b) = (n(l)?, n(t)?, n(r)?, n(b)?); + let f = frame(st)?; + let c = h.dom.coords.get(); + let p = f.to_document(c, [l, t]); + let q = f.to_document(c, [r, b]); + let rect = vectorcraft_geom::Rect::new(p.x.min(q.x), p.y.min(q.y), p.x.max(q.x), p.y.max(q.y)); + if q.x <= p.x || q.y <= p.y { + return Err(HostError::Range(format!("{what} must have its right side right of its left side and its bottom below its top"))); + } + if rect.width() < 1.0 || rect.height() < 1.0 { + return Err(HostError::Range(format!("{what} must be at least 1 point wide and tall"))); + } + if rect.width() > super::MAX_SIZE || rect.height() > super::MAX_SIZE { + return Err(HostError::Range(format!("{what} must be at most 3999856 points wide and tall"))); + } + if [rect.x0, rect.y0, rect.x1, rect.y1].iter().any(|v| v.abs() > crate::MAX_COORD) { + return Err(HostError::Range(format!("{what} is outside the canvas"))); + } + Ok(rect) +} + +fn board_set_rect(h: &Host, a: &[Data]) -> Answer { + let (b, _) = this_board(h, a)?; + let r = with_doc(h, b.doc, |_, st| rect_arg(h, st, arg(a, 1), "artboardRect"))?; + let close = |x: f64, y: f64| (x - y).abs() < 1e-9; + set_board( + h, + a, + |ab| close(ab.rect.x0, r.x0) && close(ab.rect.y0, r.y0) && close(ab.rect.x1, r.x1) && close(ab.rect.y1, r.y1), + json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height()}), + ) +} + +fn board_name(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(text(ab.name.clone()))) +} + +/// A new artboard name: at most [`MAX_TEXT_BYTES`] bytes; a number or boolean as `String()` writes +/// it. Another artboard may have the same name. → the name, trimmed as `artboard.setProps` trims +/// it; an empty one gives the artboard its default name, `Artboard N` for the Nth artboard. +fn board_name_arg(d: &Data, index: usize) -> Result { + let name = name_text(d)?; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let name = name.trim(); + Ok(if name.is_empty() { format!("Artboard {}", index + 1) } else { name.to_string() }) +} + +fn board_set_name(h: &Host, a: &[Data]) -> Answer { + let (_, i) = this_board(h, a)?; + let name = board_name_arg(arg(a, 1), i)?; + set_board(h, a, |ab| ab.name == name, json!({"name": &name})) +} + +fn board_parent(h: &Host, a: &[Data]) -> Answer { + let (b, _) = this_board(h, a)?; + Ok(doc_ref(h, b.doc.uid)) +} + +fn board_typename(h: &Host, a: &[Data]) -> Answer { + this_board(h, a)?; + Ok(text("Artboard")) +} + +fn board_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Artboard", board_name(h, a)) +} + +/// `rulerOrigin`: where the rulers measure from with this artboard active, from its top-left corner +/// with Y down. +fn board_ruler_origin(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |st, ab, i| { + let o = st.doc.ruler_origin_for(i); + Ok(super::pair([o.x - ab.rect.x0, o.y - ab.rect.y0])) + }) +} + +fn board_set_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let p = super::point(arg(a, 1), "rulerOrigin")?; + let (b, i) = this_board(h, a)?; + let (to, now) = with_doc(h, b.doc, |_, st| { + let ab = &st.doc.artboards[i]; + (vectorcraft_geom::Point::new(ab.rect.x0 + p[0], ab.rect.y0 + p[1]), st.doc.ruler_origin_for(i)) + }); + if to.distance(now) > 1e-9 { + on_doc(h, b.doc.uid, false, |h| command(h, "document.setRulerOrigin", &json!({"x": to.x, "y": to.y, "artboard": i})))?; + } + Ok(Data::Undefined) +} + +fn board_par(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(num(ab.video_ruler_pixel_aspect_ratio))) +} + +fn board_set_par(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "rulerPAR")?; + if !crate::doc::VIDEO_PIXEL_ASPECT_RANGE.contains(&v) { + return Err(HostError::Range("rulerPAR must be from 0.1 to 10".into())); + } + set_board(h, a, |ab| (ab.video_ruler_pixel_aspect_ratio - v).abs() < 1e-12, json!({"videoRulerPixelAspectRatio": v})) +} + +fn board_center(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_center_mark))) +} + +fn board_set_center(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showCenter")?; + set_board(h, a, |ab| ab.show_center_mark == v, json!({"showCenterMark": v})) +} + +fn board_cross_hairs(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_cross_hairs))) +} + +fn board_set_cross_hairs(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showCrossHairs")?; + set_board(h, a, |ab| ab.show_cross_hairs == v, json!({"showCrossHairs": v})) +} + +fn board_safe_areas(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_video_safe_areas))) +} + +fn board_set_safe_areas(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showSafeAreas")?; + set_board(h, a, |ab| ab.show_video_safe_areas == v, json!({"showVideoSafeAreas": v})) +} + +fn board_remove(h: &Host, a: &[Data]) -> Answer { + let (b, i) = this_board(h, a)?; + on_doc(h, b.doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + Ok(Data::Undefined) +} + +fn boards_doc(h: &Host, a: &[Data]) -> Result { + doc_of(h, arg(a, 0), "Artboards") +} + +fn boards_length(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.artboards.len()) as u64))) +} + +fn boards_parent(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn boards_typename(h: &Host, a: &[Data]) -> Answer { + boards_doc(h, a)?; + Ok(text("Artboards")) +} + +/// `toString()` of a collection: `[Class]`, after the same checks of the collection as `typename`. +fn layers_to_string(h: &Host, a: &[Data]) -> Answer { + layers_scope(h, arg(a, 0))?; + Ok(text("[Layers]")) +} +fn groups_to_string(h: &Host, a: &[Data]) -> Answer { + check_groups(h, arg(a, 0))?; + Ok(text("[GroupItems]")) +} +/// Fails when `d` is not a `GroupItems` collection or the document, layer or group it lists is gone. +pub(super) fn check_groups(h: &Host, d: &Data) -> Result<()> { + art_scope(h, d, Kind::Group.class()).map(|_| ()) +} +fn compounds_to_string(h: &Host, a: &[Data]) -> Answer { + art_scope(h, arg(a, 0), Kind::Compound.class())?; + Ok(text("[CompoundPathItems]")) +} +fn boards_to_string(h: &Host, a: &[Data]) -> Answer { + boards_doc(h, a)?; + Ok(text("[Artboards]")) +} + +/// An artboard index argument: a whole number below `len` (`len + 1` with `insert`). +fn board_index_arg(d: &Data, len: usize, what: &str) -> Result { + let n = number(d, what)?; + whole(n) + .and_then(|i| usize::try_from(i).ok()) + .filter(|i| *i < len) + .ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 0 to {}", len.saturating_sub(1)))) +} + +fn boards_at(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + if let Data::String(_) = arg(a, 1) { + return read_by_name(h, a, boards_by_name); + } + 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| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id)))) +} + +fn boards_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = boards_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| { + h.charge_call(st.doc.artboards.len() as u64)?; + let ab = st.doc.artboards.iter().find(|ab| ab.name == *name); + ab.map(|ab| board_ref(h, st.uid, ab.id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn boards_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => boards_by_name(h, a), + Data::Number(_) => match boards_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// A new artboard at `rect` with `artboard.new`, moved to `at` (`None`: it stays last) with +/// `artboard.reorder`; when either fails, the document is as it was. → the artboard. +fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { + let doc = boards_doc(h, a)?; + let (r, len, name) = with_doc(h, doc, |_, st| { + let boards = &st.doc.artboards; + h.charge_call(boards.len() as u64)?; + // The first "Artboard N" from one past the count that no artboard has. + let name = (boards.len() + 1..).map(|n| format!("Artboard {n}")).find(|n| !boards.iter().any(|ab| ab.name == *n)).unwrap_or_default(); + Ok::<_, HostError>((rect_arg(h, st, arg(a, 1), "artboardRect")?, boards.len(), name)) + })?; + let to = at.map(|d| board_index_arg(d, len + 1, "index")).transpose()?; + let max = whole(super::MAX_ARTBOARDS).and_then(|m| usize::try_from(m).ok()).unwrap_or(0); + if len >= max { + return Err(HostError::Range(format!("a document has at most {max} artboards"))); + } + let id = super::atomically(h, |h| { + on_doc(h, doc.uid, true, |h| { + let (_, made) = command_value(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; + let index = result_id(&made, "index") + .and_then(|i| usize::try_from(i).ok()) + .ok_or_else(|| HostError::Error("the artboard was not made".into()))?; + if let Some(to) = to + && to != index + { + command(h, "artboard.reorder", &json!({"index": index, "to": to}))?; + } + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) + }) + })?; + Ok(board_ref(h, doc.uid, id)) +} + +/// `artboards.add(artboardRect)`: a new artboard, last in the list. +fn boards_add(h: &Host, a: &[Data]) -> Answer { + add_board(h, a, None) +} + +/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. → nothing. +fn boards_insert(h: &Host, a: &[Data]) -> Answer { + if matches!(arg(a, 2), Data::Undefined) { + return Err(HostError::Type("insert needs an index".into())); + } + add_board(h, a, Some(arg(a, 2)))?; + Ok(Data::Undefined) +} + +fn boards_remove(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + let len = with_doc(h, doc, |_, st| st.doc.artboards.len()); + let i = board_index_arg(arg(a, 1), len, "index")?; + on_doc(h, doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + Ok(Data::Undefined) +} + +fn boards_active(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| active_artboard(st)) as u64))) +} + +/// `setActiveArtboardIndex(index)`: the artboard becomes the view's active one. Nothing in the +/// document changes, and no command runs. The artboard is kept by its id even when it is already +/// active only as the fallback (no artboard chosen yet), so an artboard inserted before it later +/// in the run moves it to the next index instead of taking its place. +fn boards_set_active(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + let (len, now) = with_doc(h, doc, |_, st| (st.doc.artboards.len(), active_artboard(st))); + let i = board_index_arg(arg(a, 1), len, "index")?; + { + let mut s = h.session.borrow_mut(); + let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id); + } + { + let mut chosen = h.dom.chosen_artboards.borrow_mut(); + let reverts = reverts_of(h, doc.uid); + if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) { + *generation = reverts; + } else { + chosen.push((doc.uid, reverts)); + } + } + // A document made during the run has no index from the start of the run, so the first choice + // records one; an artboard inserted before it later still puts it in the report. + if !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid) { + let mut made = h.dom.boards_chosen_in_new.borrow_mut(); + if !made.iter().any(|(uid, _)| *uid == doc.uid) { + made.push((doc.uid, i)); + } + } + if i != now { + let mut moved = h.dom.active_artboards.borrow_mut(); + if !moved.contains(&doc.uid) { + moved.push(doc.uid); + } + } + Ok(Data::Undefined) +} + +/// The documents whose active artboard the run changed, as `script.run`'s report gives them: +/// `[{document, artboard}]`, each an index, with the active artboard each document has at the end +/// of the run, or `None` when there are none. They are the documents in `moved`, then those whose +/// active artboard's index differs from the one in `start` (an artboard added, inserted, removed or +/// reordered before it). +pub(crate) fn active_artboards(moved: &[u64], start: &[(u64, usize)], docs: &[DocState]) -> Option { + let mut uids = moved.to_vec(); + for (uid, at) in start { + let shifted = docs.iter().find(|d| d.uid == *uid).is_some_and(|st| active_artboard(st) != *at); + if shifted && !uids.contains(uid) { + uids.push(*uid); + } + } + let list: Vec = uids + .iter() + .filter_map(|uid| { + let document = docs.iter().position(|d| d.uid == *uid)?; + Some(json!({"document": document, "artboard": active_artboard(&docs[document])})) + }) + .collect(); + (!list.is_empty()).then_some(Value::Array(list)) +} + +/// The classes of layers, art collections and artboards. +pub(super) fn classes(l: &Link) -> Vec { + let class = super::class; + let mut layer = named(vec![ + ("typename", get(l, layer_typename), typed("string")), + ("name", property(l, layer_name, layer_set_name), typed("string")), + ("visible", property(l, layer_visible, layer_set_visible), typed("boolean")), + ("locked", property(l, layer_locked, layer_set_locked), typed("boolean")), + ("printable", property(l, layer_printable, layer_set_printable), typed("boolean")), + ("preview", property(l, layer_preview, layer_set_preview), typed("boolean")), + ("dimPlacedImages", property(l, layer_dim, layer_set_dim), typed("boolean")), + ("opacity", property(l, layer_opacity, layer_set_opacity), typed("number")), + ("color", property(l, layer_color, layer_set_color), typed("RGBColor")), + ("parent", get(l, layer_parent), typed("*")), + ("layers", get(l, layers_of), listed("Layers")), + ("pageItems", get(l, held_page_items), listed("PageItems")), + ("groupItems", get(l, held_groups), listed("GroupItems")), + ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("textFrames", get(l, held_text), listed("TextFrames")), + ("zOrderPosition", get(l, layer_z_position), typed("number")), + ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected), typed("boolean")), + ("isIsolated", get(l, layer_is_isolated), typed("boolean")), + ("move", method(l, layer_move), returns("Layer", &[("relativeObject", "*"), ("insertionLocation", "ElementPlacement")])), + ("remove", method(l, layer_remove), returns("undefined", &[])), + ("zOrder", method(l, layer_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])), + ("toString", method(l, layer_to_string), returns("string", &[])), + ]); + layer.extend( + ["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)), + ); + vec![ + class("Layer", None, layer, None), + class( + "Layers", + None, + named(vec![ + ("typename", get(l, layers_typename), typed("string")), + ("length", get(l, layers_length), typed("number")), + ("parent", get(l, layers_parent), typed("*")), + ("index", method(l, layers_index), returns("Layer", &[("itemKey", "*")])), + ("getByName", method(l, layers_by_name), returns("Layer", &[("name", "string")])), + ("add", method(l, layers_add), returns("Layer", &[])), + ("removeAll", method(l, layers_remove_all), returns("undefined", &[])), + ("toString", method(l, layers_to_string), returns("string", &[])), + ]), + Some(super::function(l, layers_at)), + ), + class( + "GroupItems", + None, + { + let mut m = named(vec![ + ("typename", get(l, groups_typename), typed("string")), + ("length", get(l, groups_length), typed("number")), + ("parent", get(l, groups_parent), typed("*")), + ("index", method(l, groups_index), returns("GroupItem", &[("itemKey", "*")])), + ("getByName", method(l, groups_by_name), returns("GroupItem", &[("name", "string")])), + ("add", method(l, groups_add), returns("GroupItem", &[])), + ("removeAll", method(l, groups_remove_all), returns("undefined", &[])), + ("toString", method(l, groups_to_string), returns("string", &[])), + ]); + m.push(later(l, "GroupItems", "createFromFile")); + m + }, + Some(super::function(l, groups_at)), + ), + class( + "CompoundPathItems", + None, + named(vec![ + ("typename", get(l, compounds_typename), typed("string")), + ("length", get(l, compounds_length), typed("number")), + ("parent", get(l, compounds_parent), typed("*")), + ("index", method(l, compounds_index), returns("CompoundPathItem", &[("itemKey", "*")])), + ("getByName", method(l, compounds_by_name), returns("CompoundPathItem", &[("name", "string")])), + ("add", method(l, compounds_add), returns("CompoundPathItem", &[])), + ("removeAll", method(l, compounds_remove_all), returns("undefined", &[])), + ("toString", method(l, compounds_to_string), returns("string", &[])), + ]), + Some(super::function(l, compounds_at)), + ), + class( + "Artboard", + None, + named(vec![ + ("typename", get(l, board_typename), typed("string")), + ("artboardRect", property(l, board_rect, board_set_rect), typed("Array")), + ("name", property(l, board_name, board_set_name), typed("string")), + ("parent", get(l, board_parent), typed("Document")), + ("rulerOrigin", property(l, board_ruler_origin, board_set_ruler_origin), typed("Array")), + ("rulerPAR", property(l, board_par, board_set_par), typed("number")), + ("showCenter", property(l, board_center, board_set_center), typed("boolean")), + ("showCrossHairs", property(l, board_cross_hairs, board_set_cross_hairs), typed("boolean")), + ("showSafeAreas", property(l, board_safe_areas, board_set_safe_areas), typed("boolean")), + ("remove", method(l, board_remove), returns("undefined", &[])), + ("toString", method(l, board_to_string), returns("string", &[])), + ]), + None, + ), + class( + "Artboards", + None, + named(vec![ + ("typename", get(l, boards_typename), typed("string")), + ("length", get(l, boards_length), typed("number")), + ("parent", get(l, boards_parent), typed("Document")), + ("index", method(l, boards_index), returns("Artboard", &[("itemKey", "*")])), + ("getByName", method(l, boards_by_name), returns("Artboard", &[("name", "string")])), + ("add", method(l, boards_add), returns("Artboard", &[("artboardRect", "Array")])), + ("insert", method(l, boards_insert), returns("undefined", &[("artboardRect", "Array"), ("index", "number")])), + ("remove", method(l, boards_remove), returns("undefined", &[("index", "number")])), + ("getActiveArtboardIndex", method(l, boards_active), returns("number", &[])), + ("setActiveArtboardIndex", method(l, boards_set_active), returns("undefined", &[("index", "number")])), + ("toString", method(l, boards_to_string), returns("string", &[])), + ]), + Some(super::function(l, boards_at)), + ), + ] +} diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs new file mode 100644 index 0000000000..4de0a9efe4 --- /dev/null +++ b/crates/engine/src/script/dom/matrix.rs @@ -0,0 +1,586 @@ +//! The matrix functions of `app`, as the help pages +//! and +//! describe them. A matrix is a plain +//! record with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and +//! `mValueTY`; a record passed in needs only those six, and each record a function gives also has +//! the `typename` `"Matrix"`. Each function other than `isEqualMatrix` and `isSingularMatrix` gives +//! a new record, those two give a boolean, and none changes the records passed to it. +//! +//! The record maps a point `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix +//! does (ISO 32000-1, 8.3.4), in script coordinates with Y up. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `concatenateMatrix(m, n)` gives the matrix that applies `m` and then `n`; the other +//! `concatenate…` functions apply `m` and then the rotation, scale or translation they make. +//! - Left-out arguments are 0 for a translation and an angle, and 100 for a horizontal scale; a +//! left-out vertical scale is the horizontal one. +//! - Angles are degrees, positive counterclockwise, and quarter turns are exact. +//! - A matrix whose determinant is 0 is singular, and `invertMatrix` of one throws. +//! - `isEqualMatrix` compares the six values exactly. +//! - An argument that is not a finite number, or a matrix with a value that is not one, throws a +//! `TypeError`; a result with a value too large for a number throws a `RangeError`. + +use vectorcraft_js::{Data, HostError, MemberInfo}; + +use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text}; + +/// A matrix's six values: `[a, b, c, d, tx, ty]`. +pub(super) type Matrix = [f64; 6]; + +const KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"]; + +const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + +/// The matrix functions of `Application`. +pub(super) fn app_members(link: &Link) -> Vec { + let l = link; + named(vec![ + ("getIdentityMatrix", method(l, identity), returns("Matrix", &[])), + ("getTranslationMatrix", method(l, translation), returns("Matrix", &[("deltaX", "number"), ("deltaY", "number")])), + ("getScaleMatrix", method(l, scale), returns("Matrix", &[("scaleX", "number"), ("scaleY", "number")])), + ("getRotationMatrix", method(l, rotation), returns("Matrix", &[("angle", "number")])), + ("concatenateMatrix", method(l, concatenate), returns("Matrix", &[("matrix", "Matrix"), ("secondMatrix", "Matrix")])), + ( + "concatenateTranslationMatrix", + method(l, concatenate_translation), + returns("Matrix", &[("matrix", "Matrix"), ("deltaX", "number"), ("deltaY", "number")]), + ), + ( + "concatenateScaleMatrix", + method(l, concatenate_scale), + returns("Matrix", &[("matrix", "Matrix"), ("scaleX", "number"), ("scaleY", "number")]), + ), + ("concatenateRotationMatrix", method(l, concatenate_rotation), returns("Matrix", &[("matrix", "Matrix"), ("angle", "number")])), + ("invertMatrix", method(l, invert), returns("Matrix", &[("matrix", "Matrix")])), + ("isEqualMatrix", method(l, is_equal), returns("boolean", &[("matrix", "Matrix"), ("secondMatrix", "Matrix")])), + ("isSingularMatrix", method(l, is_singular), returns("boolean", &[("matrix", "Matrix")])), + ]) + .into_iter() + .map(|(name, member, info)| (name, member, with_defaults(info))) + .collect() +} + +/// `info` with the defaults of its left-out number arguments, which `reflect` reports: 0 for a +/// translation and an angle, 100 for a horizontal scale. A left-out vertical scale is the +/// horizontal one, so it has no fixed default and its description says so. +fn with_defaults(mut info: MemberInfo) -> MemberInfo { + for a in &mut info.arguments { + match a.name.as_str() { + "deltaX" | "deltaY" | "angle" => a.default = Some(num(0.0)), + "scaleX" => a.default = Some(num(100.0)), + "scaleY" => a.description = Some("The vertical scale; when it is left out, the horizontal scale.".into()), + _ => {} + } + } + info +} + +/// The record for `m`, or a `RangeError` when a value is not finite. +fn record(m: Matrix) -> Answer { + if m.iter().any(|v| !v.is_finite()) { + return Err(HostError::Range("the matrix has a value too large for a number".into())); + } + let mut items: Vec<(String, Data)> = KEYS.iter().zip(m).map(|(k, v)| ((*k).to_string(), num(v))).collect(); + items.push(("typename".into(), text("Matrix"))); + Ok(Data::Object(items)) +} + +/// The matrix argument `d`. +pub(super) fn matrix(d: &Data, what: &str) -> std::result::Result { + let bad = || HostError::Type(format!("{what} must be a Matrix")); + let Data::Object(items) = d else { return Err(bad()) }; + let mut m = [0.0; 6]; + for (slot, k) in m.iter_mut().zip(KEYS) { + match items.iter().find(|(n, _)| n == k) { + Some((_, Data::Number(v))) if v.is_finite() => *slot = *v, + _ => return Err(bad()), + } + } + Ok(m) +} + +/// A number argument, `default` when it is left out. +fn number(d: &Data, what: &str, default: f64) -> std::result::Result { + match d { + Data::Undefined => Ok(default), + Data::Number(n) if n.is_finite() => Ok(*n), + _ => Err(HostError::Type(format!("{what} must be a finite number"))), + } +} + +/// The matrix that applies `m` and then `n`. Adding 0 turns -0 into 0. +fn then(m: Matrix, n: Matrix) -> Matrix { + let [a, b, c, d, e, f] = m; + let [a2, b2, c2, d2, e2, f2] = n; + [ + products_sum(a, a2, b, c2, 0.0) + 0.0, + products_sum(a, b2, b, d2, 0.0) + 0.0, + products_sum(c, a2, d, c2, 0.0) + 0.0, + products_sum(c, b2, d, d2, 0.0) + 0.0, + products_sum(e, a2, f, c2, e2) + 0.0, + products_sum(e, b2, f, d2, f2) + 0.0, + ] +} + +/// `x·y + z·w + t`. When at most one of the three terms is not 0 and it is finite, that term is the +/// sum, rounded once. When both products and their sum are exact numbers, adding `t` rounds once. +/// Otherwise the products are summed past the range of a number and rounded at +/// the end, so a finite value is not lost to a product too large or too small for a number, to a +/// sum that rounds twice, or to a rounding error that a later term cancels down to. +fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { + let (p, q) = (x * y, z * w); + let terms = [x != 0.0 && y != 0.0, z != 0.0 && w != 0.0, t != 0.0]; + let total = p + q + t; + if terms.iter().filter(|&&on| on).count() <= 1 && total.is_finite() { + return total; + } + // A product at or above 2^-969 that rounds drops a part a number can hold, so a zero + // remainder shows the product is exact. + let exact = |v: f64, a: f64, b: f64| a == 0.0 || b == 0.0 || (v.abs() >= f64::MIN_POSITIVE * 2f64.powi(53) && a.mul_add(b, -v) == 0.0); + let plain = p + q; + if total.is_finite() && exact(p, x, y) && exact(q, z, w) && plain - p == q && plain - q == p { + return total; + } + // Each product is split into its rounded value and the part that rounding drops, both exact. + // The five parts are added one at a time into a list of values that do not overlap, smallest + // first, whose sum is exact (Shewchuk's expansion). + let ([p, p_lost], [q, q_lost]) = (product(x, y), product(z, w)); + let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Parts::EMPTY, grow); + nearest(exact) +} + +/// `a·b` as its rounded value and the part that rounding drops, both exact. +fn product(a: f64, b: f64) -> [Wide; 2] { + let (a, b) = (Wide::of(a), Wide::of(b)); + let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e)); + [Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)] +} + +/// Values that do not overlap, smallest first, held without allocating. Each value added keeps at +/// most one more, so the five parts of a sum, the two of a comparison and the sixteen of an +/// inverse's rounding test fit. +#[derive(Clone, Copy)] +struct Parts { + v: [Wide; 16], + n: usize, +} + +impl Parts { + const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 16], n: 0 }; + + fn as_slice(&self) -> &[Wide] { + &self.v[..self.n] + } +} + +/// `sums` with `part` added: values that do not overlap, smallest first, whose sum is exactly the +/// sum of `sums` and `part`. The last value is the largest and has the sign of the sum. +fn grow(sums: Parts, part: Wide) -> Parts { + let mut carry = part; + let mut kept = Parts::EMPTY; + let mut keep = |w: Wide| { + if w.m != 0.0 && kept.n < kept.v.len() { + kept.v[kept.n] = w; + kept.n += 1; + } + }; + for &h in sums.as_slice() { + let (sum, rest) = carry.two_sum(h); + keep(rest); + carry = sum; + } + keep(carry); + kept +} + +/// The sign of the exact sum of `sums`, `0.0 - v` and `offset`: 1, -1 or 0. +fn sign_past(sums: Parts, v: f64, offset: Wide) -> i32 { + let rest = [Wide::of(0.0 - v), offset].into_iter().fold(sums, grow); + match rest.as_slice().last() { + Some(w) if w.m > 0.0 => 1, + Some(w) if w.m < 0.0 => -1, + _ => 0, + } +} + +/// The number nearest the exact sum of `sums`, ties to the even one, and infinite when the sum +/// rounds to 2^1024 or past it. The sum of the values from the smallest up comes within a step of +/// it; the halfway points to the neighbors of that number are then compared with the exact sum, so +/// the result is rounded once. +fn nearest(sums: Parts) -> f64 { + let even = |v: f64| v.to_bits() & 1 == 0; + let mut v = sums.as_slice().iter().fold(Wide::of(0.0), |total, &h| total.two_sum(h).0).value().clamp(f64::MIN, f64::MAX); + for _ in 0..4 { + // Half the step to the next number up, and to the next number down. Past the largest + // number the step is to 2^1024, which is 2^971 away. + let up = if v == f64::MAX { f64::INFINITY } else { v.next_up() }; + let down = if v == f64::MIN { f64::NEG_INFINITY } else { v.next_down() }; + let half_up = if up.is_finite() { Wide::new(up - v, -1) } else { Wide::new(1.0, 970) }; + let half_down = if down.is_finite() { Wide::new(v - down, -1) } else { Wide::new(1.0, 970) }; + match sign_past(sums, v, Wide { m: 0.0 - half_up.m, e: half_up.e }) { + 1 => { + v = up; + if !v.is_finite() { + return v; + } + continue; + } + 0 => return if even(v) { v } else { up }, + _ => {} + } + match sign_past(sums, v, half_down) { + -1 => { + v = down; + if !v.is_finite() { + return v; + } + } + 0 => return if even(v) { v } else { down }, + _ => return v, + } + } + v +} + +pub(super) fn translate(dx: f64, dy: f64) -> Matrix { + [1.0, 0.0, 0.0, 1.0, dx, dy] +} + +/// A scale by `sx` and `sy` percent. +pub(super) fn scaled(sx: f64, sy: f64) -> Matrix { + [sx / 100.0, 0.0, 0.0, sy / 100.0, 0.0, 0.0] +} + +/// A turn of `degrees` counterclockwise, exact at quarter turns. The remainder keeps the sign of +/// `degrees` and is exact, so an angle next to a quarter turn is not rounded onto it. +pub(super) fn rotate(degrees: f64) -> Matrix { + let turn = degrees % 360.0; + let (sin, cos) = match turn { + 0.0 => (0.0, 1.0), + 90.0 | -270.0 => (1.0, 0.0), + 180.0 | -180.0 => (0.0, -1.0), + 270.0 | -90.0 => (-1.0, 0.0), + _ => turn.to_radians().sin_cos(), + }; + // `0.0 - sin` rather than `-sin`, so a turn of 0 gives 0 and not -0. + [cos, sin, 0.0 - sin, cos, 0.0, 0.0] +} + +fn translation_of(a: &[Data], at: usize) -> std::result::Result { + Ok(translate(number(arg(a, at), "deltaX", 0.0)?, number(arg(a, at + 1), "deltaY", 0.0)?)) +} + +fn scale_of(a: &[Data], at: usize) -> std::result::Result { + let sx = number(arg(a, at), "scaleX", 100.0)?; + Ok(scaled(sx, number(arg(a, at + 1), "scaleY", sx)?)) +} + +fn rotation_of(a: &[Data], at: usize) -> std::result::Result { + Ok(rotate(number(arg(a, at), "angle", 0.0)?)) +} + +fn identity(_: &Host, _: &[Data]) -> Answer { + record(IDENTITY) +} + +fn translation(_: &Host, a: &[Data]) -> Answer { + record(translation_of(a, 1)?) +} + +fn scale(_: &Host, a: &[Data]) -> Answer { + record(scale_of(a, 1)?) +} + +fn rotation(_: &Host, a: &[Data]) -> Answer { + record(rotation_of(a, 1)?) +} + +fn concatenate(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, matrix(arg(a, 2), "secondMatrix")?)) +} + +fn concatenate_translation(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, translation_of(a, 2)?)) +} + +fn concatenate_scale(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, scale_of(a, 2)?)) +} + +fn concatenate_rotation(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, rotation_of(a, 2)?)) +} + +/// A number as `m · 2^e` with `m` 0 or in `[0.5, 1)`, so products and quotients of such numbers +/// keep their value however far they go past the range of an `f64`. +#[derive(Clone, Copy)] +struct Wide { + m: f64, + e: i32, +} + +/// `2^e`, for `e` from -1022 to 1023. +fn pow2(e: i32) -> f64 { + f64::from_bits(u64::from((e + 1023).clamp(1, 2046).unsigned_abs()) << 52) +} + +impl Wide { + /// `x`, a finite number. + fn of(x: f64) -> Self { + if x == 0.0 { + return Self { m: 0.0, e: 0 }; + } + if x.abs() < f64::MIN_POSITIVE { + let w = Self::of(x * pow2(54)); + return Self { m: w.m, e: w.e - 54 }; + } + let bits = x.to_bits(); + let e = i32::try_from((bits >> 52) & 0x7ff).unwrap_or(0) - 1022; + Self { m: f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), e } + } + + /// `m · 2^e`, with `m` any finite number. + fn new(m: f64, e: i32) -> Self { + let w = Self::of(m); + Self { m: w.m, e: w.e.saturating_add(e) } + } + + fn div(self, o: Self) -> Self { + Self::new(self.m / o.m, self.e.saturating_sub(o.e)) + } + + /// The sum and the part of it that rounding drops, so that `self + o` is exactly their sum. A + /// number more than 2^110 times smaller than the other is returned whole as the dropped part. + fn two_sum(self, o: Self) -> (Self, Self) { + let (big, small) = if self.m == 0.0 || (o.m != 0.0 && o.e > self.e) { (o, self) } else { (self, o) }; + let gap = small.e.saturating_sub(big.e); + if small.m == 0.0 || gap < -110 { + return (big, small); + } + // Knuth's two-sum: `small` scaled to `big`'s power of 2 is exact, and so is the error. + let s = small.m * pow2(gap); + let sum = big.m + s; + let back = sum - big.m; + let rest = (big.m - (sum - back)) + (s - back); + (Self::new(sum, big.e), Self::new(rest, big.e)) + } + + /// The nearest `f64`: infinite past its range, and 0 or a subnormal number below it. + fn value(self) -> f64 { + let (mut m, mut e) = (self.m, self.e); + while e > 1000 && m.is_finite() { + m *= pow2(1000); + e -= 1000; + } + while e < -1000 && m != 0.0 { + m *= pow2(-1000); + e += 1000; + } + m * pow2(e) + } +} + +/// `a·d − b·c` with no product passing the range of a number; its `m` is 0 only when the two +/// products are equal. The products are taken whole with fused multiply-adds (Kahan's method), so +/// a difference that is small next to them keeps its value. +fn products_difference(a: f64, d: f64, b: f64, c: f64) -> Wide { + let [a, b, c, d] = [a, b, c, d].map(Wide::of); + let (ad, bc) = (a.e.saturating_add(d.e), b.e.saturating_add(c.e)); + if b.m == 0.0 || c.m == 0.0 { + return Wide::new(a.m * d.m, ad); + } + if a.m == 0.0 || d.m == 0.0 { + return Wide::new(0.0 - b.m * c.m, bc); + } + // `a·d` and `b·c` both lie in [0.25, 1) times a power of 2; one more than 2^120 times the other + // decides the sign and size alone. + let gap = bc.saturating_sub(ad); + if gap < -120 { + return Wide::new(a.m * d.m, ad); + } + if gap > 120 { + return Wide::new(0.0 - b.m * c.m, bc); + } + let b = b.m * pow2(gap); + let w = b * c.m; + let err = (0.0 - b).mul_add(c.m, w); + Wide::new(a.m.mul_add(d.m, 0.0 - w) + err, ad) +} + +/// The determinant of `m`'s linear part. +fn determinant(m: Matrix) -> Wide { + products_difference(m[0], m[3], m[1], m[2]) +} + +/// The square root of the size of `m`'s determinant: the factor by which `m` scales lengths on +/// average. It is infinite only when that factor is too large for a number. +pub(super) fn area_scale(m: Matrix) -> f64 { + let d = determinant(m); + let (mut v, mut e) = (d.m.abs(), d.e); + if e % 2 != 0 { + v *= 2.0; + e -= 1; + } + Wide::new(v.sqrt(), e / 2).value() +} + +pub(super) fn singular(m: Matrix) -> bool { + determinant(m).m == 0.0 +} + +fn invert(_: &Host, a: &[Data]) -> Answer { + let m = matrix(arg(a, 1), "matrix")?; + let det = determinant(m); + if det.m == 0.0 { + return Err(HostError::Error("the matrix is singular and cannot be inverted".into())); + } + let [a, b, c, d, e, f] = m; + // Each value is divided by the determinant before it is brought back into the range of a + // number, and the translations are taken whole, so a finite inverse is not lost to an + // intermediate value. Adding 0 turns -0 into 0. + let exact_det = || difference_parts(a, d, b, c); + let zero = Wide::of(0.0); + let plain = |v: f64| quotient(Wide::of(v), || [Wide::of(v), zero, zero, zero], det, exact_det); + record([ + plain(d), + plain(0.0 - b), + plain(0.0 - c), + plain(a), + quotient(products_difference(c, f, d, e), || difference_parts(c, f, d, e), det, exact_det), + quotient(products_difference(b, e, a, f), || difference_parts(b, e, a, f), det, exact_det), + ]) +} + +/// `a·d − b·c` as four exact parts. +fn difference_parts(a: f64, d: f64, b: f64, c: f64) -> [Wide; 4] { + let neg = |w: Wide| Wide { m: 0.0 - w.m, e: w.e }; + let ([p, p_lost], [q, q_lost]) = (product(a, d), product(b, c)); + [p, p_lost, neg(q), neg(q_lost)] +} + +/// The quotient of `num` by `det`, from their rounded values `num` and `det` and their exact parts. +/// The result is the rounded quotient, which is within a few steps of the exact one, except where +/// that would decide overflow wrongly. When the rounded quotient overflows or lies within eight +/// steps of the largest number, the exact quotient is compared with 2^1024 − 2^970, the halfway +/// point between the largest number and 2^1024: at it or past it the result is infinite. Below it +/// a finite rounded quotient is kept, and an infinite one is replaced by the number the exact +/// quotient rounds to, found from the halfway points 2^1024 − j·2^970 (odd `j`) below, ties to the +/// even one. When the rounded quotient is below 2^-1023, where every number is a multiple of the +/// smallest number, the result is the multiple whose halfway points to its neighbors hold the exact +/// quotient, ties to the even one, so a quotient just past half the smallest number is not rounded +/// to 0. The exact parts are worked out only then. Adding 0 turns -0 into 0. +fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: impl Fn() -> [Wide; 4]) -> f64 { + if num.m == 0.0 { + return 0.0; + } + let v = num.div(det).value() + 0.0; + // 2^1024 − 9·2^971, eight steps below the largest number. + let near_top = f64::MAX - 8.0 * pow2(971); + let tiny = f64::MIN_POSITIVE / 2.0; + if v.is_finite() && v.abs() < near_top && v.abs() >= tiny { + return v; + } + let (exact_num, exact_det) = (exact_num(), exact_det()); + let sign = |parts: &[Wide]| match parts.iter().copied().fold(Parts::EMPTY, grow).as_slice().last() { + Some(w) if w.m < 0.0 => -1.0, + _ => 1.0, + }; + let (sn, sd) = (sign(&exact_num), sign(&exact_det)); + if v.abs() < tiny { + return small_quotient(v, &exact_num, &exact_det, sn, sd); + } + // The sign of |num| − (2^1024 − j·2^970)·|det|. Scaling by a power of 2 is exact, and each + // `j·m` is split into its rounded value and the part that rounding drops. + let past = |j: f64| { + let scaled = |w: Wide, s: f64, e: i32| Wide { m: w.m * s, e: w.e.saturating_add(e) }; + let times_j = |w: Wide| { + let hi = j * w.m * sd; + let lo = (j * sd).mul_add(w.m, 0.0 - hi); + [Wide::new(hi, w.e.saturating_add(970)), Wide::new(lo, w.e.saturating_add(970))] + }; + let sum = exact_num + .iter() + .map(|&w| scaled(w, sn, 0)) + .chain(exact_det.iter().map(|&w| scaled(w, 0.0 - sd, 1024))) + .chain(exact_det.iter().flat_map(|&w| times_j(w))) + .fold(Parts::EMPTY, grow); + match sum.as_slice().last() { + Some(w) if w.m > 0.0 => 1, + Some(w) if w.m < 0.0 => -1, + _ => 0, + } + }; + if past(1.0) >= 0 { + return f64::INFINITY; + } + if v.is_finite() { + return v; + } + let even = |x: f64| x.to_bits() & 1 == 0; + let mut top = f64::MAX; + for k in 1..16u8 { + let below = top.next_down(); + match past(f64::from(2 * k + 1)) { + 1 => return top * sn * sd, + 0 => return if even(top) { top } else { below } * sn * sd, + _ => top = below, + } + } + top * sn * sd +} + +/// The exact quotient of `exact_num` by `exact_det`, whose signs are `sn` and `sd`, rounded to a +/// multiple of the smallest number, ties to the even multiple, starting from the rounded quotient +/// `v`, which is below 2^-1023 and within a few steps of it. +fn small_quotient(v: f64, exact_num: &[Wide; 4], exact_det: &[Wide; 4], sn: f64, sd: f64) -> f64 { + let step = f64::from_bits(1); + // The sign of |num| − j·2^-1075·|det|, with each `j·m` split into its rounded value and the + // part that rounding drops. `j` is odd and below 2^53, so it is exact. + let past = |j: f64| { + let times_j = |w: Wide| { + let hi = j * w.m * sd; + let lo = (j * sd).mul_add(w.m, 0.0 - hi); + [Wide::new(0.0 - hi, w.e.saturating_sub(1075)), Wide::new(0.0 - lo, w.e.saturating_sub(1075))] + }; + let sum = exact_num.iter().map(|&w| Wide { m: w.m * sn, e: w.e }).chain(exact_det.iter().flat_map(|&w| times_j(w))).fold(Parts::EMPTY, grow); + match sum.as_slice().last() { + Some(w) if w.m > 0.0 => 1, + Some(w) if w.m < 0.0 => -1, + _ => 0, + } + }; + // `k` steps; dividing by the smallest number is exact. + let mut k = v.abs() / step; + let even = |k: f64| k % 2.0 == 0.0; + for _ in 0..8 { + match past(2.0 * k + 1.0) { + 1 => k += 1.0, + 0 => { + k = if even(k) { k } else { k + 1.0 }; + break; + } + _ => { + if k == 0.0 { + break; + } + match past(2.0 * k - 1.0) { + -1 => k -= 1.0, + 0 => { + k = if even(k) { k } else { k - 1.0 }; + break; + } + _ => break, + } + } + } + } + k * step * sn * sd + 0.0 +} + +fn is_equal(_: &Host, a: &[Data]) -> Answer { + Ok(Data::Bool(matrix(arg(a, 1), "matrix")? == matrix(arg(a, 2), "secondMatrix")?)) +} + +fn is_singular(_: &Host, a: &[Data]) -> Answer { + Ok(Data::Bool(singular(matrix(arg(a, 1), "matrix")?))) +} diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 03ec3812a6..392e8c7700 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -17,7 +17,8 @@ //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing //! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked -//! artboard. +//! artboard. A point assigned whose x or y is more than `MAX_COORD` from the origin throws a +//! range error when it is assigned. //! - A path in a compound path or compound shape reads that owner's paint, which the paint //! commands change in its place, and a gradient that `filled = true` gives it is placed on that //! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and @@ -52,9 +53,7 @@ //! throws an error that says it is not available yet on a path inside a compound path, throws //! `Cannot edit` on a path that cannot be edited or selected, and throws an error while guides //! are locked; assigning the value the path has runs no command. -//! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and -//! `changeStrokePattern` given as different values throw an error; gradients move with the art, -//! so `changeFillGradients` false throws an error that says it is not available yet. +//! - The transforms are `PageItem`'s, with their rules in [`super::transform`]. use std::rc::Rc; use std::sync::Arc; @@ -69,9 +68,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, command_value, coordinate, doc_of, - edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, - on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, + Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, + edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, point, + point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -108,16 +107,27 @@ fn cannot_edit(id: NodeId) -> HostError { HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0)) } -/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or -/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one. -fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> { +/// The `Cannot edit` error for the path `id` of `st` when it, or a layer or group it is in, is +/// hidden or locked, or it is on a locked artboard. +fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option { if !editable(&st.doc, id) { - return Err(cannot_edit(id)); + Some(cannot_edit(id)) + } else if super::on_locked_artboard(h, st, id) { + Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))) + } else if h.session.borrow().menu.guides_locked && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })) { + Some(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0))) + } else { + None } - if super::on_locked_artboard(h, st, id) { - return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))); +} + +/// `p`, a point the script assigned, whose x and y must each be within [`crate::MAX_COORD`] of the origin. +fn in_canvas(p: Point, what: &str) -> std::result::Result { + if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD { + Ok(p) + } else { + Err(HostError::Range(format!("{what} is outside the canvas"))) } - Ok(()) } /// The path `d` names, which must still be in its document. @@ -131,9 +141,12 @@ fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result std::result::Result { +/// The path of the run `run`, document `uid`, id parts `high` and `low` and revert count `reverts`, as a handle gives them. +fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64, reverts: f64) -> std::result::Result { let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if with_doc(h, doc, |_, st| Some(st.reverts) != whole(reverts)) { + return Err(HostError::Error(STALE_ITEM.into())); + } let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; path_of(h, &path_ref(h, Item { doc, id })) } @@ -149,12 +162,10 @@ fn read_path(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::d }) } +/// A `PathItem` handle for `item`, in the form `item_of` reads (with the document's revert count). fn path_ref(h: &super::Host, item: Item) -> Data { - let s = h.session.borrow(); - match s.documents().iter().find(|d| d.uid == item.doc.uid) { - Some(st) => host_ref("PathItem", &super::node_handle(h, st, item.id)), - None => Data::Null, - } + let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)); + host_ref("PathItem", &handle) } /// The index of the first point of each subpath of `subs`, followed by the number of points. @@ -219,6 +230,8 @@ fn points_of(h: &super::Host, item: Item) -> std::result::Result Option<(usize, usize)> { for (s, sp) in subs.iter().enumerate() { + #[cfg(test)] + tests::LOCATE_STEPS.with(|steps| steps.set(steps.get() + 1)); if i < sp.anchors.len() { return Some((s, i)); } @@ -248,8 +261,9 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with /// the path's other point changes until [`flush`] writes them. The first change of a path writes /// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or -/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path that is aligned to the pixel grid, or is in an object -/// that is, is written at once, so that its points read as the grid snaps them. +/// locked or is on a locked artboard ([`protected`]), unless it changes nothing. A path +/// that is aligned to the pixel grid, or is in an object that is, is written at once, so that its +/// points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { forget_waiting_starts(h); if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() @@ -263,10 +277,13 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) let (same, refused, aligned) = read_path(h, item, |st, _, pd| { let d = &st.doc; let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); - (pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned) + let same = pd.subpaths == subs; + (same, if same { None } else { protected(h, st, item.id) }, aligned) })?; if !same { - refused?; + if let Some(e) = refused { + return Err(e); + } *h.dom.pending.borrow_mut() = Some((item, subs)); if aligned { flush(h)?; @@ -324,12 +341,50 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { } let subpaths: Vec = subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); - // Changes made before this one are looked at in full first. - see_all_points(h); - let kept = h.dom.one_path.replace(Some(item)); - let r = edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths})); - h.dom.one_path.set(kept); - r?; + super::atomically(h, |h| { + // The anchors and segments the new points no longer have leave the selection before the + // points are written. The undo step of the edit keeps the selection from before that, so + // undoing it selects them again. + let mut kept = None; + if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { + kept = Some(st.selection.clone()); + let selection = &mut st.selection; + if let Some(anchors) = selection.anchors.get_mut(&item.id) { + anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len())); + } + if let Some(segments) = selection.segments.get_mut(&item.id) { + segments.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.segment_count())); + if segments.is_empty() { + selection.segments.remove(&item.id); + } + } + if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) { + selection.key_anchor = None; + } + if (selection.contains(item.id) || selection.anchors.contains_key(&item.id) || selection.segments.contains_key(&item.id)) + && (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || subs.iter().all(|sp| sp.anchors.is_empty())) + { + selection.remove(item.id); + } + if kept.as_ref().is_some_and(|before| *before == st.selection) { + kept = None; + } + } + // The document as the edit's step keeps it, read after the switch to it, which can measure + // its type again. + let doc = super::edit_item_with(h, item, |h| { + let doc = h.session.borrow().active().map(|st| st.doc.clone()); + super::command(h, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; + Ok(doc) + })?; + if let Some((doc, selection)) = doc.zip(kept) + && let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) + && let Some(step) = st.history.undo.last_mut().filter(|step| Arc::ptr_eq(&step.doc, &doc)) + { + step.selection = Arc::new(selection); + } + Ok(()) + })?; Ok(()) } @@ -339,26 +394,36 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n) } -/// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active -/// layer, then puts the drawing mode back. -fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { - let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); - let r = f(); - h.session.borrow_mut().draw_mode = kept; - r +/// Runs a path creation command with its layer placement recorded. +fn drawing_normally(h: &super::Host, parent: Option, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> { + let mut params = params.clone(); + params["onLayer"] = json!(parent.map(|p| p.0)); + super::command_value(h, id, ¶ms) } /// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which -/// must be one the user could edit ([`refuse_path_edit`]). +/// must be one the user could edit ([`protected`]). /// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the /// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put /// back afterwards, so the edit changes only the path. fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result { - with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?; + if let Some(e) = with_doc(h, item.doc, |_, st| protected(h, st, item.id)) { + return Err(e); + } if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + o.insert("objectOnly".into(), json!(true)); + } } - keeping_paint(h, || edit_item(h, item, id, ¶ms)) + let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; + let count = if id == "object.setOverprint" { "changed" } else { "objects" }; + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint") + && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0))) + { + return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0))); + } + Ok(result) } /// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color @@ -396,65 +461,190 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { } fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { + if super::layers::is_scoped(a, "PathItems") { + return Err(HostError::Error("creating paths in a compound path is not available yet; move a path into it".into())); + } doc_of(h, arg(a, 0), "PathItems") } /// `typename` of the paths of a document that is still open. fn items_typename(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_typename(h, a); + } items_doc(h, a)?; Ok(Data::String("PathItems".into())) } fn items_length(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_length(h, a); + } let doc = items_doc(h, a)?; Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_parent(h, a); + } let doc = items_doc(h, a)?; Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) } +/// `pathItems[i]`, and `pathItems["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 path has it. fn items_at(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_at(h, a); + } let doc = items_doc(h, a)?; - 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) }; + match arg(a, 1) { + Data::String(_) => match items_by_name(h, a) { + Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined), + r => r, + }, + Data::Number(n) => match super::position(*n) { + Some(i) => 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), + } +} + +/// The path at position `i` of `pathItems`, or `undefined` past the end. +fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer { with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_by_name(h, a); + } 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 path of `pathItems` named `name`, or `Not found`. +fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer { with_doc(h, doc, |_, st| { let ids = path_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| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) } fn items_index(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_index(h, a); + } 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 whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, i)).transpose()? { + Some(Data::Undefined) | None => Err(HostError::Error(NOT_FOUND.into())), + Some(d) => Ok(d), + } + } _ => Err(HostError::Type("give a name or an index".into())), } } /// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before -/// anything is deleted, as `PageItems.removeAll()` does. +/// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or +/// layer that keeps other objects, or a compound path or group that clips one and would be left +/// with no visible path or visible type that lays out glyphs to clip by. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_remove_all(h, a); + } let doc = items_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| { let ids = path_items(h, st)?; - let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - let locks = st.doc.locked_artboards(); + let d = &st.doc; + if h.session.borrow().menu.guides_locked + && let Some(id) = ids.iter().find(|id| d.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }))) + { + return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0))); + } + let refused: Vec = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect(); + let locks = d.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused, on_locked)) + let mut next: Vec<_> = d.layers.iter().collect(); + let mut nodes = Vec::new(); + while let Some(n) = next.pop() { + nodes.push(n); + next.extend(n.children().into_iter().flatten()); + } + let mut going: std::collections::HashSet = ids.iter().copied().collect(); + let mut affected: std::collections::HashSet = ids.iter().copied().collect(); + for n in nodes.iter().rev() { + if n.children().into_iter().flatten().any(|k| affected.contains(&k.id)) { + affected.insert(n.id); + } + } + // Type is laid out only inside a mask that loses a path; no other outline decides a refusal. + let mut in_mask = std::collections::HashSet::new(); + for n in &nodes { + if n.clips() + && let Some(mask) = n.children().and_then(|k| k.first()) + && affected.contains(&mask.id) + { + let mut stack = vec![mask]; + while let Some(m) = stack.pop() { + if in_mask.insert(m.id) { + stack.extend(m.children().into_iter().flatten()); + } + } + } + } + let mut geometry = std::collections::HashSet::new(); + let mut masks = Vec::new(); + for n in nodes.into_iter().rev() { + let kids = n.children().map_or(&[][..], Vec::as_slice); + // Clear removes compound paths emptied of direct members, but keeps empty groups. + if matches!(n.kind, NodeKind::Compound { .. }) + && !kids.is_empty() + && kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id)) + { + going.insert(n.id); + } + // A clip outline takes in visible paths and the glyphs of visible type, as + // `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no + // outline. A list marker is a glyph too, so whitespace-only type is laid out as well. + let shape = n.visible + && match &n.kind { + NodeKind::Path { .. } => true, + NodeKind::Text(t) => { + in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty() + } + _ => false, + }; + // A clipping group's outline is its first member's alone. + let inner = + if n.clips() { kids.first().is_some_and(|k| geometry.contains(&k.id)) } else { kids.iter().any(|k| geometry.contains(&k.id)) }; + if n.visible && ((shape && !going.contains(&n.id)) || inner) { + geometry.insert(n.id); + } + if n.clips() + && let Some(mask) = kids.first() + && affected.contains(&mask.id) + && !geometry.contains(&mask.id) + && kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. })) + && masks.len() < 20 + { + masks.push(mask.id.0); + } + } + Ok::<_, HostError>((ids, refused, on_locked, masks)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -462,7 +652,13 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { } 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))); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } + if !masks.is_empty() { + let list = masks.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" + ))); } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; @@ -470,10 +666,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// The id in the result of a command that made an object, read from the command's own result so -/// that an id above 2^53 stays exact. -fn made_id(r: &Value) -> std::result::Result { - r["id"].as_u64().map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +/// The id in the JSON result of a command that made an object, read exactly, as the text creators +/// read it. +fn made_id(r: &(Data, Value)) -> std::result::Result { + r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } /// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, @@ -483,7 +679,8 @@ fn made_id(r: &Value) -> std::result::Result { fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = keeping_paint(h, || { on_doc(h, doc.uid, true, |h| { - let id = made_id(&drawing_normally(h, || command_value(h, id, params))?.1)?; + let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); + let id = made_id(&drawing_normally(h, parent, id, params)?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -648,9 +845,10 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?.1)?; + let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); + let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?; if unpainted { - command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]}))?; + command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?; } Ok(id) }) @@ -664,8 +862,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { fn path_points(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; - let [high, low] = id_parts(item.id); - Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low])) + let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)); + Ok(host_ref("PathPoints", &handle)) } fn path_closed(h: &super::Host, a: &[Data]) -> Answer { @@ -676,7 +874,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer { fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + edit_points(h, item, |subs| { + if subs.is_empty() && closed { + subs.push(SubPath::new(Vec::new(), closed)); + } else { + subs.iter_mut().for_each(|sp| sp.closed = closed); + } + })?; Ok(Data::Undefined) } @@ -754,7 +958,7 @@ fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer { if clipping { return Err(HostError::Error(format!("Cannot make PathItem {} a guide: it is a clipping path", item.id.0))); } - see_all_points(h); + see_all_points(h)?; let kept = h.dom.editing.replace(Some(item)); let r = on_doc(h, item.doc.uid, true, |h| { command(h, "select.set", &json!({"ids": [item.id.0]}))?; @@ -783,8 +987,8 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?; let c = h.dom.coords.get(); let anchors: Vec = - script.iter().map(|p| on_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; - let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; + script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; + let subs = if anchors.is_empty() && !closed { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; write_path(h, item, subs)?; cut_points(h, item); Ok(Data::Undefined) @@ -872,10 +1076,10 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul Ok(match linked { true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}), true => json!({"swatch": name}), - false => json!({"color": colors::param(color)}), + false => json!({"color": colors::param(color), "keepModel": true}), }) } - Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})), + Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color), "keepModel": true})), Paint::Gradient(g) => { let mut g = g.clone(); if g.geom.is_some() || g.freeform.is_some() { @@ -1111,139 +1315,59 @@ fn path_set_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer { set_overprint(h, a, false) } -// ---- PathItem transforms ---- +// ---- PathItem stroke weights for `resize` ---- -/// The member of `Transformation` that `d` names (left out: `CENTER`). -fn about_name(d: &Data) -> std::result::Result<&'static str, HostError> { - let name = match d { - Data::Undefined => "Transformation.CENTER", - Data::String(s) => s.as_str(), - _ => return Err(HostError::Type("give a Transformation value".into())), - }; - let members = ENUMS.iter().find(|(e, _)| *e == "Transformation").map_or(&[][..], |(_, m)| *m); - let member = name.strip_prefix("Transformation.").and_then(|m| members.iter().find(|x| **x == m)); - member.copied().ok_or_else(|| HostError::Type("give a Transformation value".into())) +/// The stroke weight `resize`'s `changeLineWidths` of `percent` gives the path `item`, or `None` +/// when the weight stays. A `custom` percent, one other than the resize's own scale, is at most +/// 100000. +pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, custom: bool) -> std::result::Result, HostError> { + if custom && !(0.0..=100_000.0).contains(&percent) { + return Err(HostError::Range("changeLineWidths must be from 0 to 100000 percent".into())); + } + let width = look(h, item)?.width; + let new_width = width * percent / 100.0; + if new_width > MAX_STROKE_WIDTH { + return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); + } + Ok(((new_width - width).abs() > 1e-9).then_some(new_width)) } -/// The point of the path's geometric bounds `r`, in document coordinates, that the `Transformation` -/// member `name` ([`about_name`]) names. -fn about(h: &super::Host, item: Item, name: &str, r: Rect) -> std::result::Result { - let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); - Ok(match name { - "CENTER" => Point::new(cx, cy), - "TOP" => Point::new(cx, r.y0), - "BOTTOM" => Point::new(cx, r.y1), - "LEFT" => Point::new(r.x0, cy), - "RIGHT" => Point::new(r.x1, cy), - "TOPLEFT" => Point::new(r.x0, r.y0), - "TOPRIGHT" => Point::new(r.x1, r.y0), - "BOTTOMLEFT" => Point::new(r.x0, r.y1), - "BOTTOMRIGHT" => Point::new(r.x1, r.y1), - "DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(Coords::Document, [0.0, 0.0])))?, - _ => return Err(HostError::Type("give a Transformation value".into())), +/// The largest stroke weight in the path `item`'s own appearance, in points. +pub(super) fn largest_stroke_weight(h: &super::Host, item: Item) -> std::result::Result { + read_path(h, item, |_, n, _| { + n.appearance + .items + .iter() + .filter_map(|item| match item { + vectorcraft_doc::AppearanceItem::Stroke(stroke) => Some(stroke.width), + vectorcraft_doc::AppearanceItem::Fill(_) => None, + }) + .fold(0.0, f64::max) }) } -/// The `objects` and `patterns` options of a transform command from the four flags from `i`: -/// objects, fill patterns, fill gradients and stroke patterns, each left out or true or false. -fn transform_options(a: &[Data], i: usize, params: &mut Value) -> std::result::Result<(), HostError> { - let names = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"]; - let mut flags = [None; 4]; - for (k, name) in names.iter().enumerate() { - flags[k] = given(arg(a, i + k)).map(|d| boolean(d, name)).transpose()?; - } - if flags[2] == Some(false) { - return Err(HostError::Error(format!("{} false is not available yet: gradients move with the art", names[2]))); - } - if let (Some(f), Some(s)) = (flags[1], flags[3]) - && f != s - { - return Err(HostError::Error(format!("{} and {} must be the same here", names[1], names[3]))); - } - if let Some(o) = params.as_object_mut() { - if let Some(b) = flags[0] { - o.insert("objects".into(), json!(b)); - } - if let Some(b) = flags[1].or(flags[3]) { - o.insert("patterns".into(), json!(b)); - } - } - Ok(()) +/// Whether `item` is a path, so [`resized_stroke_weight`] applies to it. +pub(super) fn is_path(h: &super::Host, item: Item) -> bool { + with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))) } -/// `translate(deltaX = 0, deltaY = 0, transformObjects?, transformFillPatterns?, ...)`. -fn path_translate(h: &super::Host, a: &[Data]) -> Answer { - let dx = given(arg(a, 1)).map_or(Ok(0.0), |d| coordinate(d, "deltaX"))?; - let dy = given(arg(a, 2)).map_or(Ok(0.0), |d| coordinate(d, "deltaY"))?; - let item = this_path(h, a)?; - let mut params = json!({"dx": dx, "dy": if h.dom.coords.get() == Coords::Document { -dy } else { dy }}); - transform_options(a, 3, &mut params)?; - if dx != 0.0 || dy != 0.0 { - edit_path(h, item, "object.move", params)?; - } - Ok(Data::Undefined) +/// Whether the path `item` is a member of a compound path or compound shape, whose stroke the +/// compound holds. +pub(super) fn paint_held_by_compound(h: &super::Host, item: Item) -> bool { + with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| paint_owner(&st.doc, item.id, n).id != item.id)) } -/// `rotate(angle, changePositions?, ..., rotateAbout?)`: counterclockwise on the page for a -/// positive angle. -fn path_rotate(h: &super::Host, a: &[Data]) -> Answer { - let angle = number(arg(a, 1), "angle")?; - let item = this_path(h, a)?; - let place = about_name(arg(a, 6))?; - let mut params = json!({"angle": angle}); - transform_options(a, 2, &mut params)?; - if angle.rem_euclid(360.0) != 0.0 - && let (Some(r), _) = item_rect(h, item, false)? - { - let origin = about(h, item, place, r)?; - params["origin"] = json!([origin.x, origin.y]); - edit_path(h, item, "object.rotate", params)?; - } - Ok(Data::Undefined) -} - -/// `resize(scaleX, scaleY, changePositions?, ..., changeLineWidths?, scaleAbout?)`: 100 is 100%; -/// `changeLineWidths` scales the stroke weight by that percent. -fn path_resize(h: &super::Host, a: &[Data]) -> Answer { - let sx = number(arg(a, 1), "scaleX")?; - let sy = number(arg(a, 2), "scaleY")?; - if sx == 0.0 || sy == 0.0 || sx.abs() > 100_000.0 || sy.abs() > 100_000.0 { - return Err(HostError::Range("scaleX and scaleY must not be 0 and at most 100000 percent".into())); - } - let widths = given(arg(a, 7)).map(|d| number(d, "changeLineWidths")).transpose()?; - if widths.is_some_and(|w| !(0.0..=100_000.0).contains(&w)) { - return Err(HostError::Range("changeLineWidths must be from 0 to 100000 percent".into())); - } - let item = this_path(h, a)?; - let place = about_name(arg(a, 8))?; - let mut params = json!({"sx": sx, "sy": sy, "basis": "page", "strokes": false}); - transform_options(a, 3, &mut params)?; - let width = look(h, item)?.width; - let new_width = widths.map(|w| width * w / 100.0); - if new_width.is_some_and(|w| w > MAX_STROKE_WIDTH) { - return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); - } - if (sx != 100.0 || sy != 100.0) - && let (Some(r), _) = item_rect(h, item, false)? - { - let origin = about(h, item, place, r)?; - params["origin"] = json!([origin.x, origin.y]); - edit_path(h, item, "object.scale", params)?; - } - if let Some(w) = new_width - && (w - width).abs() > 1e-9 - { - edit_path(h, item, "stroke.set", json!({"weight": w}))?; - } - Ok(Data::Undefined) +/// Sets the stroke weight of the path `item` to `weight` points. +pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std::result::Result<(), HostError> { + edit_path(h, item, "stroke.set", json!({"weight": weight})).map(|_| ()) } // ---- PathPoints ---- fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result { let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; - let item = path_at(h, *run, *uid, *high, *low)?; + let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; + let item = path_at(h, *run, *uid, *high, *low, *reverts)?; flush_other(h, item)?; Ok(item) } @@ -1282,8 +1406,9 @@ fn points_parent(h: &super::Host, a: &[Data]) -> Answer { } fn point_ref(h: &super::Host, item: Item, i: usize) -> Data { - let [high, low] = id_parts(item.id); - host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))]) + let mut handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)).to_vec(); + handle.extend([float(i as u64), float(point_cuts(h, item))]); + host_ref("PathPoint", &handle) } /// How many times the points read of `item` have gone stale, after [`see_points`] notes a change @@ -1335,7 +1460,10 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { POINT_LOOKS.with(|n| n.set(n.get() + 1)); let node = { let s = h.session.borrow(); - s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned()) + s.documents().iter().find(|d| d.uid == key.0).and_then(|st| { + h.dom.point_docs.borrow_mut().entry(key.0).or_insert_with(|| st.doc.clone()); + node_arc(&st.doc, NodeId(key.1)).cloned() + }) }; // A path that is gone makes its points stale, so that an undo that brings it back leaves them // stale. @@ -1357,56 +1485,98 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { /// [`see_points`] for each path whose points the run has read, after each command, so that a /// change that a later command reverses still makes the points stale. Paths under the object that /// the object model is changing ([`super::State`]), or that object itself, take the change as the -/// object model's own, and their points stay valid. A document that is the one the run last looked -/// at is skipped, as are its paths. While the object model writes one path's points -/// ([`super::State`]'s `one_path`), only that path and tracked paths in its outermost enclosing -/// Objects on Path group are looked at in its document. -pub(super) fn see_all_points(h: &super::Host) { - let keys: Vec<(u64, u64)> = { - let seen = h.dom.point_nodes.borrow(); - if seen.values().all(|paths| paths.is_empty()) { - return; - } +/// object model's own, and their points stay valid; the other Global Edit members, which take the +/// object model's edit too, are looked at as well. A document that is the one the run last looked +/// at is skipped, as are its paths. The look is charged by the objects it looks at. +pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostError> { + let (keys, looked_at): (Vec<(u64, u64)>, u64) = { let s = h.session.borrow(); let mut docs = h.dom.point_docs.borrow_mut(); - let one = h.dom.one_path.get(); + let seen = h.dom.point_nodes.borrow(); let mut keys = Vec::new(); - // The documents that changed since the last look, kept as they are now. - for (uid, paths) in seen.iter().filter(|(_, paths)| !paths.is_empty()) { - // Editing a path in an Objects on Path group can move other paths in the group. - let mut moved = Vec::new(); - match s.documents().iter().find(|d| d.uid == *uid) { - Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => continue, - Some(st) => { - if let Some(item) = one.filter(|i| i.doc.uid == *uid) { - let d = &st.doc; - let group = d.ancestry(item.id).and_then(|a| { - a.into_iter().filter_map(|id| d.node(id)).find(|g| vectorcraft_doc::objects_on_path::is_objects_on_path(g)) - }); - if let Some(g) = group { - g.walk(&mut |n: &crate::doc::Node| { - if n.id != item.id && paths.contains_key(&n.id.0) { - moved.push((*uid, n.id.0)); - } - }); + let mut looked_at = 0u64; + docs.retain(|uid, before| { + let state = s.documents().iter().find(|d| d.uid == *uid); + let after = state.map(|st| &st.doc); + if after.is_some_and(|after| Arc::ptr_eq(before, after)) { + return true; + } + // A document none of whose paths the run still holds points of is not looked at; reading + // points again keeps it as it is then. + if seen.get(uid).is_none_or(std::collections::HashMap::is_empty) { + return false; + } + // Editing a path in an Objects on Path group can move the other paths in the group, so + // the outermost such group is looked at in place of the path. While Global Edit is on, + // an edit of the selected member (also one made by moving a group that holds it) is + // given to the other members, so each of them, or the outermost Objects on Path group + // holding it, is looked at too. Subtrees the command left as they were are skipped. + // Each node is paired with the node of the same id under the same parent now, so that no + // node is searched for through the whole document. + let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) { + Some(item) => { + let root = |id: NodeId| { + before + .ancestry(id) + .and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))) + .unwrap_or(id) + }; + let members = state.and_then(|st| st.global_edit.as_ref()).map(|ge| ge.members.iter().map(|(id, _)| *id)).into_iter().flatten(); + let mut roots = std::collections::HashSet::new(); + std::iter::once(item.id) + .chain(members) + .map(root) + .filter(|id| roots.insert(*id)) + .filter_map(|id| node_arc(before, id).map(|n| (n, after.and_then(|d| node_arc(d, id))))) + .collect() + } + None => paired(&before.layers, after.map(|d| &d.layers), &mut looked_at), + }; + // A group that moved to another parent keeps its node, so a node with children that is + // not found under its old parent is looked for among all the nodes now, listed once. + let mut all: Option>> = None; + while let Some((node, mut now)) = todo.pop() { + looked_at += 1; + if now.is_none() + && node.children().is_some() + && let Some(d) = after + { + let all = all.get_or_insert_with(|| { + let mut m = std::collections::HashMap::new(); + let mut stack: Vec<&Arc> = d.layers.iter().collect(); + while let Some(n) = stack.pop() { + m.insert(n.id, n); + stack.extend(n.children().into_iter().flatten()); } - } - docs.insert(*uid, st.doc.clone()); + looked_at += m.len() as u64; + m + }); + now = all.get(&node.id).copied(); } - None => { - docs.remove(uid); + if now.is_some_and(|n| Arc::ptr_eq(node, n)) { + continue; + } + if seen.get(uid).is_some_and(|paths| paths.contains_key(&node.id.0)) { + keys.push((*uid, node.id.0)); + } + if let Some(children) = node.children() { + todo.extend(paired(children, now.and_then(|n| n.children()), &mut looked_at)); } } - match one { - Some(item) if item.doc.uid == *uid => { - keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0))); - keys.append(&mut moved); - } - _ => keys.extend(paths.keys().map(|id| (*uid, *id))), + if let Some(after) = after { + *before = after.clone(); + true + } else { + false } - } - keys + }); + keys.sort_unstable(); + keys.dedup(); + (keys, looked_at) }; + if looked_at > 0 { + h.charge_call(looked_at)?; + } let editing = h.dom.editing.get(); for (uid, id) in keys { let own = || match editing { @@ -1419,6 +1589,20 @@ pub(super) fn see_all_points(h: &super::Host) { }; see_points(h, (uid, id), own); } + Ok(()) +} + +/// Pairs each node of `before` with the node of the same id in `after`, adding to `looked_at` the +/// nodes of `after` it looks at. +fn paired<'a>( + before: &'a [Arc], + after: Option<&'a Vec>>, + looked_at: &mut u64, +) -> Vec<(&'a Arc, Option<&'a Arc>)> { + let after = after.map_or(&[][..], Vec::as_slice); + *looked_at += after.len() as u64; + let now: std::collections::HashMap> = after.iter().map(|n| (n.id, n)).collect(); + before.iter().map(|n| (n, now.get(&n.id).copied())).collect() } fn points_at(h: &super::Host, a: &[Data]) -> Answer { @@ -1486,8 +1670,8 @@ fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer { /// point of the path removed or replaced since `this` was read. pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> { let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) }; - let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; - let item = path_at(h, *run, *uid, *high, *low)?; + let [run, uid, high, low, reverts, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; + let item = path_at(h, *run, *uid, *high, *low, *reverts)?; flush_other(h, item)?; if whole(*cuts) != Some(point_cuts(h, item)) { return Err(HostError::Error(STALE_POINT.into())); @@ -1524,17 +1708,7 @@ fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Resul let p = point(arg(a, 1), what)?; let (item, _) = this_point(h, a)?; let fr = with_doc(h, item.doc, |_, st| frame(st))?; - on_canvas(fr.to_document(h.dom.coords.get(), p), what) -} - -/// `p`, a point a script gave in document coordinates, when it is on the canvas (within -/// [`crate::MAX_COORD`] of the origin); a `RangeError` otherwise. -fn on_canvas(p: Point, what: &str) -> std::result::Result { - if p.x.is_finite() && p.y.is_finite() && p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD { - Ok(p) - } else { - Err(HostError::Range(format!("{what} is outside the canvas"))) - } + in_canvas(fr.to_document(h.dom.coords.get(), p), what) } fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer { @@ -1602,12 +1776,18 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[ if held { return true; } - if !sel.contains(id) || sel.segments.contains_key(&id) { + if !sel.contains(id) { return false; } match sel.partial(id) { None => true, - Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)), + Some(picked) => locate(subs, i).is_some_and(|(s, j)| { + picked.contains(&(s, j)) + && !sel + .segments + .get(&id) + .is_some_and(|segments| segments.iter().any(|&(sub, at)| sub == s && (at == j || (at + 1) % subs[s].anchors.len() == j))) + }), } } @@ -1619,12 +1799,19 @@ fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool { /// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point /// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in -/// [`super::State`] are written first only when they add or remove points of this path, since -/// the selection names anchors by their place in the document's path. +/// [`super::State`] are written first when they add or remove points of this path or invalidate +/// selected segments. fn pt_selected(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; let moved = match &*h.dom.pending.borrow() { - Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?, + Some((waiting, subs)) if same_path(*waiting, item) => read_path(h, item, |st, _, pd| { + !same_layout(subs, &pd.subpaths) + || st + .selection + .segments + .get(&item.id) + .is_some_and(|segments| segments.iter().any(|&(s, i)| !subs.get(s).is_some_and(|sp| i < sp.segment_count()))) + })?, _ => false, }; if moved { @@ -1692,22 +1879,31 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { let picked: Vec = read_path(h, item, |st, _, pd| { let sel = &st.selection; let held = held_selected(&st.doc, sel, item.id); - if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) { + if !held && !sel.contains(item.id) { return Vec::new(); } - let mut out = Vec::new(); - let mut first = 0; + let segments = sel.segments.get(&item.id); + let ends: std::collections::BTreeSet<_> = segments + .into_iter() + .flatten() + .filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())])) + .flatten() + .collect(); + let partial = sel.partial(item.id).filter(|_| !held); + let mut picked = Vec::new(); + let mut offset = 0; for (s, sp) in pd.subpaths.iter().enumerate() { - let n = sp.anchors.len(); - out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); - first += n; + for j in 0..sp.anchors.len() { + if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) { + picked.push(offset + j); + } + } + offset += sp.anchors.len(); } - out + picked })?; h.charge_call(picked.len() as u64)?; - let [high, low] = id_parts(item.id); - let cuts = float(point_cuts(h, item)); - let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect(); + let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); Ok(Data::Array(points)) } @@ -1765,10 +1961,13 @@ fn remove_point(h: &super::Host, item: Item, i: usize, selected: Option Vec { - let transform = |first: &[(&'static str, &'static str)]| { - let mut args: Vec<(&str, &str)> = first.to_vec(); - args.extend([ - ("changePositions", "boolean"), - ("changeFillPatterns", "boolean"), - ("changeFillGradients", "boolean"), - ("changeStrokePattern", "boolean"), - ]); - args - }; - let mut resize = transform(&[("scaleX", "number"), ("scaleY", "number")]); - resize.extend([("changeLineWidths", "number"), ("scaleAbout", "Transformation")]); - let mut rotate = transform(&[("angle", "number")]); - rotate.push(("rotateAbout", "Transformation")); - let translate = [ - ("deltaX", "number"), - ("deltaY", "number"), - ("transformObjects", "boolean"), - ("transformFillPatterns", "boolean"), - ("transformFillGradients", "boolean"), - ("transformStrokePattern", "boolean"), - ]; + // `translate`, `rotate` and `resize` are `PageItem`'s ([`super::transform`]). let mut m = named(vec![ ("pathPoints", point_get(l, path_points), MemberInfo { collection: true, ..typed("PathPoints") }), ("closed", point_property(l, path_closed, path_set_closed), typed("boolean")), @@ -1878,12 +2056,9 @@ pub(super) fn path_item_members(l: &Link) -> Vec { ), ("strokeCap", property(l, path_stroke_cap, path_set_stroke_cap), typed("StrokeCap")), ("strokeJoin", property(l, path_stroke_join, path_set_stroke_join), typed("StrokeJoin")), - ("strokeMiterLimit", property(l, path_miter, path_set_miter), typed("number")), + ("strokeMiterLimit", property(l, path_miter, path_set_miter), MemberInfo { min: Some(1.0), max: Some(500.0), ..typed("number") }), ("strokeDashes", property(l, path_dashes, path_set_dashes), typed("Array")), ("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset), typed("number")), - ("translate", method(l, path_translate), returns("undefined", &translate)), - ("rotate", method(l, path_rotate), returns("undefined", &rotate)), - ("resize", method(l, path_resize), returns("undefined", &resize)), ("selectedPathPoints", get(l, path_selected_points), typed("Array")), ]); m.extend(["polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n))); @@ -1903,8 +2078,9 @@ pub(super) fn classes(l: &Link) -> Vec { None, named(vec![ ("typename", get(l, items_typename), typed("string")), + ("toString", super::class_text("PathItems"), returns("string", &[])), ("length", get(l, items_length), typed("number")), - ("parent", get(l, items_parent), typed("Document")), + ("parent", get(l, items_parent), typed("*")), ("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])), ("getByName", method(l, items_by_name), returns("PathItem", &[("name", "string")])), ("removeAll", method(l, items_remove_all), returns("undefined", &[])), @@ -1962,13 +2138,78 @@ pub(super) fn classes(l: &Link) -> Vec { #[cfg(test)] mod tests { + use std::cell::Cell; + use super::*; + use crate::Session; + + thread_local! { + pub(super) static LOCATE_STEPS: Cell = const { Cell::new(0) }; + } + + #[test] + fn selected_points_do_not_rescan_subpaths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let subpaths = vec![json!({"anchors": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 10}, {"x": 0, "y": 10}], "closed": true}); 128]; + s.execute("path.setAnchors", &json!({"id": id, "subpaths": subpaths})).unwrap(); + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 3], [127, 3]]})).unwrap(); + s.execute("select.segments", &json!({"id": id, "segments": [[0, 0], [127, 1]], "mode": "add"})).unwrap(); + LOCATE_STEPS.with(|steps| steps.set(0)); + let out = s + .execute("script.run", &json!({"source": "vc.log(app.activeDocument.pathItems[0].selectedPathPoints.length);", "name": "t.js"})) + .unwrap(); + assert_eq!(out["log"], json!([2])); + LOCATE_STEPS.with(|steps| assert!(steps.get() <= 512, "subpath visits: {}", steps.get())); + } + + #[test] + fn undoing_a_point_write_selects_the_anchors_it_removed_again() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 3]]})).unwrap(); + let source = "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 0], [10, 0], [10, 10]]); \ + vc.log(p.selectedPathPoints.length); app.undo();"; + let out = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + assert_eq!(out["log"], json!([1])); + let id = NodeId(id.as_u64().unwrap()); + let anchors: Vec<(usize, usize)> = s.active().unwrap().selection.anchors.get(&id).map(|a| a.iter().copied().collect()).unwrap_or_default(); + assert_eq!(anchors, vec![(0, 1), (0, 3)], "the undo puts back the selection the write changed"); + } + + #[test] + fn undoing_a_point_write_in_a_background_document_selects_its_anchors_again() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let text = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 3]]})).unwrap(); + let uid = s.active().unwrap().uid; + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let st = s.document_mut(uid).unwrap(); + let NodeKind::Text(t) = &mut Arc::make_mut(&mut st.doc).node_mut(NodeId(text)).unwrap().kind else { panic!("not a text object") }; + t.cached_bounds = None; + let before_activation = st.doc.clone(); + let source = "var d; for (var i = 0; i < app.documents.length; i++) { if (app.documents[i].pathItems.length) d = app.documents[i]; } \ + d.pathItems[0].setEntirePath([[0, 0], [10, 0], [10, 10]]); app.activeDocument = d; app.undo();"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + let id = NodeId(id.as_u64().unwrap()); + let st = s.documents().iter().find(|d| d.uid == uid).unwrap(); + assert!(!Arc::ptr_eq(&st.doc, &before_activation)); + assert!(matches!(&st.doc.node(NodeId(text)).unwrap().kind, NodeKind::Text(t) if t.cached_bounds.is_some())); + assert_eq!(st.doc.node(id).and_then(|n| n.path_data()).map(|pd| pd.subpaths[0].anchors.len()), Some(4)); + let anchors: Vec<(usize, usize)> = st.selection.anchors.get(&id).map(|a| a.iter().copied().collect()).unwrap_or_default(); + assert_eq!(anchors, vec![(0, 1), (0, 3)], "the undo puts back the selection the write changed"); + } #[test] fn a_made_id_above_two_to_the_53_stays_exact() { - assert_eq!(made_id(&json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993))); - assert_eq!(made_id(&json!({"id": 7})), Ok(NodeId(7))); - assert!(made_id(&json!({"id": 1.5})).is_err()); - assert!(made_id(&json!({})).is_err()); + let made = |v: Value| made_id(&(Data::Undefined, v)); + assert_eq!(made(json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993))); + assert_eq!(made(json!({"id": 7})), Ok(NodeId(7))); + assert!(made(json!({"id": 1.5})).is_err()); + assert!(made(json!({})).is_err()); } } diff --git a/crates/engine/src/script/dom/preferences.rs b/crates/engine/src/script/dom/preferences.rs new file mode 100644 index 0000000000..c4308efba2 --- /dev/null +++ b/crates/engine/src/script/dom/preferences.rs @@ -0,0 +1,297 @@ +//! `app.preferences`, as the help page +//! describes it: values a script reads and stores by key with a getter and a setter for each type. +//! +//! `ShowExternalJSXWarning` is the preference `showExternalScriptWarning`, the warning before a +//! script picked with File › Scripts › Other Script… runs. A script turns it on at once; turning it +//! off waits for the person to answer Yes to a confirm, and throws when the run cannot ask anyone +//! (VectorCraft's own rule). Every other key is kept in +//! [`crate::Prefs::script_preferences`], with the preferences, so it lasts across runs and restarts +//! and a failed or stopped run puts it back as it was. +//! +//! VectorCraft's own rules, which the help page does not state: +//! - A key that was never stored reads as `false`, `0`, `0` or `""`. +//! - A getter of another type converts the stored value as `Boolean`, `Number` or `String` do; +//! `getIntegerPreference` drops the fraction, and gives `0` for a value that is not a number. +//! - A key is a string of 1 to [`MAX_KEY_UNITS`] UTF-16 units without control characters, a string +//! value has at most [`MAX_STRING_BYTES`] bytes, and at most [`MAX_KEYS`] keys and +//! [`MAX_TOTAL_BYTES`] bytes are stored. A set that would pass a limit throws and stores nothing. +//! - A setter's value must have its type: `setIntegerPreference` takes a whole number within +//! ±2^53, and `setRealPreference` a finite number. +//! - Removing a key that is not stored does nothing; removing `ShowExternalJSXWarning` turns the +//! warning back on. + +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; + +use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text, typed, typename_of}; +use crate::ScriptPreference; +use crate::script::dialogs::{DialogKind, OnYes, ScriptDialog}; + +/// The key that stands for the preference `showExternalScriptWarning`. +pub const EXTERNAL_SCRIPT_WARNING: &str = "ShowExternalJSXWarning"; +/// The longest key, in UTF-16 units. +pub const MAX_KEY_UNITS: usize = 256; +/// The longest string value, in bytes. +pub const MAX_STRING_BYTES: usize = 64 * 1024; +/// The most keys stored. +pub const MAX_KEYS: usize = 4096; +/// The most bytes stored, keys and values together; a value that is not a string counts 8. +pub const MAX_TOTAL_BYTES: usize = 1024 * 1024; + +/// The confirm a run shows before a script turns off [`EXTERNAL_SCRIPT_WARNING`]; No is its default. +pub const WARNING_OFF_QUESTION: &str = "The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off?"; +/// The error when a script turns off [`EXTERNAL_SCRIPT_WARNING`] in a run that cannot ask the person. +pub const WARNING_OFF_NEEDS_A_PERSON: &str = + "ShowExternalJSXWarning can be turned off only after the person at the computer agrees, in a run that can show a dialog"; + +/// The largest whole number `setIntegerPreference` takes. +const MAX_INTEGER: f64 = 9_007_199_254_740_992.0; + +/// The `app.preferences` member of `Application`. +pub(super) fn app_members() -> Vec { + named(vec![("preferences", HostMember::Get(std::rc::Rc::new(|_| Ok(host_ref("Preferences", &[])))), typed("Preferences"))]) +} + +/// The `Preferences` class. +pub(super) fn class(link: &Link) -> HostClass { + let l = link; + let key = [("key", "string")]; + super::class( + "Preferences", + None, + named(vec![ + ("typename", typename_of("Preferences"), typed("string")), + ("getBooleanPreference", method(l, |h, a| get(h, a, Kind::Boolean)), returns("boolean", &key)), + ("getIntegerPreference", method(l, |h, a| get(h, a, Kind::Integer)), returns("number", &key)), + ("getRealPreference", method(l, |h, a| get(h, a, Kind::Real)), returns("number", &key)), + ("getStringPreference", method(l, |h, a| get(h, a, Kind::String)), returns("string", &key)), + ("setBooleanPreference", method(l, |h, a| set(h, a, Kind::Boolean)), returns("undefined", &[("key", "string"), ("value", "boolean")])), + ("setIntegerPreference", method(l, |h, a| set(h, a, Kind::Integer)), returns("undefined", &[("key", "string"), ("value", "number")])), + ("setRealPreference", method(l, |h, a| set(h, a, Kind::Real)), returns("undefined", &[("key", "string"), ("value", "number")])), + ("setStringPreference", method(l, |h, a| set(h, a, Kind::String)), returns("undefined", &[("key", "string"), ("value", "string")])), + ("removePreference", method(l, remove), returns("undefined", &key)), + ]), + None, + ) +} + +#[derive(Clone, Copy)] +enum Kind { + Boolean, + Integer, + Real, + String, +} + +/// The key of a call on `app.preferences`: `this` must be that object, and the key a string within +/// the limits. +fn key_of(a: &[Data]) -> std::result::Result<&str, HostError> { + if !matches!(host_ref_parts(arg(a, 0)), Some(("Preferences", _))) { + return Err(HostError::Type("this is not a Preferences object".into())); + } + let Data::String(key) = arg(a, 1) else { return Err(HostError::Type("a preference's key must be a string".into())) }; + if key.is_empty() || key.encode_utf16().count() > MAX_KEY_UNITS { + return Err(HostError::Range(format!( + "a preference's key must have a length of 1 to {MAX_KEY_UNITS} (UTF-16 code units, as `length` counts)" + ))); + } + if key.chars().any(char::is_control) { + return Err(HostError::Error("a preference's key cannot hold control characters".into())); + } + Ok(key) +} + +/// The value stored under `key`, if any. +fn stored(h: &Host, key: &str) -> Option { + let s = h.session.borrow(); + if key == EXTERNAL_SCRIPT_WARNING { + return Some(ScriptPreference::Boolean(s.prefs.show_external_script_warning)); + } + s.prefs.script_preferences.get(key).cloned() +} + +/// `Number(text)`: blank text is 0, `0x`, `0o` and `0b` start a whole number in base 16, 8 or 2, +/// and text that is not a number is NaN. The whitespace trimmed is JavaScript's: Unicode's +/// `White_Space` without U+0085 (NEXT LINE), and U+FEFF. +fn text_number(t: &str) -> f64 { + let t = t.trim_matches(|c: char| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}'); + if t.is_empty() { + return 0.0; + } + let radix = match t.get(..2) { + Some("0x" | "0X") => 16, + Some("0o" | "0O") => 8, + Some("0b" | "0B") => 2, + _ => 0, + }; + if radix != 0 { + return radix_number(t.get(2..).unwrap_or(""), radix).unwrap_or(f64::NAN); + } + match t.strip_prefix(['+', '-']).unwrap_or(t) { + "Infinity" => { + if t.starts_with('-') { + f64::NEG_INFINITY + } else { + f64::INFINITY + } + } + rest if rest.bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E' | b'+' | b'-')) => t.parse().unwrap_or(f64::NAN), + _ => f64::NAN, + } +} + +/// The whole number `digits` writes in base `radix` (16, 8 or 2), rounded once to the nearest +/// number, ties to the even one, and infinite past the largest; `None` when it is empty or holds a +/// character that is not a digit of that base. +fn radix_number(digits: &str, radix: u32) -> Option { + if digits.is_empty() { + return None; + } + let width = radix.trailing_zeros(); + // The first 64 bits from the leading 1, how many bits come after them, and whether any of + // those is 1. + let (mut top, mut taken, mut past, mut sticky) = (0u64, 0u32, 0u64, false); + for c in digits.chars() { + let d = c.to_digit(radix)?; + for bit in (0..width).rev().map(|i| (d >> i) & 1 == 1) { + if taken == 0 && !bit { + continue; + } + if taken < 64 { + top = (top << 1) | u64::from(bit); + taken += 1; + } else { + past = past.saturating_add(1); + sticky |= bit; + } + } + } + if taken <= 53 { + return Some(top as f64); + } + // Keep 53 bits; the dropped ones round them to the nearest, ties to even. + let drop = taken - 53; + let (kept, rest, half) = (top >> drop, top & ((1u64 << drop) - 1), 1u64 << (drop - 1)); + let up = rest > half || (rest == half && (sticky || kept & 1 == 1)); + let kept = kept + u64::from(up); + let exp = i32::try_from(u64::from(drop).saturating_add(past)).unwrap_or(i32::MAX).min(2000); + Some(kept as f64 * 2f64.powi(exp)) +} + +#[allow(clippy::cast_precision_loss)] +fn as_number(v: &ScriptPreference) -> f64 { + match v { + ScriptPreference::Boolean(b) => f64::from(u8::from(*b)), + ScriptPreference::Integer(n) => *n as f64, + ScriptPreference::Real(n) => *n, + ScriptPreference::String(t) => text_number(t), + } +} + +fn get(h: &Host, a: &[Data], kind: Kind) -> Answer { + let key = key_of(a)?; + let v = stored(h, key); + Ok(match (kind, v) { + (Kind::Boolean, None) => Data::Bool(false), + (Kind::Integer | Kind::Real, None) => num(0.0), + (Kind::String, None) => text(""), + (Kind::Boolean, Some(v)) => Data::Bool(match v { + ScriptPreference::Boolean(b) => b, + ScriptPreference::String(t) => !t.is_empty(), + v => { + let n = as_number(&v); + n != 0.0 && !n.is_nan() + } + }), + (Kind::Real, Some(v)) => num(as_number(&v)), + (Kind::Integer, Some(v)) => { + let n = as_number(&v).trunc(); + num(if n.is_finite() { n } else { 0.0 }) + } + (Kind::String, Some(v)) => text(match v { + ScriptPreference::Boolean(b) => b.to_string(), + ScriptPreference::String(t) => t, + v => vectorcraft_js::number_to_string(as_number(&v)), + }), + }) +} + +/// The bytes `key` and `v` count toward [`MAX_TOTAL_BYTES`]. +fn size(key: &str, v: &ScriptPreference) -> usize { + key.len() + if let ScriptPreference::String(t) = v { t.len() } else { 8 } +} + +/// Whether `store` holds at most [`MAX_KEYS`] keys and [`MAX_TOTAL_BYTES`] bytes. +pub fn within_limits(store: &std::collections::BTreeMap) -> bool { + store.len() <= MAX_KEYS && store.iter().map(|(k, v)| size(k, v)).sum::() <= MAX_TOTAL_BYTES +} + +#[allow(clippy::cast_possible_truncation)] +fn set(h: &Host, a: &[Data], kind: Kind) -> Answer { + let key = key_of(a)?.to_string(); + let v = arg(a, 2); + let value = match (kind, v) { + (Kind::Boolean, Data::Bool(b)) => ScriptPreference::Boolean(*b), + (Kind::Integer, Data::Number(n)) if n.fract() == 0.0 && n.abs() <= MAX_INTEGER => ScriptPreference::Integer(*n as i64), + (Kind::Real, Data::Number(n)) if n.is_finite() => ScriptPreference::Real(*n), + (Kind::String, Data::String(t)) if t.len() <= MAX_STRING_BYTES => ScriptPreference::String(t.clone()), + (Kind::String, Data::String(_)) => return Err(HostError::Range(format!("a preference's text has at most {MAX_STRING_BYTES} bytes"))), + (Kind::Boolean, _) => return Err(HostError::Type("setBooleanPreference needs true or false".into())), + (Kind::Integer, _) => return Err(HostError::Type("setIntegerPreference needs a whole number".into())), + (Kind::Real, _) => return Err(HostError::Type("setRealPreference needs a finite number".into())), + (Kind::String, _) => return Err(HostError::Type("setStringPreference needs a string".into())), + }; + if key == EXTERNAL_SCRIPT_WARNING { + let ScriptPreference::Boolean(on) = value else { + return Err(HostError::Type(format!("{EXTERNAL_SCRIPT_WARNING} is set with setBooleanPreference"))); + }; + return set_warning(h, on); + } + let mut s = h.session.borrow_mut(); + let store = &mut s.prefs.script_preferences; + if store.get(&key) == Some(&value) { + return Ok(Data::Undefined); + } + let total: usize = store.iter().filter(|(k, _)| **k != key).map(|(k, v)| size(k, v)).sum(); + let count = store.len() + usize::from(!store.contains_key(&key)); + if count > MAX_KEYS { + return Err(HostError::Range(format!("app.preferences holds at most {MAX_KEYS} keys"))); + } + if total + size(&key, &value) > MAX_TOTAL_BYTES { + return Err(HostError::Range(format!("app.preferences holds at most {MAX_TOTAL_BYTES} bytes"))); + } + store.insert(key, value); + Ok(Data::Undefined) +} + +/// Sets `showExternalScriptWarning` in the run's preferences: on at once, and off only after the +/// person answers Yes to [`WARNING_OFF_QUESTION`] ([`crate::Session::script_answer`] sets it). With +/// nobody to ask, turning it off throws and changes nothing. Scripts cannot run `prefs.set`; the +/// run's preferences are put back when the run fails and merged into the app's when it ends. +fn set_warning(h: &Host, on: bool) -> Answer { + if on || !h.session.borrow().prefs.show_external_script_warning { + h.session.borrow_mut().prefs.show_external_script_warning = on; + return Ok(Data::Undefined); + } + let question = ScriptDialog { + kind: DialogKind::Confirm, + message: WARNING_OFF_QUESTION.into(), + title: None, + error_icon: false, + no_as_default: true, + preset: String::new(), + }; + if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) { + return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into())); + } + Err(HostError::Wait) +} + +fn remove(h: &Host, a: &[Data]) -> Answer { + let key = key_of(a)?; + if key == EXTERNAL_SCRIPT_WARNING { + h.session.borrow_mut().prefs.show_external_script_warning = true; + } else if h.session.borrow().prefs.script_preferences.contains_key(key) { + h.session.borrow_mut().prefs.script_preferences.remove(key); + } + Ok(Data::Undefined) +} diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 2e1d374cb1..13e9222864 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -545,6 +545,8 @@ struct Job { paper_size: bool, /// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says. source: bool, + /// `colorProfileMode` is assigned `CUSTOMPROFILE`: `name` must name the profile. + custom: bool, /// `printArea` is assigned: the artboards print even when the base settings ignore them. print_area: bool, /// The groups of `settings`: the top level and each nested object by its key. @@ -693,6 +695,7 @@ fn map_color(h: &Host, slot: usize, job: &mut Job) { let source = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "SOURCEPROFILE"); job.profile = set.iter().find(|(k, _)| *k == "name").map(|(_, v)| string_of(v)); job.source = source; + job.custom = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "CUSTOMPROFILE"); let g = job.group("color"); for (k, v) in &set { if *k == "intent" { @@ -992,7 +995,7 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer { /// each assigned name against the list it must come from, and puts the checked names into the /// job: a print or flattener preset by its name (any case), an RGB or CMYK color profile by its /// name (any case) and a paper by its id or label. An empty name, or one with a path separator or -/// a control character, throws. +/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name`. fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> { let (count, saved_ignore) = with_doc(h, doc, |_, st| { let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str); @@ -1022,6 +1025,9 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos } job.group("advanced").insert("flattenerPreset".into(), json!(n)); } + if job.custom && job.profile.is_none() { + return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into())); + } if let Some(name) = job.profile.take() { let what = "PrintColorManagementOptions.name"; let n = plain_name(what, "color profile", &name)?; diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs new file mode 100644 index 0000000000..f067b430d4 --- /dev/null +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -0,0 +1,696 @@ +//! Rasterizing art and capturing it as an image in the script object model: `Document.rasterize`, +//! `Document.imageCapture` and their option classes, as the help pages +//! , +//! , +//! and +//! describe. +//! +//! `rasterize` runs `object.rasterize` with the source art's ids, and `imageCapture` runs +//! `document.export` of an area of the page, inside the run's transaction. Every option is given to +//! the command, at the help page's default when the script leaves it out, so the document's raster +//! effects settings do not change the result. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `clipBounds` is `[left, top, right, bottom]` in the run's script coordinates, as +//! `geometricBounds` gives them; the right edge must be right of the left one and the bottom edge +//! below the top one, and the numbers are never swapped. +//! - `rasterize` takes one page item or a list of at most [`super::MAX_LISTED`] of them, all of +//! this document, none listed twice, inside another listed one or a path of a compound path, and +//! none locked or in a locked layer or group. It keeps the selection, less the art it replaces, +//! and gives the new `RasterItem`: with `clippingMask`, the image inside its clip group. +//! `transparency` wins over `backgroundBlack`. `convertSpotColors`, `convertTextToOutlines` and +//! `includeLayers` true throw an error that says they are not available yet. +//! - `imageCapture` writes a PNG, and the file's name must end with `.png`. Without `clipBounds` it +//! captures the bounds of all the visible art, on the artboards or off them. With +//! `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with +//! `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 +//! to 255. The file is written only where the script's `File` objects may write, and never over +//! an open document's file or a file one of them links, under any of its names (a hard link +//! included); on Unix it is never written over a file that has other hard links. Source paths +//! outside both the automation read and write roots are excluded before +//! filesystem probes. +//! - An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is +//! drawn; the resolution is never lowered to make it fit. +//! - `windowCapture` throws an error that says it is not available yet. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_geom::Rect; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; + +use super::{ + Answer, Described, Doc, Host, Link, MAX_LISTED, STALE_ITEM, arg, boolean, class, command, command_value, coordinate, current, frame, given, + item_of, item_ref, later, method, named, num, on_doc, returns, text, this_doc, with_doc, +}; + +/// The lowest resolution the option classes take, in pixels per inch. +pub const MIN_RESOLUTION: f64 = 72.0; +/// The highest resolution the option classes take, in pixels per inch. +pub const MAX_RESOLUTION: f64 = 2400.0; +/// The most room `RasterizeOptions.padding` adds around the art, in points. +pub const MAX_PADDING: f64 = 1000.0; +/// The error of a source art object from another document. +pub const OTHER_DOCUMENT: &str = "The source art must be in this document"; + +/// The enumerations these members use, as `dom`'s are made. +pub(super) const ENUMS: &[(&str, &[&str])] = + &[("AntiAliasingMethod", &["ARTOPTIMIZED", "None", "TYPEOPTIMIZED"]), ("RasterizationColorModel", &["BITMAP", "DEFAULTCOLORMODEL", "GRAYSCALE"])]; + +/// The member of `enumeration` that `d` names (`"Enumeration.MEMBER"`). +fn member<'a>(d: &'a Data, enumeration: &str, what: &str) -> std::result::Result<&'a str, HostError> { + let members = ENUMS.iter().find(|(n, _)| *n == enumeration).map_or(&[][..], |(_, m)| *m); + let bad = || HostError::Type(format!("{what} must be a {enumeration} value")); + let Data::String(s) = d else { return Err(bad()) }; + let m = s.strip_prefix(enumeration).and_then(|r| r.strip_prefix('.')).ok_or_else(bad)?; + if members.contains(&m) { Ok(m) } else { Err(bad()) } +} + +/// A finite number from `lo` to `hi`. +fn number_in(d: &Data, what: &str, lo: f64, hi: f64) -> std::result::Result { + match d { + Data::Number(n) if n.is_finite() => { + if (lo..=hi).contains(n) { + Ok(*n) + } else { + Err(HostError::Range(format!("{what} must be from {lo} to {hi}"))) + } + } + _ => Err(HostError::Type(format!("{what} must be a finite number"))), + } +} + +/// The fields of the options object `d` of `class`, or `None` when the script gave none. +fn options<'a>(d: &'a Data, class: &str) -> std::result::Result, HostError> { + match given(d) { + None | Some(Data::Null) => Ok(None), + Some(Data::Object(items)) if items.iter().any(|(k, v)| k == "typename" && matches!(v, Data::String(s) if s == class)) => Ok(Some(items)), + Some(_) => Err(HostError::Type(format!("the options must be a {class} object"))), + } +} + +/// `clipBounds`, `[left, top, right, bottom]` in the run's script coordinates, as a rectangle in +/// document coordinates; `None` when the script gave none. +fn clip_bounds(h: &Host, doc: Doc, d: &Data) -> std::result::Result, HostError> { + let a = match given(d) { + None | Some(Data::Null) => return Ok(None), + Some(Data::Array(a)) if a.len() == 4 => a, + Some(_) => return Err(HostError::Type("clipBounds must be an array of four numbers [left, top, right, bottom]".into())), + }; + let mut n = [0.0; 4]; + for (o, d) in n.iter_mut().zip(a) { + *o = coordinate(d, "clipBounds")?; + } + let f = with_doc(h, doc, |_, st| frame(st))?; + let c = h.dom.coords.get(); + let (p0, p1) = (f.to_document(c, [n[0], n[1]]), f.to_document(c, [n[2], n[3]])); + if p1.x <= p0.x || p1.y <= p0.y { + return Err(HostError::Range("clipBounds must have its right edge right of its left edge and its bottom edge below its top edge".into())); + } + Ok(Some(Rect::new(p0.x, p0.y, p1.x, p1.y))) +} + +/// Throws when an image of `region` at `ppi` would be more than 64 megapixels or longer than the +/// renderer draws on a side, before anything is drawn. +fn check_size(region: Rect, ppi: f64) -> std::result::Result<(), HostError> { + let scale = ppi / 72.0; + let (w, h) = ((region.width() * scale).round().max(1.0), (region.height() * scale).round().max(1.0)); + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + if w * h > crate::cmd::menucmds::MAX_PIXELS || w > side || h > side { + return Err(HostError::Range(format!( + "the image would be {w} × {h} pixels; images are limited to 64 megapixels and {side} pixels a side: lower the resolution or the bounds" + ))); + } + Ok(()) +} + +// ---- Rasterize ---- + +/// `object.rasterize`'s params for the `RasterizeOptions` fields `items` (`None`: the defaults), +/// with every option given. +fn rasterize_params(items: Option<&[(String, Data)]>) -> std::result::Result, HostError> { + let (mut anti_alias, mut black, mut clear, mut clip, mut model, mut padding, mut ppi) = ("art", false, false, false, "document", 0.0, 300.0); + for (k, v) in items.unwrap_or_default() { + if matches!(v, Data::Undefined) { + continue; + } + let what = format!("RasterizeOptions.{k}"); + match k.as_str() { + "antiAliasingMethod" => { + anti_alias = match member(v, "AntiAliasingMethod", &what)? { + "None" => "none", + "TYPEOPTIMIZED" => "type", + _ => "art", + } + } + "backgroundBlack" => black = boolean(v, &what)?, + "transparency" => clear = boolean(v, &what)?, + "clippingMask" => clip = boolean(v, &what)?, + "colorModel" => { + model = match member(v, "RasterizationColorModel", &what)? { + "BITMAP" => "bitmap", + "GRAYSCALE" => "grayscale", + _ => "document", + } + } + "padding" => padding = number_in(v, &what, 0.0, MAX_PADDING)?, + "resolution" => ppi = number_in(v, &what, MIN_RESOLUTION, MAX_RESOLUTION)?, + "convertSpotColors" | "convertTextToOutlines" | "includeLayers" if boolean(v, &what)? => { + return Err(HostError::Error(format!("{what} is not available yet"))); + } + _ => {} + } + } + let background = if clear { + "transparent" + } else if black { + "black" + } else { + "white" + }; + let mut p = Map::new(); + p.insert("ppi".into(), json!(ppi)); + p.insert("background".into(), json!(background)); + p.insert("antiAlias".into(), json!(anti_alias)); + p.insert("padding".into(), json!(padding)); + p.insert("colorModel".into(), json!(model)); + p.insert("clippingMask".into(), json!(clip)); + Ok(p) +} + +/// The ids of the source art `d` names for `rasterize` in the document `doc`: one page item, or a +/// list of them, none inside another listed one. The command checks that none is listed twice or +/// locked. +fn sources(h: &Host, doc: Doc, d: &Data) -> std::result::Result, HostError> { + let list: Vec<&Data> = match d { + Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("rasterize takes at most {MAX_LISTED} objects"))), + Data::Array(a) => a.iter().collect(), + Data::Undefined | Data::Null => return Err(HostError::Type("rasterize needs the source art, a page item or a list of them".into())), + d => vec![d], + }; + if list.is_empty() { + return Err(HostError::Error("rasterize needs at least one page item".into())); + } + h.charge_call(16 * list.len() as u64)?; + let mut ids = Vec::with_capacity(list.len()); + for d in list { + let item = item_of(h, d)?; + if item.doc.uid != doc.uid { + return Err(HostError::Error(OTHER_DOCUMENT.into())); + } + ids.push(item.id.0); + } + let listed: std::collections::HashSet = ids.iter().copied().collect(); + let inside = with_doc(h, doc, |_, st| { + ids.iter().find_map(|id| { + let up = st.doc.ancestry(crate::NodeId(*id))?; + up.iter().any(|a| a.0 != *id && listed.contains(&a.0)).then_some(()) + }) + }); + if inside.is_some() { + return Err(HostError::Error("a source page item is inside another one, which is listed too".into())); + } + Ok(ids) +} + +/// `document.rasterize(sourceArt, clipBounds?, options?)`: `object.rasterize` of the source art, +/// which the image replaces in one undo step. → the new `RasterItem`. +fn doc_rasterize(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let ids = sources(h, doc, arg(a, 1))?; + let clip = clip_bounds(h, doc, arg(a, 2))?; + let mut p = rasterize_params(options(arg(a, 3), "RasterizeOptions")?)?; + p.insert("ids".into(), json!(ids)); + if let Some(r) = clip { + p.insert("clipBounds".into(), json!([r.x0, r.y0, r.x1, r.y1])); + } + // The image's id is read from the command's own result inside the run's savepoint, so an id + // that a script number cannot hold exactly still names the image, and a missing one undoes the edit. + let (r, image) = on_doc(h, doc.uid, true, |h| { + let (r, value) = command_value(h, "object.rasterize", &Value::Object(p))?; + let image = value.get("imageId").and_then(Value::as_u64).ok_or_else(|| HostError::Error("the image was not made".into()))?; + Ok((r, image)) + })?; + super::save_open::command_warnings(h, "rasterize", &r); + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(item_ref(h, st, crate::NodeId(image))) +} + +// ---- Image capture ---- + +/// A channel of `matteColor`: a finite number from 0 to 255. +fn channel(items: &[(String, Data)], key: &str) -> std::result::Result { + let d = items.iter().find(|(k, _)| k == key).map_or(&Data::Undefined, |(_, v)| v); + let n = number_in(d, &format!("ImageCaptureOptions.matteColor.{key}"), 0.0, 255.0)?; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let byte = n.round() as u8; + Ok(byte) +} + +/// The capture's resolution and `document.export`'s `background` and `antiAlias` for the +/// `ImageCaptureOptions` fields `items` (`None`: the defaults). +fn capture_settings(items: Option<&[(String, Data)]>) -> std::result::Result<(f64, String, &'static str), HostError> { + let (mut anti_alias, mut matte, mut clear, mut ppi) = (false, false, false, 150.0); + let mut color = [255u8; 3]; + for (k, v) in items.unwrap_or_default() { + if matches!(v, Data::Undefined) { + continue; + } + let what = format!("ImageCaptureOptions.{k}"); + match k.as_str() { + "antiAliasing" => anti_alias = boolean(v, &what)?, + "matte" => matte = boolean(v, &what)?, + "transparency" => clear = boolean(v, &what)?, + "resolution" => ppi = number_in(v, &what, MIN_RESOLUTION, MAX_RESOLUTION)?, + "matteColor" => { + let Data::Object(c) = v else { return Err(HostError::Type(format!("{what} must be an RGBColor"))) }; + color = [channel(c, "red")?, channel(c, "green")?, channel(c, "blue")?]; + } + _ => {} + } + } + let background = if clear { + "transparent".to_string() + } else if matte { + format!("#{:02x}{:02x}{:02x}", color[0], color[1], color[2]) + } else { + "white".to_string() + }; + Ok((ppi, background, if anti_alias { "art" } else { "none" })) +} + +/// The files a capture must not write over: the open documents' files and the files their linked +/// images and placed documents show, wherever those are stored (opacity masks, symbols, patterns +/// and brushes included), with a DCS image's plate files, also when a file is missing, in the form +/// [`placed`] gives. A link's places are the ones opening the document looks at: its stored path +/// from the document's folder and its relative path from the folder of the file the document was +/// read from (a template opened as an untitled document has no file of its own), with a DCS +/// image's plate files beside each. The documents the interface has open while the run's slice +/// runs, such as one opened while the run was paused, count too. +fn sources_on_disk(h: &Host) -> Vec { + let s = h.session.borrow(); + let interface = h.interface_docs.borrow(); + let mut paths: Vec = Vec::new(); + for st in s.documents().iter().chain(interface.iter()) { + paths.extend(st.path.clone()); + paths.extend(crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st))); + } + paths.iter().filter_map(|p| source_place(p)).collect() +} + +/// An open document or linked file inside the automation read or write roots: one that only a write +/// root covers is compared too, since a capture may write there. A path outside both is left out +/// before it is looked up, as no capture can write it; the refusal names only the requested path. +fn source_place(path: &str) -> Option { + if crate::file_access::check_read(path).is_err() && crate::file_access::check_write_unrecorded(path).is_err() { + return None; + } + placed(std::path::Path::new(path)) +} + +/// A file as its folder's real path and its name. +type Placed = (std::path::PathBuf, std::ffi::OsString); + +/// `p` as its folder's real path and its file name: from its real path with links followed, or, +/// for a file that is not there, from its folder's real path. `None` when neither the file nor its +/// folder is there. +fn placed(p: &std::path::Path) -> Option { + let real = std::fs::canonicalize(p).ok().or_else(|| Some(std::fs::canonicalize(p.parent()?).ok()?.join(p.file_name()?)))?; + Some((real.parent()?.to_path_buf(), real.file_name()?.to_os_string())) +} + +/// Whether two [`placed`] files are one file: the same folder, and the same name, or names that +/// differ only in letter case in a folder whose volume ignores case, or only in their Unicode +/// normalization form in a folder whose volume ignores that. +fn same_file(a: &Placed, b: &Placed) -> bool { + if !same_folder(&a.0, &b.0) { + return false; + } + if a.1 == b.1 { + return true; + } + let (x, y) = (a.1.to_string_lossy(), b.1.to_string_lossy()); + let form = |s: &str| unicode_normalization::UnicodeNormalization::nfc(s).collect::(); + if form(&x) == form(&y) { + return ignores_normalization(&a.0); + } + let (lx, ly) = (x.to_lowercase(), y.to_lowercase()); + if form(&lx) != form(&ly) || !ignores_case(&a.0) { + return false; + } + lx == ly || ignores_normalization(&a.0) +} + +/// Whether file names in the real folder `folder` ignore their Unicode normalization form: the +/// first of the folder's first 256 entries whose name changes between the composed (NFC) and +/// decomposed (NFD) forms, and that is not a symbolic link, is looked up in the other form, and +/// names ignore the form when that finds the same entry. With no such entry, names ignore the form +/// on macOS, whose volumes (APFS and HFS+) look names up that way, and on Linux in a folder that +/// carries the casefold inode flag ([`casefolded`]): ext4 and f2fs casefolding also ignores the +/// form, as they are taken to when the flag can't be read. Elsewhere names keep the form. +fn ignores_normalization(folder: &std::path::Path) -> bool { + use unicode_normalization::UnicodeNormalization; + for entry in std::fs::read_dir(folder).into_iter().flatten().flatten().take(256) { + let Some(name) = entry.file_name().to_str().map(str::to_string) else { continue }; + let (c, d): (String, String) = (name.nfc().collect(), name.nfd().collect()); + let other = if name == c { d } else { c }; + if other != name && entry.file_type().is_ok_and(|t| !t.is_symlink()) { + return finds_same(&entry.path(), &folder.join(other)); + } + } + #[cfg(target_os = "linux")] + { + casefolded(folder) + } + #[cfg(not(target_os = "linux"))] + { + cfg!(target_os = "macos") + } +} + +/// `FS_CASEFOLD_FL` from Linux's `include/uapi/linux/fs.h`: the folder looks names up casefolded. +#[cfg(target_os = "linux")] +const FS_CASEFOLD_FL: u32 = 0x4000_0000; + +/// Whether the Linux folder `folder` carries the casefold inode flag, read with +/// `FS_IOC_GETFLAGS`. `true` when the folder can't be opened or its flags can't be read: `false` +/// only when the flags are read and the flag is clear. +#[cfg(target_os = "linux")] +fn casefolded(folder: &std::path::Path) -> bool { + std::fs::File::open(folder).ok().and_then(|d| rustix::fs::ioctl_getflags(&d).ok()).is_none_or(|f| has_casefold(f.bits())) +} + +/// Whether the inode flags `bits` include `FS_CASEFOLD_FL`. +#[cfg(target_os = "linux")] +fn has_casefold(bits: u32) -> bool { + bits & FS_CASEFOLD_FL != 0 +} + +/// The check `imageCapture` makes on the file it writes, `p`, given as written or as the real path +/// of its folder with its name: it is none of the `sources` ([`sources_on_disk`]), not one of them +/// under another name, and has no other hard links. +fn capture_target_check(p: &std::path::Path, sources: &[Placed], shown: &str) -> Result<(), String> { + let real = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + if placed(&real).is_some_and(|t| sources.iter().any(|s| same_file(&t, s) || same_identity(&real, &s.0.join(&s.1)))) { + return Err(format!("imageCapture cannot write over an open document or a file it links: {shown}")); + } + if has_other_links(&real) { + return Err(format!("imageCapture cannot write over a file that has other hard links: {shown}")); + } + Ok(()) +} + +#[cfg(test)] +thread_local! { + /// Run once in `imageCapture` after its checks and before its export, for tests that change the + /// destination in between. + pub(crate) static BEFORE_CAPTURE_EXPORT: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Whether two real paths are one file or folder: the same path, or, on Unix, the same device and +/// file number, so a path spelled in another letter case on a volume that ignores case still +/// matches. On Windows a real path carries the letter case stored on disk. +fn same_folder(a: &std::path::Path, b: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if a == b { + return true; + } + if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) { + return x.dev() == y.dev() && x.ino() == y.ino(); + } + false + } + #[cfg(not(unix))] + { + a == b + } +} + +/// Whether two existing paths name one file on disk, such as two hard links to it: the same device +/// and file number on Unix, or the same volume and file index on Windows. `false` when either is +/// missing. +fn same_identity(a: &std::path::Path, b: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + matches!((std::fs::metadata(a), std::fs::metadata(b)), (Ok(x), Ok(y)) if (x.dev(), x.ino()) == (y.dev(), y.ino())) + } + #[cfg(windows)] + { + same_file::is_same_file(a, b).unwrap_or(false) + } + #[cfg(not(any(unix, windows)))] + { + let _ = (a, b); + false + } +} + +/// Whether the existing file at `p` has more than one name on Unix: writing into it in place, when +/// its folder refuses a replacement, would change the file under its other names too. Always +/// `false` off Unix, where [`same_identity`] compares the protected files instead. +fn has_other_links(p: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.nlink() > 1) + } + #[cfg(not(unix))] + { + let _ = p; + false + } +} + +/// Whether `other`, a spelling of `entry` in other letter case, finds `entry` itself and not a +/// symbolic link or another file. +fn finds_same(entry: &std::path::Path, other: &std::path::Path) -> bool { + if !std::fs::symlink_metadata(other).is_ok_and(|m| !m.file_type().is_symlink()) { + return false; + } + match (std::fs::canonicalize(entry), std::fs::canonicalize(other)) { + (Ok(a), Ok(b)) => same_folder(&a, &b), + _ => false, + } +} + +/// `name` with the letter case of every ASCII letter swapped, and other characters as they are. +fn swapped_case(name: &str) -> String { + name.chars().map(|c| if c.is_ascii_lowercase() { c.to_ascii_uppercase() } else { c.to_ascii_lowercase() }).collect() +} + +/// Whether file names in the real folder `folder` ignore letter case. Names keep case when two of +/// the folder's first 256 entries differ only in the case of ASCII letters. Otherwise the first of +/// them whose name has an ASCII letter and that is not a symbolic link is looked up with the case +/// of those letters swapped: names ignore case when that finds the same entry. With no such entry +/// on macOS, where a whole volume either ignores or keeps case, the nearest folder at or above +/// `folder` whose name has an ASCII letter, with its parent on the same volume, is looked up the +/// same way in its parent. When neither tells, names are taken to ignore case. +fn ignores_case(folder: &std::path::Path) -> bool { + let entries: Vec = std::fs::read_dir(folder).into_iter().flatten().flatten().take(256).collect(); + let mut folded = std::collections::HashSet::new(); + let names: std::collections::HashSet = entries.iter().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + if !names.iter().all(|n| folded.insert(n.to_ascii_lowercase())) { + return false; + } + for entry in &entries { + let name = entry.file_name().to_string_lossy().into_owned(); + let swapped = swapped_case(&name); + if swapped != name && entry.file_type().is_ok_and(|t| !t.is_symlink()) { + return finds_same(&entry.path(), &folder.join(swapped)); + } + } + #[cfg(target_os = "macos")] + for dir in folder.ancestors() { + use std::os::unix::fs::MetadataExt; + let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else { break }; + let device = |p: &std::path::Path| std::fs::metadata(p).map(|m| m.dev()).ok(); + let here = device(folder); + if here.is_none() || device(dir) != here || device(parent) != here { + break; + } + let name = name.to_string_lossy(); + let swapped = swapped_case(&name); + if swapped != name { + return finds_same(dir, &parent.join(swapped)); + } + } + true +} + +/// `document.imageCapture(imageFile, clipBounds?, options?)`: `document.export` of a PNG of the +/// art inside `clipBounds`, or of all the visible art. +fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = vectorcraft_js::file_ref_path(arg(a, 1)).ok_or_else(|| HostError::Type("imageCapture needs a File".into()))?; + let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase(); + if !name.ends_with(".png") || name.len() <= ".png".len() { + return Err(HostError::Error("imageCapture writes a PNG file: give it a name that ends with .png".into())); + } + let clip = clip_bounds(h, doc, arg(a, 2))?; + let (ppi, background, anti_alias) = capture_settings(options(arg(a, 3), "ImageCaptureOptions")?)?; + let region = match clip { + Some(r) => r, + None => with_doc(h, doc, |_, st| crate::cmd::fileio::export_art_bounds(&st.doc, "png")) + .ok_or_else(|| HostError::Error("the document has no visible art to capture".into()))?, + }; + check_size(region, ppi)?; + let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?; + let sources = sources_on_disk(h); + let shown = path.to_string(); + // Checked here, and again as the export commits its file, so a destination changed into a link + // to a protected file while the art renders is refused too. + let guard = move |p: &std::path::Path| capture_target_check(p, &sources, &shown); + guard(&real).map_err(HostError::Error)?; + let plain = crate::cmd::findfiles::plain(real); + let Some(plain) = plain.to_str() else { + return Err(HostError::Error(format!("imageCapture cannot write to a path that is not valid UTF-8: {path}"))); + }; + let p = json!({ + "path": plain, + "format": "png", + "rect": [region.x0, region.y0, region.width(), region.height()], + "ppi": ppi, + "background": background, + "antiAlias": anti_alias, + "includeArtboardFill": false, + }); + #[cfg(test)] + BEFORE_CAPTURE_EXPORT.with(|f| f.borrow_mut().take().map(|f| f())); + h.disk.borrow_mut().exact = true; + let r = crate::file_access::with_write_guard(std::rc::Rc::new(guard), || on_doc(h, doc.uid, false, |h| command(h, "document.export", &p))); + h.disk.borrow_mut().exact = false; + super::save_open::command_warnings(h, "imageCapture", &r?); + Ok(Data::Undefined) +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec { + let mut members = named(vec![ + ( + "rasterize", + method(l, doc_rasterize), + returns("RasterItem", &[("sourceArt", "*"), ("clipBounds", "Array"), ("options", "RasterizeOptions")]), + ), + ( + "imageCapture", + method(l, doc_image_capture), + returns("undefined", &[("imageFile", "File"), ("clipBounds", "Array"), ("options", "ImageCaptureOptions")]), + ), + ]); + members.push(later(l, "Document", "windowCapture")); + members +} + +/// The fields a new options object starts with. +type Starts = fn() -> Vec<(&'static str, Data)>; + +fn rasterize_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasingMethod", text("AntiAliasingMethod.ARTOPTIMIZED")), + ("backgroundBlack", Data::Bool(false)), + ("clippingMask", Data::Bool(false)), + ("colorModel", text("RasterizationColorModel.DEFAULTCOLORMODEL")), + ("convertSpotColors", Data::Bool(false)), + ("convertTextToOutlines", Data::Bool(false)), + ("includeLayers", Data::Bool(false)), + ("padding", num(0.0)), + ("resolution", num(300.0)), + ("transparency", Data::Bool(false)), + ] +} + +fn capture_starts() -> Vec<(&'static str, Data)> { + let white = Data::Object(vec![ + ("typename".to_string(), text("RGBColor")), + ("red".to_string(), num(255.0)), + ("green".to_string(), num(255.0)), + ("blue".to_string(), num(255.0)), + ]); + vec![ + ("antiAliasing", Data::Bool(false)), + ("matte", Data::Bool(false)), + ("matteColor", white), + ("resolution", num(150.0)), + ("transparency", Data::Bool(false)), + ] +} + +/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its +/// help page gives. +pub(super) fn classes(link: &Link) -> Vec { + let all: [(&'static str, Starts); 2] = [("RasterizeOptions", rasterize_starts), ("ImageCaptureOptions", capture_starts)]; + all.into_iter() + .map(|(name, starts)| { + let l = link.clone(); + let f: HostFunction = Rc::new(move |_: Vec| { + current(&l)?.charge_call(64)?; + let mut items = vec![("typename".to_string(), text(name))]; + items.extend(starts().into_iter().map(|(k, v)| (k.to_string(), v))); + Ok(Data::Object(items)) + }); + HostClass { construct: Some(f), ..class(name, None, Vec::new(), None) } + }) + .collect() +} + +#[cfg(test)] +mod source_tests { + use super::*; + + #[test] + fn capture_sources_keep_files_outside_automation_read_roots() { + let dir = vectorcraft_testkit::TempDir::new("capture-source-roots"); + let readable = dir.join("readable"); + let writable = dir.join("writable"); + std::fs::create_dir(&readable).unwrap(); + std::fs::create_dir(&writable).unwrap(); + let inside = readable.join("doc.vectorcraft"); + // An open document that only a write root covers: a capture to its path must still be + // refused. + let outside = writable.join("other.vectorcraft"); + // Outside every root: no capture can write it, so it is not looked up. + let elsewhere = dir.join("linked.png"); + std::fs::write(&inside, b"document").unwrap(); + std::fs::write(&outside, b"document").unwrap(); + std::fs::write(&elsewhere, b"linked").unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&readable], &[&writable]).unwrap(); + crate::file_access::confine(roots.as_ref(), || { + assert!(source_place(&inside.to_string_lossy()).is_some()); + assert!(source_place(&elsewhere.to_string_lossy()).is_none()); + let source = source_place(&outside.to_string_lossy()).expect("a source outside the read roots is still compared"); + let target = placed(&outside).unwrap(); + assert!(same_file(&target, &source)); + }); + } + + /// In an empty Linux folder, names that differ only in their normalization form are one file + /// only when the folder is casefolded. On a folder without the flag they are distinct, and + /// nothing is written into the folder to find out. + #[cfg(target_os = "linux")] + #[test] + fn names_in_another_normalization_form_match_only_in_a_casefolded_empty_folder() { + let dir = vectorcraft_testkit::TempDir::new("capture-nfd-distinct"); + let folder = std::fs::canonicalize(&*dir).unwrap(); + let (linked, capture): (Placed, Placed) = ((folder.clone(), "cafe\u{301}.png".into()), (folder.clone(), "caf\u{e9}.png".into())); + assert_eq!(same_file(&capture, &linked), casefolded(&folder)); + assert_eq!(std::fs::read_dir(&folder).unwrap().count(), 0); + } + + /// A casefolded folder, which looks a name up in either normalization form, is recognized by + /// its inode flag. A folder whose flags can't be read is taken for one, so a capture is never + /// written over a source under a name in another normalization form. + #[cfg(target_os = "linux")] + #[test] + fn a_casefolded_folder_is_recognized_by_its_inode_flag() { + assert!(has_casefold(FS_CASEFOLD_FL)); + assert!(has_casefold(FS_CASEFOLD_FL | 0x10)); + assert!(!has_casefold(0x10)); + assert!(!has_casefold(0)); + let dir = vectorcraft_testkit::TempDir::new("capture-nfd-missing"); + assert!(casefolded(&dir.join("missing"))); + } +} diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 237576b64d..34f7755d1a 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -8,7 +8,8 @@ //! , //! , //! , -//! and +//! , +//! and //! describe. //! //! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's @@ -18,14 +19,21 @@ //! commands may use. //! //! VectorCraft's own rules, which the help pages do not state: -//! - `saveAs` without options saves in the format the path's extension names; it writes the file -//! at the path as given. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and +//! - `saveAs` without options selects the format from the script's file name before resolving +//! symbolic links. A name without a recognized extension uses the document's current format. +//! Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and //! `exportFile` as PNG24, JPEG or SVG use the defaults a new options object of that class holds. //! `exportFile` adds the format's extension unless the name already ends //! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes //! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. //! An SVG with `embedRasterImages` false also writes the document's embedded images beside it, //! and when one of those files may not be written, none of them is. +//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF +//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not +//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page +//! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to +//! true colors, PNG, millimeters and 100. `unitScaleRatio` is a percentage: at 100 one `unit` is +//! one drawing unit. It is at least 0.0001 and at most 1000. //! - An option the classes here map is applied; a listed option that is not mapped is accepted at //! the default its help page gives and throws an error that says it is not available yet at any //! other value; a property the help pages do not list throws an error that names it, unless it is @@ -40,8 +48,8 @@ //! save of one artboard writes only the file at the path, holding that artboard. Without //! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of //! artboard numbers throws. -//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no -//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. +//! - `Document.path` is a `Folder` for the folder of the document's file. A file saved or opened +//! under a relative path is in the process's working folder. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. //! `fullName` and `path` of a document whose file the automation read roots do not allow throw //! `Script file access denied`. Changing `Document.saved` runs `document.setSaved`. //! Assigning its current value runs no command. @@ -64,6 +72,7 @@ use std::cell::Cell; use std::rc::Rc; use serde_json::{Map, Value, json}; +use vectorcraft_doc::Unit; use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; use super::{ @@ -86,6 +95,15 @@ pub(in crate::script) struct State { /// The enumerations these members use, as `dom`'s are made. pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("ExportType", &["AutoCAD", "FLASH", "GIF", "JPEG", "PNG24", "PNG8", "SVG", "TIFF"]), + ("AutoCADColors", &["Max8Colors", "Max16Colors", "Max256Colors", "TrueColors"]), + ( + "AutoCADCompatibility", + &["AutoCADRelease13", "AutoCADRelease18", "AutoCADRelease14", "AutoCADRelease21", "AutoCADRelease15", "AutoCADRelease24"], + ), + ("AutoCADExportFileFormat", &["DXF", "DWG"]), + ("AutoCADExportOption", &["PreserveAppearance", "MaximizeEditability"]), + ("AutoCADRasterFormat", &["PNG", "JPEG"]), + ("AutoCADUnit", &["Points", "Picas", "Inches", "Millimeters", "Centimeters", "Pixels"]), ( "Compatibility", &[ @@ -182,6 +200,10 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("SVGFontType", &["CEFFONT", "OUTLINEFONT", "SVGFONT"]), ]; +/// Other names of enumeration members: `(enumeration, name, member)` makes `enumeration.name` the +/// same value as `enumeration.member`. +pub(super) const ALIASES: &[(&str, &str, &str)] = &[("ExportType", "AUTOCAD", "AutoCAD")]; + const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; const QUIET: &str = "UserInteractionLevel.DONTDISPLAYALERTS"; @@ -196,6 +218,9 @@ enum Default { Member(&'static str, &'static str), /// The help page gives no default: any value throws. Unset, + /// White as an `RGBColor`: red, green and blue each 255 (its `typename`, when it has one, + /// `RGBColor`). + White, } impl Default { @@ -205,6 +230,11 @@ impl Default { (Default::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9, (Default::Text(a), Data::String(b)) => a == b, (Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m), + (Default::White, Data::Object(items)) => { + let get = |k: &str| items.iter().find(|(name, _)| name == k).map(|(_, v)| v); + get("typename").is_none_or(|t| matches!(t, Data::String(t) if t == "RGBColor")) + && ["red", "green", "blue"].iter().all(|k| matches!(get(k), Some(Data::Number(n)) if *n == 255.0)) + } _ => false, } } @@ -560,7 +590,7 @@ fn png24_map(name: &str, d: &Data, p: &mut Map) -> std::result::R raster_map("ExportOptionsPNG24", name, d, p) } -const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; +const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))]; fn png24_starts() -> Vec<(&'static str, Data)> { vec![ @@ -588,7 +618,7 @@ fn jpeg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Re } const JPEG_KEPT: &[(&str, Default)] = - &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; + &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))]; fn jpeg_starts() -> Vec<(&'static str, Data)> { vec![ @@ -649,9 +679,120 @@ fn svg_starts() -> Vec<(&'static str, Data)> { ] } +/// The members of the enumeration `name` in [`ENUMS`]. +fn members_of(name: &str) -> &'static [&'static str] { + ENUMS.iter().find(|(n, _)| *n == name).map_or(&[][..], |(_, m)| *m) +} + +fn autocad_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("ExportOptionsAutoCAD.{name}"); + let pick = |enumeration: &str| member(d, enumeration, members_of(enumeration), &what); + match name { + "alterPathsForAppearance" => { + p.insert("alterPaths".into(), json!(boolean(d, &what)?)); + } + "colors" => { + let colors = match pick("AutoCADColors")? { + "Max8Colors" => json!(8), + "Max16Colors" => json!(16), + "Max256Colors" => json!(256), + _ => json!("true"), + }; + p.insert("colors".into(), colors); + } + "convertTextToOutlines" => { + p.insert("outlineText".into(), json!(boolean(d, &what)?)); + } + "exportFileFormat" => { + if pick("AutoCADExportFileFormat")? == "DWG" { + return Err(HostError::Error( + "AutoCADExportFileFormat.DWG is not available: set exportFileFormat to AutoCADExportFileFormat.DXF".into(), + )); + } + } + "exportOption" => { + let preserve = if pick("AutoCADExportOption")? == "PreserveAppearance" { "appearance" } else { "editability" }; + p.insert("preserve".into(), json!(preserve)); + } + "exportSelectedArtOnly" => { + p.insert("selectedOnly".into(), json!(boolean(d, &what)?)); + } + "rasterFormat" => { + p.insert("rasterFormat".into(), json!(if pick("AutoCADRasterFormat")? == "JPEG" { "jpeg" } else { "png" })); + } + "scaleLineweights" => { + p.insert("scaleLineweights".into(), json!(boolean(d, &what)?)); + } + "unit" => { + let unit = match pick("AutoCADUnit")? { + "Points" => Unit::Points, + "Picas" => Unit::Picas, + "Inches" => Unit::Inches, + "Millimeters" => Unit::Millimeters, + "Centimeters" => Unit::Centimeters, + _ => Unit::Pixels, + }; + p.insert("unit".into(), json!(unit.key())); + } + "unitScaleRatio" => { + let n = match d { + Data::Number(n) if n.is_finite() => *n, + _ => return Err(HostError::Type(format!("{what} must be a finite number"))), + }; + // A percentage: the DXF writer's `scale` is `n / 100`, and its smallest scale (1e-6) is + // 0.0001%. + if !(0.0001..=1000.0).contains(&n) { + return Err(HostError::Range(format!("{what} must be at least 0.0001 and at most 1000"))); + } + p.insert("scale".into(), json!((n / 100.0).max(*vectorcraft_cad::SCALE_RANGE.start()))); + } + "version" => { + let version = match pick("AutoCADCompatibility")? { + "AutoCADRelease13" => "R13", + "AutoCADRelease14" => "R14", + "AutoCADRelease15" => "2000", + "AutoCADRelease18" => "2004", + "AutoCADRelease21" => "2007", + _ => "2010", + }; + p.insert("version".into(), json!(version)); + } + _ => return Ok(false), + } + Ok(true) +} + +fn autocad_starts() -> Vec<(&'static str, Data)> { + vec![ + ("alterPathsForAppearance", Data::Bool(false)), + ("convertTextToOutlines", Data::Bool(false)), + ("exportFileFormat", text("AutoCADExportFileFormat.DWG")), + ("exportOption", text("AutoCADExportOption.MaximizeEditability")), + ("exportSelectedArtOnly", Data::Bool(false)), + ("scaleLineweights", Data::Bool(false)), + ("version", text("AutoCADCompatibility.AutoCADRelease24")), + ] +} + +/// The options object `d` with the options of a new `class` object it leaves out, or holds as +/// `undefined`, added. +fn with_starts(class: &OptionClass, d: &Data) -> Data { + let Data::Object(items) = d else { return d.clone() }; + let mut items = items.clone(); + for (k, v) in (class.starts)() { + match items.iter_mut().find(|(n, _)| n == k) { + Some((_, held)) if matches!(held, Data::Undefined) => *held = v, + Some(_) => {} + None => items.push((k.to_string(), v)), + } + } + Data::Object(items) +} + const PNG24: OptionClass = OptionClass { name: "ExportOptionsPNG24", map: png24_map, kept: PNG24_KEPT, starts: png24_starts }; const JPEG: OptionClass = OptionClass { name: "ExportOptionsJPEG", map: jpeg_map, kept: JPEG_KEPT, starts: jpeg_starts }; const SVG: OptionClass = OptionClass { name: "ExportOptionsSVG", map: svg_map, kept: SVG_KEPT, starts: svg_starts }; +const AUTOCAD: OptionClass = OptionClass { name: "ExportOptionsAutoCAD", map: autocad_map, kept: &[], starts: autocad_starts }; /// An `ExportType`: the format `document.export` writes, the extensions a file name may already /// end with (the first is added), and its option class (`None`: no options are taken). @@ -662,9 +803,9 @@ struct ExportKind { } fn export_kind(d: &Data) -> std::result::Result { - let all = ENUMS.iter().find(|(n, _)| *n == "ExportType").map_or(&[][..], |(_, m)| *m); let raster = |format, extensions| ExportKind { format, extensions, options: None }; - Ok(match member(d, "ExportType", all, "exportType")? { + Ok(match member(d, "ExportType", members_of("ExportType"), "exportType")? { + "AutoCAD" => ExportKind { format: "dxf", extensions: &["dxf"], options: Some(&AUTOCAD) }, "PNG24" => ExportKind { format: "png", extensions: &["png"], options: Some(&PNG24) }, "JPEG" => ExportKind { format: "jpg", extensions: &["jpg", "jpeg"], options: Some(&JPEG) }, "SVG" => ExportKind { format: "svg", extensions: &["svg"], options: Some(&SVG) }, @@ -733,13 +874,31 @@ pub(super) fn refused(message: &str, path: &str) -> HostError { /// Runs `f` with the commands' reads and writes held to the script's own grants /// ([`super::super::files::Disk::exact`]). -pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { +pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Result) -> Result { h.disk.borrow_mut().exact = true; let r = f(); h.disk.borrow_mut().exact = false; r } +/// Writes each warning in a command's answer `result` to the console after `method`'s name. +pub(super) fn command_warnings(h: &Host, method: &str, result: &Data) { + if let Data::Object(items) = result { + for (key, value) in items { + let warnings: &[Data] = match (key.as_str(), value) { + ("warning", Data::String(_)) => std::slice::from_ref(value), + ("warnings", Data::Array(warnings)) => warnings, + _ => continue, + }; + for warning in warnings { + if let Data::String(warning) = warning { + super::super::each_line(&format!("{method}: {warning}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + } + } + } +} + /// Runs command `id` with `p` and writes each warning it gives to the console after `method`'s /// name, as `app.documents.addDocument` does: what a save or an export leaves out of its file, or /// a linked image an open could not read. → the command's answer. @@ -841,11 +1000,26 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { None => Map::new(), }, Some(o) => match kind.options { + // An AutoCAD option left out takes its help page's default, not the DXF writer's. + Some(class) if class.name == AUTOCAD.name => options_params(class, &with_starts(class, o))?, Some(class) => options_params(class, o)?, None if matches!(o, Data::Null) => return Err(HostError::Type("the options must be an object".into())), None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), }, }; + // A DXF version before 2004 holds no true color: with `colors` left out it takes 256 indexed + // colors, and `AutoCADColors.TrueColors` with it throws. + if kind.format == "dxf" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) { + match p.get("colors") { + None => { + p.insert("colors".into(), json!(256)); + } + Some(c) if c.as_str() == Some("true") => { + return Err(HostError::Error("AutoCADColors.TrueColors needs AutoCADRelease18 or a later version".into())); + } + Some(_) => {} + } + } let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false); let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false); let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0)); @@ -853,7 +1027,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into())); } // A raster file has one pixel per point at 100%, whatever the document's raster effects resolution. - if kind.format != "svg" { + // A DXF's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100. + if !matches!(kind.format, "svg" | "dxf") { p.insert("scale".into(), json!(hs / 100.0)); } let format = if svgz { "svgz" } else { kind.format }; @@ -1015,12 +1190,13 @@ const SAVES_SOME_ARTBOARDS: &str = "the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; /// Whether the file that saving `st` with its remembered options writes would omit artboards. A -/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai` -/// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its -/// `range` names only the separate files. An EPS file embeds the whole document in its main file, -/// so its `artboardRange` never omits an artboard from what reopens. +/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file holds every +/// artboard, and its `range` names only the separate files of `separateArtboards`. A `.ai` file +/// other than a legacy version 7 one with `separateArtboards` holds every artboard too. An EPS +/// file embeds the whole document in its main file, so its `artboardRange` never omits an artboard +/// from what reopens. fn picks_artboards(st: &crate::doc_state::DocState) -> bool { - if st.format == "eps" { + if matches!(st.format, "eps" | "vectorcraft" | "template") { return false; } let options = Value::Object(crate::cmd::fileio::remembered_save_options(st)); @@ -1032,7 +1208,7 @@ fn picks_artboards(st: &crate::doc_state::DocState) -> bool { return true; } let legacy = crate::cmd::fileio::saves_legacy_ai(st.format, &options); - if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy { + if matches!(st.format, "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy { return false; } let count = st.doc.artboards.len(); @@ -1132,7 +1308,7 @@ pub(super) fn document_members(l: &Link) -> Vec { /// The option classes: each `new Name()` gives a record with its `typename` and the defaults its /// help page gives for the options mapped here. pub(super) fn classes(link: &Link) -> Vec { - let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG]); + let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG, &AUTOCAD]); all.map(|c| { let l = link.clone(); let f: HostFunction = Rc::new(move |_: Vec| { diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 3c4acac317..58f1103874 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1,12 +1,16 @@ -//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its +//! Type in the script object model: the `textFrames` of a document, a layer and a group, 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 +//! , +//! and //! describe them. //! //! VectorCraft's own rules, which the help pages do not state: +//! - A layer's or group's `textFrames` list the type directly in it, topmost first. Their `add()`, +//! `pointText`, `areaText` and `pathText` put the new type on top of its contents, and a hidden +//! or locked layer or group throws. //! - 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. @@ -33,6 +37,8 @@ //! 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`. +//! - `fillColor` and `strokeColor` take and give color objects as a path's do; a `NoColor` takes +//! the paint away. `strokeWeight` is 0 to 1000 points. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, VecDeque}; @@ -40,13 +46,14 @@ use std::rc::Rc; use std::sync::{Arc, Weak}; use serde_json::{Value, json}; +use vectorcraft_color::Paint; 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, + Answer, Described, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, boolean, class, colors, 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}; @@ -59,6 +66,10 @@ 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; +/// The most bytes the offset tables of the frames' indexes hold in a run. Past it the tables of +/// the other frames are given up; their text, generations and edits stay, and each frame's tables +/// are made again when it is next read. +const INDEX_BUDGET: usize = 64 << 20; /// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units. pub(super) struct Index { @@ -102,6 +113,22 @@ impl Index { Self { text, chars, bytes, words, paras } } + /// The text alone, without its offset tables, for a frame whose tables were given up under + /// [`INDEX_BUDGET`]; [`observe`] makes them again before the index is read. + fn bare(text: String) -> Self { + Self { text, chars: Vec::new(), bytes: Vec::new(), words: Vec::new(), paras: Vec::new() } + } + + fn is_bare(&self) -> bool { + self.chars.is_empty() + } + + /// The bytes the offset tables hold. + fn table_bytes(&self) -> usize { + let pairs = self.words.capacity() + self.paras.capacity(); + (self.chars.capacity() + self.bytes.capacity()) * size_of::() + pairs * size_of::<(usize, usize)>() + } + fn len(&self) -> usize { self.chars.last().copied().unwrap_or(0) } @@ -202,10 +229,32 @@ pub(in crate::script) struct TextState { made: Cell, /// The span of each range object, by its number, whose `length` the script set. resized: RefCell>, + /// The bytes the offset tables of the frames' indexes hold ([`INDEX_BUDGET`]). + table_bytes: Cell, /// The styles the run's style objects name. styles: styles::StyleState, } +/// Puts `index` in the log of frame `key` and keeps the offset tables of all the frames within +/// [`INDEX_BUDGET`], giving up the tables of other frames first. +fn set_index(state: &TextState, frames: &mut HashMap<(u64, u64), Log>, key: (u64, u64), index: Index) { + let mut total = state.table_bytes.get() + index.table_bytes(); + if let Some(l) = frames.get_mut(&key) { + total -= l.index.table_bytes(); + l.index = Rc::new(index); + } + for (k, l) in frames.iter_mut() { + if total <= INDEX_BUDGET { + break; + } + if *k != key && !l.index.is_bare() { + total -= l.index.table_bytes(); + l.index = Rc::new(Index::bare(l.index.text.clone())); + } + } + state.table_bytes.set(total); +} + fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { match &st.doc.node(id)?.kind { NodeKind::Text(t) => Some(t), @@ -231,29 +280,36 @@ fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc {} + let fresh = match frames.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => None, Some(l) => { - if l.reverts != st.reverts || !same_text(t, &l.index.text) { + let changed = l.reverts != st.reverts || !same_text(t, &l.index.text); + if changed { 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; + changed.then(|| t.plain_text()) } None => { let l = Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, - index: Rc::new(Index::new(t.plain_text())), + index: Rc::new(Index::bare(String::new())), stamp: 0, floor: 0, edits: VecDeque::new(), }; frames.insert(key, l); + Some(t.plain_text()) } + }; + // Tables given up under the budget are made again from the text the log keeps. + let fresh = fresh.or_else(|| frames.get(&key).filter(|l| l.index.is_bare()).map(|l| l.index.text.clone())); + if let Some(text) = fresh { + set_index(&h.dom.text, &mut frames, key, Index::new(text)); } let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; Ok((l.index.clone(), l.stamp)) @@ -303,6 +359,27 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u }) } +/// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing +/// changed, when the frame or a layer or group it is in is hidden or locked, or the frame is on a +/// locked artboard. +fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { + refuse_protected(h, item, "TextFrame")?; + edit_item(h, item, id, params) +} + +/// Throws `Cannot edit` for the `class` object of `item` when it or a layer or group it is in is +/// hidden or locked, or it is on a locked artboard. +fn refuse_protected(h: &Host, item: Item, class: &str) -> std::result::Result<(), HostError> { + let (ok, on_locked) = with_doc(h, item.doc, |_, st| (editable(&st.doc, item.id), super::on_locked_artboard(h, st, item.id))); + if !ok { + return Err(HostError::Error(format!("Cannot edit {class} {}: it, or a layer or group it is in, is hidden or locked", item.id.0))); + } + if on_locked { + return Err(HostError::Error(format!("Cannot edit {class} {}: it is on a locked artboard", item.id.0))); + } + Ok(()) +} + /// 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> { @@ -323,9 +400,9 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser l.floor = l.stamp; l.edits.clear(); } - l.index = Rc::new(Index::new(now)); l.doc = Arc::downgrade(&st.doc); l.reverts = st.reverts; + set_index(&h.dom.text, &mut frames, (st.uid, item.id.0), Index::new(now)); Ok(()) }) } @@ -453,7 +530,7 @@ fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { 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}))?; + edit_text(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) } @@ -547,6 +624,7 @@ fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { /// `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)?; + refuse_protected(h, item, "TextFrame")?; 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!({})) @@ -568,6 +646,7 @@ fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))), Some(true) => {} } + refuse_protected(h, item, "TextFrame")?; 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))) @@ -730,35 +809,44 @@ 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) { + // The place, and whether it is the end of a range, which rounds up to a character boundary. + let (at, after) = 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) + (items.clone().next().and_then(span).map_or(s, |(x, _)| x), false) } else { - items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + (items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true) } } else { let rel = arg(a, 2); let target = if handle_of(rel, "TextFrame").is_some() { whole_span(h, item_of(h, rel)?)?.1 + } else if handle_of(rel, "TextRange").is_some() { + span_of(h, rel, &["TextRange"])? } else { - span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))? + // A range of a removed frame keeps its own error. + span_of(h, rel, &["TextRange"]).map_err(|e| match e { + HostError::Error(m) if m == STALE_RANGE => HostError::Error(m), + _ => 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 text_placement(arg(a, 3))? { (te, true) } else { (ts, false) } }; + // A place inside a character (between the two halves of a surrogate pair) moves to its edge. + let b = index.byte(at, after); + let at = index.text[..b].encode_utf16().count(); 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 => ("", ""), @@ -774,7 +862,7 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { ), }; 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}))?; + edit_text(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(); @@ -804,9 +892,12 @@ enum Attr { Underline, StrikeThrough, TextFont, + FillColor, + StrokeColor, + StrokeWeight, } -const ATTRS: [(&str, Attr); 11] = [ +const ATTRS: [(&str, Attr); 14] = [ ("size", Attr::Size), ("leading", Attr::Leading), ("autoLeading", Attr::AutoLeading), @@ -818,6 +909,9 @@ const ATTRS: [(&str, Attr); 11] = [ ("underline", Attr::Underline), ("strikeThrough", Attr::StrikeThrough), ("textFont", Attr::TextFont), + ("fillColor", Attr::FillColor), + ("strokeColor", Attr::StrokeColor), + ("strokeWeight", Attr::StrokeWeight), ]; /// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with @@ -920,11 +1014,28 @@ fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize) Attr::Underline => Data::Bool(s.underline), Attr::StrikeThrough => Data::Bool(s.strikethrough), Attr::TextFont => font_ref(h, &s.font_family, &s.font_style), + Attr::FillColor => colors::of_paint(&s.fill), + Attr::StrokeColor => colors::of_paint(&s.stroke), + Attr::StrokeWeight => num(s.stroke_width * stroke_scale(t)), } } -/// 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> { +/// Document points per text-space point of a character stroke, as `text.setRangeStyle` scales a +/// `strokeWidth` it is given. +fn stroke_scale(t: &TextObject) -> f64 { + vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0) +} + +/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after in +/// the document `doc` (a color as given when there is none). +fn attr_param( + h: &Host, + attr: Attr, + name: &str, + v: &Data, + first: (&TextObject, &CharStyle, usize), + doc: Option<&vectorcraft_doc::Document>, +) -> std::result::Result<(Value, Data), HostError> { let finite = || number(v, name); Ok(match attr { Attr::Size => { @@ -991,6 +1102,21 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, & let (family, style) = font_of(h, v)?; (json!({"font": family, "style": style}), font_ref(h, &family, &style)) } + Attr::FillColor | Attr::StrokeColor => { + let color = colors::assigned(v, name)?; + let given = color.map_or_else(|| json!("none"), |c| colors::param(&c)); + // The paint reads back as the text's document stores it: an RGB color in a CMYK document as CMYK. + let paint = color.map_or(Paint::None, |c| Paint::solid(doc.map_or(c, |d| crate::cmd::newart::stored_color_in(d, c)))); + let key = if matches!(attr, Attr::FillColor) { "fill" } else { "stroke" }; + (json!({ key: given }), colors::of_paint(&paint)) + } + Attr::StrokeWeight => { + let n = finite()?; + if !(0.0..=1000.0).contains(&n) { + return Err(HostError::Range("strokeWeight must be from 0 to 1000 points".into())); + } + (json!({"strokeWidth": n}), num(n)) + } }) } @@ -1021,10 +1147,11 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { 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))?; + let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1), Some(&st.doc))?; // 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)); + // An empty range changes nothing, also one inside a character that `ba..bb` widens to it. + let unchanged = s == e || 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, @@ -1042,7 +1169,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { 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)?; + edit_text(h, r.item, "text.setRangeStyle", &p)?; } Ok(()) })?; @@ -1054,7 +1181,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { o.insert("start".into(), json!(ba)); o.insert("end".into(), json!(bb)); } - let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?; + let answer = edit_text(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)?; @@ -1216,7 +1343,7 @@ fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { o.insert("start".into(), json!(ba)); o.insert("end".into(), json!(bb)); } - edit_item(h, r.item, id, &p)?; + edit_text(h, r.item, id, &p)?; Ok(Data::Undefined) } @@ -1250,32 +1377,46 @@ fn frame_ids(h: &Host, st: &DocState) -> std::result::Result>, Ho Ok(ids) } +/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists. +fn frames_scope(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { + super::layers::text_scope(h, arg(a, 0)) +} + fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { - doc_of(h, arg(a, 0), "TextFrames") + Ok(frames_scope(h, a)?.0) +} + +/// The type objects a `TextFrames` of `container` lists: the document's ([`frame_ids`]), or those +/// directly in a layer or group, topmost first. +fn listed(h: &Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { + match container { + None => frame_ids(h, st), + Some(c) => super::layers::text_list(h, st, c), + } } 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).map(|ids| ids.len()))? as u64))) + let (doc, c) = frames_scope(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| listed(h, st, c).map(|l| l.len()))? as u64))) } fn frames_parent(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; - Ok(doc_ref(h, doc.uid)) + let (doc, c) = frames_scope(h, a)?; + Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) } fn frames_at(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, c) = frames_scope(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) }; - with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(listed(h, st, c)?.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 (doc, c) = frames_scope(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)?; + let ids = listed(h, st, c)?; 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())) @@ -1303,29 +1444,40 @@ fn vertical_of(d: &Data) -> std::result::Result { } } -/// 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 { +/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`, on +/// top of the contents of `container` when there is one. +fn point_text(h: &Host, (doc, container): (Doc, Option), 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})))?; + let mut params = json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical}); + if let Some(c) = container { + check_open(h, doc, c)?; + if let Some(o) = params.as_object_mut() { + o.insert("parent".into(), json!(c.0)); + } + } + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", ¶ms))?; new_ref(h, doc, result_id(&r)) } +/// The error for a layer or group that takes no new type. +const SHUT_CONTAINER: &str = "the layer or group is hidden or locked"; + /// `add()`: empty point type at the origin. fn frames_add(h: &Host, a: &[Data]) -> Answer { - point_text(h, frames_doc(h, a)?, None, false) + point_text(h, frames_scope(h, a)?, None, false) } /// `pointText(anchor, orientation?)`. fn frames_point_text(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let scope = frames_scope(h, a)?; let anchor = point(arg(a, 1), "anchor")?; - point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?) + point_text(h, scope, Some(anchor), vertical_of(arg(a, 2))?) } -/// Turns the path `d` names into area type or type on a path with `text.createInPath`. +/// Turns the path `d` names into area type or type on a path with `text.createInPath`, and moves +/// it on top of the contents of the collection's layer or group when there is one. fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, container) = frames_scope(h, a)?; if handle_of(arg(a, 1), "PathItem").is_none() { return Err(HostError::Type("textPath must be a PathItem".into())); } @@ -1336,6 +1488,7 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { return Err(HostError::Error("TextFrames: path positions are not available yet".into())); } + refuse_protected(h, path, "PathItem")?; 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))?; @@ -1344,12 +1497,35 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { } 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)?; + // Makes the type, threaded after or before the base frame when there is one. + let make = |h: &Host| -> std::result::Result, HostError> { + 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)?; + } + Ok(id) + }; + let Some(c) = container else { + return new_ref(h, doc, make(h)?); + }; + check_open(h, doc, c)?; + // The path is moved as well as converted, so it must be one that `move` takes. + if !with_doc(h, doc, |_, st| editable(&st.doc, path.id)) { + return Err(HostError::Error(format!("Cannot move PathItem {}: it is hidden or locked", path.id.0))); } - new_ref(h, doc, id) + super::refuse_protected_edit(h, path)?; + let id = super::atomically(h, |h| { + let id = make(h)?.ok_or_else(|| HostError::Error("the command made no object".into()))?; + super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?; + Ok(id) + })?; + new_ref(h, doc, Some(id)) +} + +/// Refuses a hidden or locked layer or group as the place for new type. +fn check_open(h: &Host, doc: Doc, container: NodeId) -> std::result::Result<(), HostError> { + if with_doc(h, doc, |_, st| st.doc.is_editable(container)) { Ok(()) } else { Err(HostError::Error(SHUT_CONTAINER.into())) } } /// `areaText(textPath, orientation?, baseFrame?, postFix?)`. @@ -1362,17 +1538,22 @@ 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. +/// `removeAll()`: deletes every type object the collection lists 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 (doc, c) = frames_scope(h, a)?; + let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| { + let ids = listed(h, st, c)?; 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(); - Ok::<_, HostError>((ids, refused, on_locked)) + // Type that clips a group or layer releases its mask, so the object above it is not made + // the clipping path. + let released = super::masks_cleared_by(&st.doc, &ids); + // So would deleting the type above an image in an ordinary group named as a tracing. + let tracing = super::release_makes_tracing(&st.doc, &released, &ids) || super::removal_makes_tracing(&st.doc, &ids); + Ok::<_, HostError>((ids, refused, on_locked, released, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -1380,10 +1561,15 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { } 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))); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } + // A clip group named as a tracing, released with an image left first, would become one. + if tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + let params = json!({"ids": ids.iter().map(|i| i.0).collect::>()}); + super::atomically(h, |h| on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, ¶ms)))?; } Ok(Data::Undefined) } @@ -1557,6 +1743,7 @@ fn attr_type(attr: Attr) -> &'static str { match attr { Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", Attr::TextFont => "TextFont", + Attr::FillColor | Attr::StrokeColor => "Color", _ => "number", } } @@ -1738,8 +1925,8 @@ pub(super) fn classes(l: &Link) -> Vec { 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", "*")])), + ("parent", get(l, frames_parent), typed("*")), + ("index", method(l, frames_index), returns("TextFrame", &[("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")])), diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index 8317e1ae04..af3e9118ea 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -342,7 +342,8 @@ fn target_span(h: &Host, d: &Data) -> std::result::Result { span_of(h, d, &TEXT) } -/// `applyTo(textItem, clearingOverrides?)`. +/// `applyTo(textItem, clearingOverrides?)`. Throws `Cannot edit`, with nothing changed, when the +/// text frame is protected as for any other text edit. fn style_apply_to(h: &Host, a: &[Data]) -> Answer { let style = this_style(h, a)?; let target = target_span(h, arg(a, 1))?; @@ -355,6 +356,7 @@ fn style_apply_to(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("the text is in another document than the style".into())); } let (index, s, e, _) = resolve(h, target)?; + super::refuse_protected(h, target.item, "TextFrame")?; h.charge_call(16 + (e - s) as u64)?; let (start, end) = if style.para { let (_, ba, bb) = para_range(&index, s, e); @@ -429,6 +431,8 @@ fn char_value(h: &Host, attr: Attr, m: &Map) -> Data { Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")), None => Data::Undefined, }, + // A style's colors and stroke weight are not available yet (`char_members`). + Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight => Data::Undefined, } } @@ -467,7 +471,7 @@ fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { 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 (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0), None)?; 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 }; @@ -538,6 +542,9 @@ fn char_members(link: &Link) -> Vec { ATTRS .iter() .map(|&(name, attr)| { + if matches!(attr, Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight) { + return super::super::later(link, "CharacterAttributes", name); + } let data_type = match attr { Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", Attr::TextFont => "TextFont", diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs new file mode 100644 index 0000000000..22a1e36f1d --- /dev/null +++ b/crates/engine/src/script/dom/tracing.rs @@ -0,0 +1,970 @@ +//! Tracing in the script object model: `PlacedItem.trace()` and `RasterItem.trace()`, the +//! `PluginItem` an Image Trace object is, its `TracingObject` and its `TracingOptions`, as the help +//! pages , +//! and +//! describe them. +//! +//! An Image Trace object is a group that holds its source image, hidden, as its first object. +//! Tracing runs `imageTrace.make`, expanding `imageTrace.expand`, releasing `imageTrace.release` +//! and a change of view `imageTrace.setView`, so each joins the run's transaction and its work +//! counts against the run's limits. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `trace()` returns once the trace is made, so the counts can be read at once. It traces with +//! the Default preset. +//! - The traced image stays the same object: `sourceArt` gives it, and `releaseTracing()` gives it +//! back. `trace()` on an image that is the source of a tracing throws [`ALREADY_TRACED`], and on +//! a linked image whose file is missing throws `Linked image is missing`. +//! - `pathCount` counts the traced paths, without the seam fills an Abutting trace adds, +//! `anchorCount` their anchor points and `usedColorCount` the different paints they are filled +//! and stroked with, as the tracing is when they are read. `areaCount` throws. `imageResolution` +//! is the source image's pixels per inch as it is placed; an image placed at a different +//! resolution across and down has none. +//! - Assigning an option, or `loadFromPreset(name)`, traces again unless the options are already +//! so. Tracing again makes a new object: the `PluginItem`, its `TracingObject` and its +//! `TracingOptions` follow it. A tracing that another command traced again, expanded or +//! released, or whose source image was deleted, is stale. +//! - Tracing again throws [`ADDED_ARTWORK`], with nothing changed, when the tracing holds an object +//! its trace did not make, whether this run, an earlier run or a command added it, and +//! `releaseTracing()` throws [`ADDED_ARTWORK_RELEASE`] in the same case. The tracing records the +//! objects its trace made ([`crate::doc::TraceMade`]), and a copy of it records their copies. A +//! tracing saved without that record is checked only for objects added in this run. +//! - `palette` is `""` for the automatic palette, or `"Limited"`, `"Full Tone"` or +//! `"Document Library"`. `minArea` is the Noise setting in pixels: an area smaller than it is not +//! traced. `tracingMode` has no value for the Flat Logo mode. The options with no VectorCraft +//! setting throw [`not_implemented`]. +//! - `viewRaster` and `viewVector` take only the pairs of the Image Trace views +//! ([`VIEWS`]); the Split view has neither. +//! - `storeToPreset(name)` gives `false` for a built-in preset and `Custom`; a script cannot change +//! the saved presets, so any other name throws. A preset name has at most [`MAX_PRESET_NAME`] +//! bytes and none of `/`, `\`, `:` or control characters. + +use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, MemberInfo, host_ref, host_ref_parts}; + +use super::{ + Answer, Described, Host, Item, Link, STALE_ITEM, arg, boolean, class, command, command_value, edit_item, float, get, item_of, item_ref, method, + named, node_of, num, number, on_doc, property, returns, text, typed, typename_of, whole, with_doc, +}; +use crate::doc::{Node, TraceView}; +use crate::{NodeId, NodeKind}; + +/// The error of `trace()` on an image that is the source of a tracing. +pub const ALREADY_TRACED: &str = "The image is the source art of a tracing"; +/// The error of tracing again a tracing that holds an object its trace did not make. +pub const ADDED_ARTWORK: &str = "Cannot retrace a tracing containing added artwork"; +/// The error of releasing a tracing that holds an object its trace did not make. +pub const ADDED_ARTWORK_RELEASE: &str = "Cannot release a tracing containing added artwork"; +/// The error of options that trace with neither fills nor strokes. +pub const NEEDS_FILLS_OR_STROKES: &str = "TracingOptions requires fills or strokes"; +/// The error of `expandTracing(true)`. +pub const VIEWED_EXPAND: &str = "TracingObject.expandTracing(true) is not implemented"; +/// The longest preset name `loadFromPreset` and `storeToPreset` take, in bytes. +pub const MAX_PRESET_NAME: usize = 256; +/// The most times one run traces a tracing again through its options. +pub const MAX_RETRACES: usize = 10_000; +/// The largest `minArea`: the most pixels the tracer traces ([`vectorcraft_trace::MAX_PIXELS`]). +pub const MAX_MIN_AREA: u64 = vectorcraft_trace::MAX_PIXELS; + +/// The enumerations the members here give values of, as the help page +/// lists them. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("TracingModeType", &["TRACINGMODEBLACKANDWHITE", "TRACINGMODECOLOR", "TRACINGMODEGRAY"]), + ( + "ViewRasterType", + &["TRACINGVIEWRASTERADJUSTEDIMAGE", "TRACINGVIEWRASTERNOIMAGE", "TRACINGVIEWRASTERORIGINALIMAGE", "TRACINGVIEWRASTERTRANSPARENTIMAGE"], + ), + ( + "ViewVectorType", + &["TRACINGVIEWVECTORNOTRACINGRESULT", "TRACINGVIEWVECTOROUTLINES", "TRACINGVIEWVECTOROUTLINESWITHTRACING", "TRACINGVIEWVECTORTRACINGRESULT"], + ), +]; + +/// The classes this module defines. +pub(super) const CLASSES: &[&str] = &["PluginItem"]; + +/// Each Image Trace view with the `viewRaster` and `viewVector` that give it. +const VIEWS: &[(TraceView, &str, &str)] = &[ + (TraceView::Result, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"), + (TraceView::ResultWithOutlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINESWITHTRACING"), + (TraceView::Outlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"), + (TraceView::OutlinesWithSource, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"), + (TraceView::Source, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTORNOTRACINGRESULT"), +]; + +/// Each `tracingMode` with its Image Trace mode. +const MODES: &[(&str, &str)] = &[ + ("TracingModeType.TRACINGMODEBLACKANDWHITE", "blackAndWhite"), + ("TracingModeType.TRACINGMODEGRAY", "grayscale"), + ("TracingModeType.TRACINGMODECOLOR", "color"), +]; + +/// Each `palette` name with its Image Trace palette. +const PALETTES: &[(&str, &str)] = &[("", "automatic"), ("Limited", "limited"), ("Full Tone", "fullTone"), ("Document Library", "documentLibrary")]; + +/// The options with no VectorCraft setting. +const NOT_IMPLEMENTED: &[&str] = &[ + "cornerAngle", + "livePaintOutput", + "maxStrokeWeight", + "minStrokeLength", + "outputToSwatches", + "pathFitting", + "preprocessBlur", + "resample", + "resampleResolution", +]; + +/// What a run keeps for tracings: for each document uid and Image Trace object a script traced +/// again through its options, the id of the object that replaced it. +#[derive(Default)] +pub(super) struct State { + next: RefCell>, + /// `next` the other way round: for each replacing object, the object it replaced. + prev: RefCell>, + sources: RefCell>, + descendants: RefCell>>, + /// For each document uid, stores the last noted revert count ([`crate::DocState::reverts`]) + /// and the lowest id the run could allocate after the first note or the latest revert + /// ([`note_document`]). + marks: RefCell>, + retraces: Cell, +} + +/// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put +/// it back put back the same object), else the first object the document holds among those that +/// replaced it, one after the other, when this run traced it again (an Undo can put back one of +/// them), else the last of them, else `id`. +pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId { + let s = h.session.borrow(); + let doc = s.documents().iter().find(|d| d.uid == uid); + let held = |id: NodeId| doc.is_some_and(|d| d.doc.node(id).is_some()); + let next = h.dom.tracing.next.borrow(); + let mut id = id; + // Each object is replaced by one made later, so the steps end; the bound holds them anyway. + for _ in 0..=next.len() { + if held(id) { + return id; + } + match next.get(&(uid, id.0)) { + Some(n) => id = NodeId(*n), + None => return id, + } + } + id +} + +/// The first object of the run's chain of replacements that leads to `id` in the document `uid`, +/// so every handle to a tracing traced again names the same object; `id` when no earlier object +/// in the chain resolves to it. +pub(super) fn origin(h: &Host, uid: u64, id: NodeId) -> NodeId { + let first = { + let prev = h.dom.tracing.prev.borrow(); + let mut first = id; + // Each object replaces one made before it, so the steps end; the bound holds them anyway. + for _ in 0..prev.len() { + match prev.get(&(uid, first.0)) { + Some(old) => first = NodeId(*old), + None => break, + } + } + first + }; + if first != id && follow(h, uid, first) == id { first } else { id } +} + +/// Records that `new` replaced `old` in the document `uid`. +fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { + let mut prev = h.dom.tracing.prev.borrow_mut(); + // A second replacement of `old` takes the place of the first in both directions. + if let Some(earlier) = h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0) + && prev.get(&(uid, earlier)) == Some(&old.0) + { + prev.remove(&(uid, earlier)); + } + prev.insert((uid, new.0), old.0); +} + +pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) { + let mut first = true; + if let Some(source) = group.children().and_then(|c| c.first()) { + let mut sources = h.dom.tracing.sources.borrow_mut(); + first = !sources.contains_key(&(uid, group.id.0)); + sources.entry((uid, group.id.0)).or_insert(source.id); + } + // Only a tracing saved without the record of the objects its trace made needs the snapshot, + // taken the first time this run sees it. + if !first || group.trace_made().is_some() { + return; + } + h.dom.tracing.descendants.borrow_mut().entry((uid, group.id.0)).or_insert_with(|| { + let mut ids = HashSet::new(); + group.walk(&mut |n| { + if n.id != group.id { + ids.insert(n.id); + } + }); + ids + }); +} + +/// Before each command a script runs: notes the active document ([`note_document`]). +pub(super) fn before_command(h: &Host) { + let s = h.session.borrow(); + if let Some(st) = s.active() { + note_document(h, st); + } +} + +/// Records the next object id when the run first notes the document `st`. A revert resets +/// the mark to the reloaded document's next object id and keeps the descendant snapshots. +/// Loaded objects have ids below the mark; objects the run makes afterward have ids at or above it. +fn note_document(h: &Host, st: &crate::DocState) { + let mut marks = h.dom.tracing.marks.borrow_mut(); + match marks.get_mut(&st.uid) { + Some((reverts, _)) if *reverts == st.reverts => {} + Some((reverts, mark)) => { + *reverts = st.reverts; + *mark = st.doc.peek_next_id(); + } + None => { + marks.insert(st.uid, (st.reverts, st.doc.peek_next_id())); + } + } +} + +/// Returns the lowest id the run could allocate in document `uid` after its first note or latest +/// revert ([`note_document`]). +fn mark(h: &Host, uid: u64) -> Option { + h.dom.tracing.marks.borrow().get(&uid).map(|(_, mark)| *mark) +} + +pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool { + let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied(); + source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source)) +} + +/// The error of a member with no VectorCraft setting. +pub fn not_implemented(class: &str, name: &str) -> String { + format!("{class}.{name} is not implemented") +} + +fn out_of_range(name: &str, range: &str) -> HostError { + HostError::Range(format!("TracingOptions.{name} is out of range: {range}")) +} + +fn invalid(name: &str) -> HostError { + HostError::Error(format!("TracingOptions.{name} has an invalid value")) +} + +fn stale() -> HostError { + HostError::Error(STALE_ITEM.into()) +} + +fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> { + match d { + Data::Object(o) => o.iter().find(|(n, _)| n == k).map(|(_, v)| v), + _ => None, + } +} + +/// The first id of a command's result `key`: a number or a list of them, read exactly. +fn result_id(v: &Value, key: &str) -> Option { + match &v[key] { + Value::Array(a) => a.first().and_then(Value::as_u64).map(NodeId), + n => n.as_u64().map(NodeId), + } +} + +/// The Image Trace object, its document and the id its handle holds, of the `cls` (`TracingObject` +/// or `TracingOptions`) `d` names. It must still be an Image Trace object of its document. +fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 5]), HostError> { + let Some((c, handle)) = host_ref_parts(d).filter(|(c, _)| *c == cls) else { + return Err(HostError::Type(format!("this is not a {cls}"))); + }; + let &[run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) }; + let (doc, original) = node_of(h, &handle).ok_or_else(stale)?; + let id = follow(h, doc.uid, original); + let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|g| crate::cmd::is_trace_group(g) && same_source(h, doc.uid, original, g))); + if !live { + return Err(stale()); + } + Ok((Item { doc, id }, [run, uid, high, low, reverts])) +} + +/// The `PluginItem` `this` names, with the handle numbers its `tracing` keeps. +fn plugin_of(h: &Host, a: &[Data]) -> Result<(Item, [f64; 5]), HostError> { + match host_ref_parts(arg(a, 0)) { + Some(("PluginItem", handle)) => { + let item = item_of(h, arg(a, 0))?; + match handle.as_slice() { + &[run, uid, high, low, reverts] => Ok((item, [run, uid, high, low, reverts])), + _ => Err(HostError::Type("this is not a PluginItem".into())), + } + } + _ => Err(HostError::Type("this is not a PluginItem".into())), + } +} + +/// Reads the Image Trace object of `item` with `f`. +fn read_group(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) -> Result) -> Result { + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => f(st, n), + None => Err(stale()), + }) +} + +fn refuse_uneditable(h: &Host, item: Item) -> Result<(), HostError> { + let editable = with_doc(h, item.doc, |_, st| super::editable(&st.doc, item.id) && !super::on_locked_artboard(h, st, item.id)); + if !editable { + return Err(HostError::Error(format!("Cannot edit page item {}", item.id.0))); + } + Ok(()) +} + +/// Runs command `id` with `params` on `item`'s document → the object its result names under `key`. +/// The selection stays as it was, with that object in place of `item`. +fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result { + refuse_uneditable(h, item)?; + let mut before = with_doc(h, item.doc, |_, st| st.selection.clone()); + on_doc(h, item.doc.uid, false, |h| { + let (_, r) = command_value(h, id, params)?; + for w in r.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("{id}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + let new = result_id(&r, key).ok_or_else(|| HostError::Error(format!("{id} gave no object")))?; + let remap = |i: NodeId| if i == item.id { new } else { i }; + before.objects = before.objects.into_iter().map(remap).collect(); + let mut seen = HashSet::new(); + before.objects.retain(|i| seen.insert(*i)); + before.key = before.key.map(remap); + before.target = before.target.map(remap); + before.on_path_member = before.on_path_member.map(remap); + let restore = { + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + (st.selection != before).then(|| st.doc.clone()) + }; + if let Some(doc) = restore { + super::restore_selection(h, &doc, &before)?; + } + Ok(new) + }) +} + +/// Throws `refusal` when the Image Trace object of `item` holds an object its trace did not make, +/// and "Cannot edit page item" when it holds a locked object other than its source image, which +/// the replacement would discard. The objects looked at are charged to the run either way. +fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { + let (visited, result) = read_group(h, item, |st, group| { + note_document(h, st); + remember_source(h, item.doc.uid, group); + // A tracing with a record is checked against the objects its trace made. A tracing without + // a record is checked against its first descendant snapshot, which survives reverts. + // If the group id is below the document's mark, members at or above the mark are also added. + // A revert resets the mark to the reloaded document's next object id. + let made = group.trace_made(); + let descendants = h.dom.tracing.descendants.borrow(); + let ids = match made { + Some(_) => None, + None => descendants.get(&(item.doc.uid, item.id.0)), + }; + let newer = match made { + Some(_) => None, + None => mark(h, item.doc.uid).filter(|m| group.id.0 < *m), + }; + let source = group.children().and_then(|c| c.first()).map(|n| n.id); + let mut visited = 0u64; + let mut locked = None; + let mut todo: Vec<&Arc> = group.children().map(|c| c.iter().collect()).unwrap_or_default(); + while let Some(n) = todo.pop() { + visited += 1; + let added = match (&made, ids) { + (Some(m), _) => !m.contains(n.id), + (None, Some(ids)) => !ids.contains(&n.id), + (None, None) => false, + } || newer.is_some_and(|m| n.id.0 >= m); + // Added artwork is reported before a locked object, whichever comes first. + if added { + return Ok((visited, Err(HostError::Error(refusal.into())))); + } + if n.locked && Some(n.id) != source && locked.is_none() { + locked = Some(n.id); + } + todo.extend(n.children().into_iter().flatten()); + } + Ok((visited, locked.map_or(Ok(()), |id| Err(HostError::Error(format!("Cannot edit page item {}", id.0)))))) + })?; + h.charge_call(visited)?; + result +} + +/// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its +/// script objects follow the new one. +fn retrace(h: &Host, item: Item, mut params: Map) -> Result<(), HostError> { + if h.dom.tracing.retraces.get() >= MAX_RETRACES { + return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times"))); + } + refuse_added(h, item, ADDED_ARTWORK)?; + params.insert("id".into(), json!(item.id.0)); + // One savepoint covers the trace and the selection's restore, so a failed restore undoes the trace. + let new = super::atomically(h, |h| replace(h, item, "imageTrace.make", &Value::Object(params), "id"))?; + read_group(h, Item { id: new, ..item }, |_, group| { + remember_source(h, item.doc.uid, group); + Ok(()) + })?; + h.dom.tracing.retraces.set(h.dom.tracing.retraces.get() + 1); + replaced(h, item.doc.uid, item.id, new); + Ok(()) +} + +// ---- PlacedItem and RasterItem ---- + +/// `trace()`: `imageTrace.make` of the image with the Default preset → its `PluginItem`. +fn image_trace(h: &Host, a: &[Data], cls: &str) -> Answer { + let item = match host_ref_parts(arg(a, 0)) { + Some((c, _)) if c == cls => item_of(h, arg(a, 0))?, + _ => return Err(HostError::Type(format!("this is not a {cls}"))), + }; + let (source, linked) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let source = crate::cmd::is_trace_source(d, item.id); + let linked = matches!(d.node(item.id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some()); + (source, linked) + }); + if source { + return Err(HostError::Error(ALREADY_TRACED.into())); + } + if linked { + let info = on_doc(h, item.doc.uid, false, |h| command(h, "links.info", &json!({"id": item.id.0})))?; + if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") { + return Err(HostError::Error(super::images::MISSING_LINK.into())); + } + } + let id = replace(h, item, "imageTrace.make", &json!({"id": item.id.0}), "id")?; + Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) +} + +fn placed_trace(h: &Host, a: &[Data]) -> Answer { + image_trace(h, a, "PlacedItem") +} + +fn raster_trace(h: &Host, a: &[Data]) -> Answer { + image_trace(h, a, "RasterItem") +} + +// ---- PluginItem ---- + +fn plugin_is_tracing(h: &Host, a: &[Data]) -> Answer { + plugin_of(h, a)?; + Ok(Data::Bool(true)) +} + +fn plugin_tracing(h: &Host, a: &[Data]) -> Answer { + let (item, handle) = plugin_of(h, a)?; + let source = read_group(h, item, |_, g| g.children().and_then(|c| c.first()).map(|n| n.id).ok_or_else(stale))?; + let (_, original) = node_of(h, &handle).ok_or_else(stale)?; + h.dom.tracing.sources.borrow_mut().entry((item.doc.uid, original.0)).or_insert(source); + Ok(host_ref("TracingObject", &handle)) +} + +// ---- TracingObject ---- + +/// What a tracing's counts are made of. +#[derive(Default)] +struct Counts { + paths: u64, + anchors: u64, + colors: u64, + /// The objects looked at. + visited: u64, +} + +/// Which of a tracing's counts a read needs; the others are not worked out. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Metric { + Paths, + Anchors, + Colors, +} + +/// The anchor points of `n` and every path in it, adding each object looked at below `n` to +/// `visited`. +fn anchors_of(n: &Node, visited: &mut u64) -> u64 { + match &n.kind { + NodeKind::Path { path, .. } => path.anchor_count() as u64, + _ => n.children().map_or(0, |c| { + c.iter() + .map(|m| { + *visited += 1; + anchors_of(m, visited) + }) + .sum() + }), + } +} + +/// The traced paths of the Image Trace object `g`, their anchor points and paints: every path +/// and compound path in it but its source image, the seam fills and clipping paths. The seam fills +/// are a clip group directly in the tracing that [`crate::cmd::is_seam_fills`] accepts, or, for a +/// trace made before seam fills were clipped, the lowest item above the source image when it +/// accepts that. A group nested deeper, or an unclipped group higher up, is counted. An Image +/// Trace object inside `g` leaves out its own seam fills the same way. Only the count `metric` +/// names is worked out; a compound path counts as one path, and the paths inside it are looked at +/// (and counted in `visited`) only for its anchor points. +fn counts(g: &Node, metric: Metric) -> Counts { + let mut c = Counts::default(); + let mut paints = HashSet::new(); + let mut todo: Vec<&Arc> = g.children().map(|ch| ch.iter().skip(1).collect()).unwrap_or_default(); + let mut seams = seam_fills_of(g); + while let Some(n) = todo.pop() { + c.visited += 1; + if seams.contains(&n.id) { + continue; + } + if crate::cmd::is_trace_group(n) { + seams.extend(seam_fills_of(n)); + } + match &n.kind { + NodeKind::Path { clipping: true, .. } => {} + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + c.paths += 1; + match metric { + Metric::Paths => {} + Metric::Anchors => c.anchors += anchors_of(n, &mut c.visited), + Metric::Colors => { + for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] { + if paint != vectorcraft_color::Paint::None + && let Ok(key) = serde_json::to_string(&paint) + { + paints.insert(key); + } + } + } + } + } + _ => todo.extend(n.children().into_iter().flatten()), + } + } + c.colors = paints.len() as u64; + c +} + +/// The seam fills of the Image Trace object `g` ([`counts`]). +fn seam_fills_of(g: &Node) -> HashSet { + g.children() + .into_iter() + .flatten() + .skip(1) + .enumerate() + .filter(|(i, n)| (*i == 0 || matches!(n.kind, NodeKind::Group { clip: true, .. })) && crate::cmd::is_seam_fills(n)) + .map(|(_, n)| n.id) + .collect() +} + +/// Reads the counts of the tracing `this` names with `f`. +fn count(h: &Host, a: &[Data], metric: Metric) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + let c = read_group(h, item, |_, g| Ok(counts(g, metric)))?; + h.charge_call(c.visited)?; + Ok(num(float(match metric { + Metric::Paths => c.paths, + Metric::Anchors => c.anchors, + Metric::Colors => c.colors, + }))) +} + +fn tracing_paths(h: &Host, a: &[Data]) -> Answer { + count(h, a, Metric::Paths) +} + +fn tracing_anchors(h: &Host, a: &[Data]) -> Answer { + count(h, a, Metric::Anchors) +} + +fn tracing_colors(h: &Host, a: &[Data]) -> Answer { + count(h, a, Metric::Colors) +} + +fn tracing_areas(h: &Host, a: &[Data]) -> Answer { + tracing_of(h, arg(a, 0), "TracingObject")?; + Err(HostError::Error(not_implemented("TracingObject", "areaCount"))) +} + +/// `imageResolution`: the source image's pixels per inch, 72 over the size of a pixel in points. +fn tracing_resolution(h: &Host, a: &[Data]) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + read_group(h, item, |_, g| { + let source = g.children().and_then(|c| c.first()).ok_or_else(stale)?; + let NodeKind::Image(im) = &source.kind else { return Err(stale()) }; + let none = || HostError::Error("the source image has no single resolution".into()); + if source.is_distorted_image() { + return Err(none()); + } + let [xa, xb, ya, yb, ..] = im.xf.as_coeffs(); + let (across, down) = (xa.hypot(xb), ya.hypot(yb)); + if across <= 1e-12 || down <= 1e-12 || (across - down).abs() > 1e-9 * across.max(down) { + return Err(none()); + } + Ok(num(72.0 / across)) + }) +} + +fn tracing_parent(h: &Host, a: &[Data]) -> Answer { + let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?; + Ok(host_ref("PluginItem", &handle)) +} + +fn tracing_source(h: &Host, a: &[Data]) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + read_group(h, item, |st, g| g.children().and_then(|c| c.first()).map(|s| item_ref(h, st, s.id)).ok_or_else(stale)) +} + +fn tracing_options(h: &Host, a: &[Data]) -> Answer { + let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?; + Ok(host_ref("TracingOptions", &handle)) +} + +/// `expandTracing(viewed?)`: `imageTrace.expand` → the `GroupItem` that takes the tracing's place. +fn tracing_expand(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::Undefined | Data::Bool(false) => {} + Data::Bool(true) => { + tracing_of(h, arg(a, 0), "TracingObject")?; + return Err(HostError::Error(VIEWED_EXPAND.into())); + } + _ => return Err(HostError::Type("viewed must be true or false".into())), + } + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + let id = replace(h, item, "imageTrace.expand", &json!({"ids": [item.id.0]}), "ids")?; + Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) +} + +/// `releaseTracing()`: `imageTrace.release` → the source image, back in the tracing's place. A +/// tracing that holds an object its trace did not make throws [`ADDED_ARTWORK_RELEASE`], since the +/// release keeps only the source image. +fn tracing_release(h: &Host, a: &[Data]) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + refuse_added(h, item, ADDED_ARTWORK_RELEASE)?; + let id = replace(h, item, "imageTrace.release", &json!({"ids": [item.id.0]}), "ids")?; + Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) +} + +// ---- TracingOptions ---- + +/// The tracing `this` names, the settings it was traced with, its view and its preset's name. +fn options_of(h: &Host, a: &[Data]) -> Result<(Item, Map, TraceView, String), HostError> { + let (item, _) = tracing_of(h, arg(a, 0), "TracingOptions")?; + read_group(h, item, |_, g| { + let trace = g.extras().trace.as_deref(); + let params = trace.and_then(|t| t.get("params")).and_then(Value::as_object).cloned(); + let params = params.ok_or_else(|| HostError::Error("the tracing has no recorded options".into()))?; + let preset = trace.and_then(|t| t.get("preset")).and_then(Value::as_str).unwrap_or_default().to_string(); + Ok((item, params, g.trace_view(), preset)) + }) +} + +/// Reads the setting `key` of the tracing `this` names with `f`. +fn read_option(h: &Host, a: &[Data], key: &str, f: impl FnOnce(&Value) -> Answer) -> Answer { + let (_, params, ..) = options_of(h, a)?; + f(params.get(key).unwrap_or(&Value::Null)) +} + +/// Traces again with the setting `key` at `value`, unless it is at that value already. +fn write_option(h: &Host, a: &[Data], key: &str, value: Value) -> Answer { + let (item, mut params, ..) = options_of(h, a)?; + if params.get(key) == Some(&value) { + return Ok(Data::Undefined); + } + params.insert(key.into(), value); + let on = |k: &str| params.get(k).and_then(Value::as_bool) == Some(true); + if !on("fills") && !on("strokes") { + return Err(HostError::Error(NEEDS_FILLS_OR_STROKES.into())); + } + let mut p = Map::new(); + p.insert("params".into(), Value::Object(params)); + retrace(h, item, p)?; + Ok(Data::Undefined) +} + +/// A whole number from `lo` to `hi` for the option `name`. +fn whole_in(d: &Data, name: &str, lo: u64, hi: u64) -> Result { + let n = number(d, &format!("TracingOptions.{name}"))?; + if n.fract() != 0.0 || n < float(lo) || n > float(hi) { + return Err(out_of_range(name, &format!("a whole number from {lo} to {hi}"))); + } + whole(n).ok_or_else(|| out_of_range(name, &format!("a whole number from {lo} to {hi}"))) +} + +fn as_number(v: &Value) -> Answer { + v.as_f64().map(num).ok_or_else(|| HostError::Error("the tracing's options are damaged".into())) +} + +fn as_bool(v: &Value) -> Answer { + v.as_bool().map(Data::Bool).ok_or_else(|| HostError::Error("the tracing's options are damaged".into())) +} + +fn options_mode(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "mode", |v| { + let mode = v.as_str().unwrap_or_default(); + match MODES.iter().find(|(_, m)| *m == mode) { + Some((name, _)) => Ok(text(*name)), + None => Err(HostError::Error("TracingOptions.tracingMode has no value for this tracing's mode".into())), + } + }) +} + +fn options_set_mode(h: &Host, a: &[Data]) -> Answer { + let mode = match arg(a, 1) { + Data::String(s) => MODES.iter().find(|(n, _)| n == s).map(|(_, m)| *m), + _ => None, + }; + let mode = mode.ok_or_else(|| HostError::Type("TracingOptions.tracingMode must be a TracingModeType value".into()))?; + write_option(h, a, "mode", json!(mode)) +} + +fn options_threshold(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "threshold", as_number) +} + +fn options_set_threshold(h: &Host, a: &[Data]) -> Answer { + let v = whole_in(arg(a, 1), "threshold", 0, 255)?; + write_option(h, a, "threshold", json!(v)) +} + +fn options_max_colors(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "colors", as_number) +} + +fn options_set_max_colors(h: &Host, a: &[Data]) -> Answer { + let v = whole_in(arg(a, 1), "maxColors", 2, 256)?; + write_option(h, a, "colors", json!(v)) +} + +fn options_min_area(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "noise", as_number) +} + +fn options_set_min_area(h: &Host, a: &[Data]) -> Answer { + let v = whole_in(arg(a, 1), "minArea", 0, MAX_MIN_AREA)?; + write_option(h, a, "noise", json!(v)) +} + +fn options_fills(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "fills", as_bool) +} + +fn options_set_fills(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "TracingOptions.fills")?; + write_option(h, a, "fills", json!(v)) +} + +fn options_strokes(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "strokes", as_bool) +} + +fn options_set_strokes(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "TracingOptions.strokes")?; + write_option(h, a, "strokes", json!(v)) +} + +fn options_ignore_white(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "ignoreWhite", as_bool) +} + +fn options_set_ignore_white(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "TracingOptions.ignoreWhite")?; + write_option(h, a, "ignoreWhite", json!(v)) +} + +fn options_palette(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "palette", |v| { + let palette = v.as_str().unwrap_or_default(); + match PALETTES.iter().find(|(_, p)| *p == palette) { + Some((name, _)) => Ok(text(*name)), + None => Err(HostError::Error("the tracing's options are damaged".into())), + } + }) +} + +fn options_set_palette(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("TracingOptions.palette must be a string".into())) }; + let palette = PALETTES.iter().find(|(n, _)| n == name).map(|(_, p)| *p).ok_or_else(|| invalid("palette"))?; + write_option(h, a, "palette", json!(palette)) +} + +/// The view's `viewRaster` (`raster`) or `viewVector`. +fn view_part(view: TraceView, raster: bool) -> Answer { + let name = if raster { "viewRaster" } else { "viewVector" }; + VIEWS + .iter() + .find(|(v, ..)| *v == view) + .map(|(_, r, v)| text(if raster { *r } else { *v })) + .ok_or_else(|| HostError::Error(format!("TracingOptions.{name} has no value for the Split view"))) +} + +fn options_view(h: &Host, a: &[Data], raster: bool) -> Answer { + let (_, _, view, _) = options_of(h, a)?; + view_part(view, raster) +} + +/// Shows the view `viewRaster` (`raster`) or `viewVector` makes with the other one as it is. +fn options_set_view(h: &Host, a: &[Data], raster: bool) -> Answer { + let (name, kind) = if raster { ("viewRaster", "ViewRasterType") } else { ("viewVector", "ViewVectorType") }; + let given = match arg(a, 1) { + Data::String(s) if ENUMS.iter().any(|(e, members)| *e == kind && members.iter().any(|m| *s == format!("{kind}.{m}"))) => s.clone(), + _ => return Err(HostError::Type(format!("TracingOptions.{name} must be a {kind} value"))), + }; + let (item, _, view, _) = options_of(h, a)?; + let Data::String(other) = view_part(view, !raster)? else { return Err(invalid(name)) }; + let pair = |r: &str, v: &str| if raster { given == r && other == v } else { other == r && given == v }; + let (to, ..) = VIEWS.iter().find(|(_, r, v)| pair(r, v)).ok_or_else(|| invalid(name))?; + if *to != view { + refuse_uneditable(h, item)?; + edit_item(h, item, "imageTrace.setView", &json!({"ids": [item.id.0], "view": to.id()}))?; + } + Ok(Data::Undefined) +} + +fn options_view_raster(h: &Host, a: &[Data]) -> Answer { + options_view(h, a, true) +} + +fn options_set_view_raster(h: &Host, a: &[Data]) -> Answer { + options_set_view(h, a, true) +} + +fn options_view_vector(h: &Host, a: &[Data]) -> Answer { + options_view(h, a, false) +} + +fn options_set_view_vector(h: &Host, a: &[Data]) -> Answer { + options_set_view(h, a, false) +} + +fn options_preset(h: &Host, a: &[Data]) -> Answer { + let (_, _, _, preset) = options_of(h, a)?; + Ok(text(preset)) +} + +fn options_parent(h: &Host, a: &[Data]) -> Answer { + let (_, handle) = tracing_of(h, arg(a, 0), "TracingOptions")?; + Ok(host_ref("TracingObject", &handle)) +} + +/// A preset name given to `method`: a string of at most [`MAX_PRESET_NAME`] bytes without `/`, +/// `\`, `:` or control characters, trimmed. +fn preset_name<'a>(d: &'a Data, method: &str) -> Result<&'a str, HostError> { + let Data::String(name) = d else { return Err(HostError::Type(format!("TracingOptions.{method} needs a preset name, as a string"))) }; + if name.len() > MAX_PRESET_NAME { + return Err(HostError::Range(format!("TracingOptions.{method}: a preset name has at most {MAX_PRESET_NAME} bytes"))); + } + if name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control()) { + return Err(HostError::Error(format!("TracingOptions.{method}: a preset name cannot hold / \\ : or control characters"))); + } + let name = name.trim(); + if name.is_empty() { + return Err(HostError::Error(format!("TracingOptions.{method}: the preset name is empty"))); + } + Ok(name) +} + +/// `loadFromPreset(name)`: traces again with the built-in or saved preset `name` → `true`. +fn options_load(h: &Host, a: &[Data]) -> Answer { + let name = preset_name(arg(a, 1), "loadFromPreset")?; + let (item, params, _, preset) = options_of(h, a)?; + let wanted = vectorcraft_trace::preset(name).or_else(|| h.session.borrow().trace_preset(name).map(|q| q.params.clone())); + let wanted = wanted.ok_or_else(|| HostError::Error("TracingOptions.loadFromPreset: no built-in or saved preset has that name".into()))?; + let same = serde_json::to_value(&wanted).ok().as_ref().and_then(Value::as_object) == Some(¶ms); + if !(same && preset.eq_ignore_ascii_case(name)) { + let mut p = Map::new(); + p.insert("preset".into(), json!(name)); + retrace(h, item, p)?; + } + Ok(Data::Bool(true)) +} + +/// `storeToPreset(name)`: `false` for a built-in preset or `Custom`; any other name runs +/// `imageTrace.presets.save`, which a script cannot run. +fn options_store(h: &Host, a: &[Data]) -> Answer { + let name = preset_name(arg(a, 1), "storeToPreset")?; + let (_, params, ..) = options_of(h, a)?; + if vectorcraft_trace::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") { + return Ok(Data::Bool(false)); + } + command(h, "imageTrace.presets.save", &json!({"name": name, "params": params}))?; + Ok(Data::Bool(true)) +} + +/// A member of `TracingOptions` with no VectorCraft setting: reading and assigning it both throw, +/// after the check that the tracing `this` names is still there, and `reflect` and +/// `hasOwnProperty` leave it out. +fn missing(link: &Link, name: &'static str) -> Described { + let message = not_implemented("TracingOptions", name); + let l = link.clone(); + let f: vectorcraft_js::HostFunction = std::rc::Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16)?; + tracing_of(&h, arg(&a, 0), "TracingOptions")?; + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() }) +} + +/// Adds `trace()` to the `PlacedItem` and `RasterItem` classes in `classes`. +pub(super) fn add_trace(classes: &mut [HostClass], l: &Link) { + for c in classes.iter_mut() { + let f: super::Member = match c.name.as_str() { + "PlacedItem" => placed_trace, + "RasterItem" => raster_trace, + _ => continue, + }; + c.members.push(("trace".into(), method(l, f))); + c.info.push(("trace".into(), returns("PluginItem", &[]))); + } +} + +/// `PluginItem`, after `PageItem`, `TracingObject` and `TracingOptions`. +pub(super) fn classes(l: &Link) -> Vec { + let plugin = named(vec![("isTracing", get(l, plugin_is_tracing), typed("boolean")), ("tracing", get(l, plugin_tracing), typed("TracingObject"))]); + let tracing = named(vec![ + ("typename", typename_of("TracingObject"), typed("string")), + ("anchorCount", get(l, tracing_anchors), typed("number")), + ("areaCount", HostMember::Unavailable(super::function(l, tracing_areas)), MemberInfo { unavailable: true, ..MemberInfo::default() }), + ("imageResolution", get(l, tracing_resolution), typed("number")), + ("parent", get(l, tracing_parent), typed("PluginItem")), + ("pathCount", get(l, tracing_paths), typed("number")), + ("sourceArt", get(l, tracing_source), typed("PageItem")), + ("tracingOptions", get(l, tracing_options), typed("TracingOptions")), + ("usedColorCount", get(l, tracing_colors), typed("number")), + ("expandTracing", method(l, tracing_expand), returns("GroupItem", &[("viewed", "boolean")])), + ("releaseTracing", method(l, tracing_release), returns("PageItem", &[])), + ]); + let mut options = named(vec![ + ("typename", typename_of("TracingOptions"), typed("string")), + ("parent", get(l, options_parent), typed("TracingObject")), + ("preset", get(l, options_preset), typed("string")), + ("tracingMode", property(l, options_mode, options_set_mode), typed("TracingModeType")), + ("threshold", property(l, options_threshold, options_set_threshold), MemberInfo { min: Some(0.0), max: Some(255.0), ..typed("number") }), + ("fills", property(l, options_fills, options_set_fills), typed("boolean")), + ("strokes", property(l, options_strokes, options_set_strokes), typed("boolean")), + ("maxColors", property(l, options_max_colors, options_set_max_colors), MemberInfo { min: Some(2.0), max: Some(256.0), ..typed("number") }), + ("palette", property(l, options_palette, options_set_palette), typed("string")), + ("ignoreWhite", property(l, options_ignore_white, options_set_ignore_white), typed("boolean")), + ("minArea", property(l, options_min_area, options_set_min_area), typed("number")), + ("viewRaster", property(l, options_view_raster, options_set_view_raster), typed("ViewRasterType")), + ("viewVector", property(l, options_view_vector, options_set_view_vector), typed("ViewVectorType")), + ("loadFromPreset", method(l, options_load), returns("boolean", &[("presetName", "string")])), + ("storeToPreset", method(l, options_store), returns("boolean", &[("presetName", "string")])), + ]); + options.extend(NOT_IMPLEMENTED.iter().map(|m| missing(l, m))); + vec![ + class("PluginItem", Some("PageItem"), plugin, None), + class("TracingObject", None, tracing, None), + class("TracingOptions", None, options, None), + ] +} diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs new file mode 100644 index 0000000000..3bf88a577c --- /dev/null +++ b/crates/engine/src/script/dom/transform.rs @@ -0,0 +1,376 @@ +//! The transform methods of a page item, `translate`, `rotate`, `resize` and `transform`, as the +//! help page describes them. Each one +//! runs `object.transform` on the object, with its selection kept, so it joins the run's one undo +//! step for the document; a call that changes nothing runs no command. `PathItem` uses these +//! methods too. +//! +//! VectorCraft's own rules, which the help page does not state: +//! - Offsets, angles and matrices are taken with Y up, as `Matrix` records are, whatever +//! `app.coordinateSystem` is: `translate(0, 10)` moves the object up, and a positive angle turns +//! it counterclockwise. +//! - `rotate`, `resize` and `transform` act about the center of the object's geometric bounds, +//! unless a `Transformation` value names another point of those bounds; `DOCUMENTORIGIN` is the +//! bottom-left corner of the first artboard. A matrix's own translation is added after it acts +//! about that point. The value is checked even when the call changes nothing. +//! - Positions, pattern fills and pattern strokes, and gradients each follow their argument: +//! positions and gradients default to `true`, and patterns to the Transform Pattern Tiles +//! preference. Fill and stroke patterns transform together, and gradients with the object, so a +//! call whose values differ, counting the defaults of the arguments it leaves out, throws an error +//! that says so. +//! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own +//! scale in percent, the square root of the area it scales by (stroke weights and effects scale +//! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to +//! 100000, which sets the stroke weight to that percent of what it was, at most 1000 points. +//! When strokes and effects scale on a path, the scale and every stroke layer's resulting weight +//! must stay finite, and each weight can reach at most 1000 points. Any other value, and a scale +//! of strokes and effects with positions left as they are, throws an error that says so. +//! - A path without points takes any transformation about any point named. `DOCUMENTORIGIN` +//! still uses the first artboard's bottom-left corner; other named points use the origin. +//! Its linked opacity mask, strokes, effects and patterns transform with the same options. +//! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a +//! locked object, an object on a locked artboard and a guide while guides are locked are refused +//! with nothing changed, and so are +//! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object +//! past the canvas. + +use serde_json::json; +use vectorcraft_geom::{Affine, Point, Rect}; +use vectorcraft_js::{Data, HostError}; + +use super::matrix::{self, Matrix}; +use super::{Answer, Coords, Host, Item, arg, atomically, coordinate, edit_item, frame, number, paths, this_item, with_doc}; + +/// The error for an object on a locked artboard. +pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"; + +/// The error for a locked object. +pub(super) const LOCKED: &str = "cannot transform locked objects"; + +/// The error for a guide while guides are locked. +const GUIDES_LOCKED: &str = "cannot transform a guide while guides are locked"; + +/// The error for a hidden object. +pub(super) const HIDDEN: &str = "cannot transform hidden objects"; + +/// The identity matrix. +const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + +/// What a transform method changes besides the object's geometry. +struct Options { + /// Positions and orientations (`changePositions`, `transformObjects`). + objects: bool, + /// Pattern fills and strokes. + patterns: bool, + /// Stroke weights and effects (`changeLineWidths`). + strokes: bool, +} + +/// An optional `true` or `false` argument. +fn flag(d: &Data, what: &str) -> std::result::Result, HostError> { + match d { + Data::Undefined => Ok(None), + Data::Bool(b) => Ok(Some(*b)), + _ => Err(HostError::Type(format!("{what} must be true or false"))), + } +} + +/// The positions, fill patterns, fill gradients and stroke patterns arguments at `at` and after, +/// with the names the method gives them. +fn options(h: &Host, a: &[Data], at: usize, names: [&str; 4]) -> std::result::Result { + let tiles = h.session.borrow().prefs.transform_pattern_tiles; + let objects = flag(arg(a, at), names[0])?.unwrap_or(true); + let fill = flag(arg(a, at + 1), names[1])?.unwrap_or(tiles); + let gradients = flag(arg(a, at + 2), names[2])?.unwrap_or(true); + let stroke = flag(arg(a, at + 3), names[3])?.unwrap_or(tiles); + if fill != stroke { + return Err(HostError::Error(format!("{} and {} must be the same here", names[1], names[3]))); + } + if gradients != objects { + return Err(HostError::Error(format!("{} different from {} is not available yet", names[2], names[0]))); + } + Ok(Options { objects, patterns: fill, strokes: false }) +} + +/// Whether `changeLineWidths` (`d`) is the scale of the linear part `m` of a matrix, so stroke +/// weights and effects scale with it (`Some(true)`), or 100 (`Some(false)`); `None` for any other +/// number. +fn own_line_widths(d: &Data, m: Matrix) -> std::result::Result<(Option, f64, f64), HostError> { + let lw = match d { + Data::Undefined => return Ok((Some(false), 100.0, 100.0)), + d => number(d, "changeLineWidths")?, + }; + if lw < 0.0 { + return Err(HostError::Range("changeLineWidths must not be negative".into())); + } + // The determinant is taken past the range of a number, so a scale whose square is too large + // for one still has its own value. + // 100 keeps the stroke weights, even for a scale within the tolerance of it. + let own = matrix::area_scale(m) * 100.0; + if (lw - 100.0).abs() <= 1e-9 { + return Ok((Some(false), lw, own)); + } + if lw > 0.0 && own.is_finite() && (lw - own).abs() <= 1e-9 * own { + return Ok((Some((own - 100.0).abs() > 1e-9), lw, own)); + } + Ok((None, lw, own)) +} + +/// The error for a `changeLineWidths` the method does not take. +fn other_line_widths(own: f64) -> HostError { + HostError::Error(format!("changeLineWidths other than 100 or the scale itself ({own}) is not available yet")) +} + +/// Whether `changeLineWidths` (`d`) scales stroke weights for the linear part `m` of a matrix. +fn line_widths(d: &Data, m: Matrix) -> std::result::Result { + match own_line_widths(d, m)? { + (Some(strokes), _, _) => Ok(strokes), + (None, _, own) => Err(other_line_widths(own)), + } +} + +/// The member of `Transformation` that `d` names (left out: `CENTER`). +fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> { + const MEMBERS: [&str; 10] = ["CENTER", "TOPLEFT", "TOP", "TOPRIGHT", "LEFT", "RIGHT", "BOTTOMLEFT", "BOTTOM", "BOTTOMRIGHT", "DOCUMENTORIGIN"]; + let name = match d { + Data::Undefined => "CENTER", + Data::String(s) => s.strip_prefix("Transformation.").unwrap_or(""), + _ => "", + }; + if MEMBERS.contains(&name) { Ok(name) } else { Err(HostError::Type("the point to transform about must be a Transformation value".into())) } +} + +/// The point of `r` (document coordinates, Y down) that the `Transformation` member `name` +/// ([`anchor_name`]) names. Without bounds, a path uses the origin except for `DOCUMENTORIGIN`. +fn anchor(h: &Host, item: Item, r: Option, name: &str) -> std::result::Result { + if r.is_none() && !paths::is_path(h, item) { + return Err(HostError::Error("the object has no bounds".into())); + } + if name == "DOCUMENTORIGIN" { + return with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0]))); + } + let Some(r) = r else { + return Ok(Point::ORIGIN); + }; + let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); + Ok(match name { + "TOPLEFT" => Point::new(r.x0, r.y0), + "TOP" => Point::new(cx, r.y0), + "TOPRIGHT" => Point::new(r.x1, r.y0), + "LEFT" => Point::new(r.x0, cy), + "RIGHT" => Point::new(r.x1, cy), + "BOTTOMLEFT" => Point::new(r.x0, r.y1), + "BOTTOM" => Point::new(cx, r.y1), + "BOTTOMRIGHT" => Point::new(r.x1, r.y1), + _ => Point::new(cx, cy), + }) +} + +/// The matrix `m` (Y up) as it acts on the page (Y down), about `o`. +fn on_page(m: Matrix, o: Point) -> Affine { + let [a, b, c, d, tx, ty] = m; + let (b, c, ty) = (0.0 - b, 0.0 - c, 0.0 - ty); + if [a, b, c, d] == [1.0, 0.0, 0.0, 1.0] { + return Affine::translate((tx, ty)); + } + Affine::translate((o.x + tx, o.y + ty)) * Affine::new([a, b, c, d, 0.0, 0.0]) * Affine::translate((-o.x, -o.y)) +} + +/// Whether the object `id` of `d` stays within the canvas under `xf` (page coordinates), symbol +/// instances measured by their art as [`vectorcraft_doc::Document::bounds_of`] measures them. The +/// object is measured whole, and a group is looked into object by object, as the native file's +/// canvas check does (`vectorcraft_doc::canvas_range`), since a clipping group's bounds are its +/// clipping path's and leave out the art it clips. +fn fits(d: &vectorcraft_doc::Document, id: vectorcraft_doc::NodeId, xf: Affine) -> bool { + fn within(n: &vectorcraft_doc::Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool { + if matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. } | vectorcraft_doc::NodeKind::Layer { .. }) { + n.children().into_iter().flatten().all(|c| within(c, symbols)) + } else { + n.geometric_bounds_with(symbols).is_none_or(crate::sanity::rect_in_range) + } + } + d.node(id).is_some_and(|n| { + let mut n = n.clone(); + n.transform(xf, false); + within(&n, &d.symbol_boxes()) + }) +} + +/// Applies `m` (Y up) to `item`, about the point `about` names (`None`: the matrix acts as a move, +/// which needs no point), with `opts`, then sets the stroke weight of a path to `weight` points +/// when it is given. +fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, weight: Option) -> Answer { + let about = about.map(anchor_name).transpose()?; + if m.iter().any(|v| !v.is_finite()) { + return Err(HostError::Range("the transformation has a value too large for a number".into())); + } + if matrix::singular(m) { + return Err(HostError::Error("the transformation is singular and would flatten the object".into())); + } + let (locked, hidden, on_locked, bounds, uses_pattern, clipped) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let line = d.ancestry(item.id); + let mut locked = line.as_ref().is_none_or(|a| a.iter().any(|i| d.node(*i).is_none_or(|n| n.locked))); + let hidden = line.as_ref().is_none_or(|a| a.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(|n| !n.visible))); + let (mut uses, mut clipped) = (false, false); + if let Some(n) = d.node(item.id) { + n.walk(&mut |c| { + locked |= c.locked; + uses |= vectorcraft_doc::pattern::uses_pattern(c, None); + clipped |= + matches!(c.kind, vectorcraft_doc::NodeKind::Group { clip: true, .. } | vectorcraft_doc::NodeKind::Layer { clip: true, .. }); + }); + } + (locked, hidden, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses, clipped) + }); + if locked { + return Err(HostError::Error(format!("{LOCKED}: {}", item.id.0))); + } + if hidden { + return Err(HostError::Error(format!("{HIDDEN}: {}", item.id.0))); + } + if on_locked { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); + } + if h.session.borrow().menu.guides_locked && with_doc(h, item.doc, |_, st| crate::is_guide_path(&st.doc, item.id)) { + return Err(HostError::Error(format!("{GUIDES_LOCKED}: {}", item.id.0))); + } + // The identity acts the same about every point for any object. + let o = match (about, bounds) { + _ if m == IDENTITY => Point::ORIGIN, + (Some(name), r) => anchor(h, item, r, name)?, + (None, _) => Point::ORIGIN, + }; + let xf = on_page(m, o); + if opts.strokes && !opts.objects { + return Err(HostError::Error("changeLineWidths other than 100 with changePositions false is not available yet".into())); + } + if opts.objects && xf != Affine::IDENTITY { + // The transformed corners of the bounds hold the transformed object. When one of them is + // past the canvas, or the object holds a clipping group (whose bounds leave out the art + // it clips), the transformed object itself is measured. + let inside = |p: Point| p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD; + let outside = bounds.is_some_and(|r| { + 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)]; + !corners.iter().all(|p| inside(xf * *p)) + }); + if (clipped || outside) && !with_doc(h, item.doc, |_, st| fits(&st.doc, item.id, xf)) { + return Err(HostError::Range("the transformation would take the object past the canvas".into())); + } + } + let c = xf.as_coeffs(); + let identity = xf == Affine::IDENTITY; + // Every stroke layer's weight is checked with the factor `object.transform` applies. + let factor = if opts.strokes { vectorcraft_doc::Scaling::factor(xf) } else { None }; + if let Some(k) = factor + && paths::is_path(h, item) + && (!k.is_finite() || { + let width = paths::largest_stroke_weight(h, item)? * k; + !width.is_finite() || width > paths::MAX_STROKE_WIDTH + }) + { + return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); + } + let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; + // The transformation and the stroke weight change together or not at all. + atomically(h, |h| { + if changes { + let p = json!({"ids": [item.id.0], "matrix": c, "objects": opts.objects, "patterns": opts.patterns, "strokes": opts.strokes}); + edit_item(h, item, "object.transform", &p)?; + } + if let Some(w) = weight { + paths::set_stroke_weight(h, item, w)?; + } + Ok(Data::Undefined) + }) +} + +/// `translate(deltaX?, deltaY?, transformObjects?, transformFillPatterns?, transformFillGradients?, +/// transformStrokePatterns?)`: moves the object by `deltaX` and `deltaY` points (0 when left out). +pub(super) fn translate(h: &Host, a: &[Data]) -> Answer { + let delta = |i: usize, what: &str| match arg(a, i) { + Data::Undefined => Ok(0.0), + d => number(d, what), + }; + let (dx, dy) = (delta(1, "deltaX")?, delta(2, "deltaY")?); + let names = ["transformObjects", "transformFillPatterns", "transformFillGradients", "transformStrokePatterns"]; + let opts = options(h, a, 3, names)?; + let item = this_item(h, a)?; + // An offset past the canvas is refused only when the call moves the object or a pattern it + // uses. + let limit = coordinate(&Data::Number(dx), "deltaX").and_then(|_| coordinate(&Data::Number(dy), "deltaY")); + if let Err(e) = limit { + let moves = opts.objects + || opts.patterns + && with_doc(h, item.doc, |_, st| { + st.doc.node(item.id).is_some_and(|n| { + let mut uses = false; + n.walk(&mut |c| uses |= vectorcraft_doc::pattern::uses_pattern(c, None)); + uses + }) + }); + if moves { + return Err(e); + } + } + apply(h, item, matrix::translate(dx, dy), None, &opts, None) +} + +const CHANGE_NAMES: [&str; 4] = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"]; + +/// `rotate(angle, changePositions?, changeFillPatterns?, changeFillGradients?, changeStrokePattern?, +/// rotateAbout?)`: turns the object by `angle` degrees, counterclockwise when it is positive. +pub(super) fn rotate(h: &Host, a: &[Data]) -> Answer { + let angle = number(arg(a, 1), "angle")?; + let opts = options(h, a, 2, CHANGE_NAMES)?; + apply(h, this_item(h, a)?, matrix::rotate(angle), Some(arg(a, 6)), &opts, None) +} + +/// `resize(scaleX, scaleY, changePositions?, changeFillPatterns?, changeFillGradients?, +/// changeStrokePattern?, changeLineWidths?, scaleAbout?)`: scales the object by `scaleX` and +/// `scaleY` percent along the page's axes. +pub(super) fn resize(h: &Host, a: &[Data]) -> Answer { + let (sx, sy) = (number(arg(a, 1), "scaleX")?, number(arg(a, 2), "scaleY")?); + if sx == 0.0 || sy == 0.0 { + return Err(HostError::Range("scaleX and scaleY must not be 0".into())); + } + let m = matrix::scaled(sx, sy); + let mut opts = options(h, a, 3, CHANGE_NAMES)?; + let item = this_item(h, a)?; + let weight = match own_line_widths(arg(a, 7), m)? { + // The compound holds a member's visible stroke, so its weight is set through the compound + // as well as the member's own strokes and effects scaling, by the scale itself. + (Some(true), _, own) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => { + opts.strokes = true; + paths::resized_stroke_weight(h, item, own, false)? + } + (Some(strokes), _, _) => { + opts.strokes = strokes; + None + } + (None, lw, _) if paths::is_path(h, item) => paths::resized_stroke_weight(h, item, lw, true)?, + (None, _, own) => return Err(other_line_widths(own)), + }; + apply(h, item, m, Some(arg(a, 8)), &opts, weight) +} + +/// `transform(transformationMatrix, changePositions?, changeFillPatterns?, changeFillGradients?, +/// changeStrokePattern?, changeLineWidths?, transformAbout?)`: applies a `Matrix` record to the +/// object. +pub(super) fn transform(h: &Host, a: &[Data]) -> Answer { + let m = matrix::matrix(arg(a, 1), "transformationMatrix")?; + let mut opts = options(h, a, 2, CHANGE_NAMES)?; + let item = this_item(h, a)?; + let weight = match own_line_widths(arg(a, 6), m)? { + // As in `resize`: the compound holds a member's visible stroke, so its weight is set + // through the compound as well. + (Some(true), _, own) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => { + opts.strokes = true; + paths::resized_stroke_weight(h, item, own, false)? + } + _ => { + opts.strokes = line_widths(arg(a, 6), m)?; + None + } + }; + apply(h, item, m, Some(arg(a, 7)), &opts, weight) +} diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 85c01d6a74..11db9b859e 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -220,6 +220,9 @@ pub(crate) struct Setup { pub script: Option, /// The script's text with the files it includes, whose SHA-256 the grants it keeps are for. pub source: String, + /// The SHA-256 the grants are for in place of `source`'s: for the run of a ScriptUI palette's + /// handler, the one of the script that showed the palette. + pub own: Option, /// The folder that holds each script's data folder ([`crate::Session::attach_script_data`]). pub data_dir: Option, /// The code the run's named engine kept from its earlier runs: the SHA-256 of each source @@ -309,7 +312,7 @@ impl Disk { let start = scope.folder().map_or_else(|| home.clone(), |p| p.to_string_lossy().into_owned()); let web = cfg!(target_arch = "wasm32"); let script = setup.script.as_deref().filter(|_| !web).and_then(|p| std::fs::canonicalize(p).ok()); - let own = vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes()); + let own = setup.own.unwrap_or_else(|| vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes())); let script = script.map(|p| (p, own.clone())); let fenced = setup.data_dir.as_deref().filter(|_| !web).and_then(Path::parent).and_then(real_or_planned); let held = scope.roots().iter().map(|r| (r.clone(), false, true)).collect(); @@ -381,6 +384,11 @@ impl Disk { } } + /// The SHA-256 the run's grants are for ([`Setup::own`]). + pub(crate) fn own(&self) -> &str { + &self.own + } + /// Adds the source with SHA-256 `hash` to what the run's code may run. → whether it was new. fn saw(&mut self, hash: String) -> bool { if self.ran_too_much || self.ran.contains(&hash) || self.own == hash { diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 058d37f35b..aaf1070d93 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -238,9 +238,10 @@ pub(crate) struct Files { entry_key: Option, } -/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in -/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text -/// run as ECMAScript 5.1 with the ExtendScript extensions. +/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] and +/// [`vectorcraft_js::Options::es2017`] when its file name ends in `.js` or `.mjs` (in any letter +/// case); a `.jsx` script, any other file and a script given as text run as ECMAScript 5.1 with +/// the ExtendScript extensions. pub(crate) fn es2015_script(path: Option<&str>) -> bool { path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs")) } @@ -496,7 +497,7 @@ impl Files { /// The options a file of this run is parsed with, preprocessor lines aside. pub(crate) fn options(&self) -> Options { - Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() } + Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, es2017: self.es2015, e4x: true, ..Options::default() } } /// The `JSINCLUDE` folders of this process: absolute folders separated by `;`. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index cc1a6f5b3c..d5dbbc1bb8 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -48,6 +48,11 @@ //! 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. //! +//! A run in a named engine can show ScriptUI palettes ([`palettes`]), which stay open after it and +//! whose events run as runs of their own in that engine, one at a time once no run is going. A run +//! of that engine whose own code calls `update()` handles the waiting events inside the run +//! instead. A palette closes with its engine. +//! //! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run //! only after the run's changes are kept, for the frontend to send once the person approves them //! ([`printing`]). @@ -58,10 +63,12 @@ pub mod dialogs; pub mod dollar; pub mod dom; pub mod include; +pub mod palettes; pub mod printing; pub mod scriptui; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; +pub use palettes::{ScriptPalette, Waiting}; pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue}; use std::cell::{Cell, RefCell}; @@ -111,6 +118,9 @@ pub const MAX_LOG_LINES: usize = 10_000; pub const MAX_LOG_BYTES: usize = 4 << 20; /// The most bytes of `args` given to one run, as JSON. pub const MAX_ARGS_BYTES: usize = 1 << 20; +/// The shortest run time between two ScriptUI `update()` calls that each end the slice, so the app +/// draws the window (VectorCraft's own value, about one frame). +const UPDATE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(16); /// The `vc.run` calls one slice makes before the interface draws again. const SLICE_HOST_CALLS: u32 = 256; /// The bytes that may cross between a script and the host in one run. @@ -482,6 +492,7 @@ struct World { draw_mode: DrawMode, draw_inside: Option, clipboard: Clipboard, + clipboard_copied: bool, untitled_counter: u32, menu: cmd::menucmds::MenuState, last_solid: crate::Color, @@ -498,11 +509,13 @@ struct World { /// The choices outside the documents that a script's commands can change: the preferences, the /// global edit options, the Select Similar Objects attribute, the recent URLs, the chosen gradient stop, freeform point and appearance -/// item, the Eyedropper's sample, the envelope defaults and the Caps Lock state. +/// item, the Eyedropper's sample, the envelope defaults, the Caps Lock state and whether Overprint +/// Preview turns on when the run ends. #[derive(Clone)] struct Choices { prefs: crate::Prefs, caps_lock: bool, + overprint_after_run: bool, eyedropper_sample: Option>, global_edit_options: cmd::globaledit::Options, select_similar: &'static str, @@ -518,6 +531,7 @@ impl Choices { Self { prefs: s.prefs.clone(), caps_lock: s.caps_lock, + overprint_after_run: s.overprint_after_run, eyedropper_sample: s.eyedropper_sample.clone(), global_edit_options: s.global_edit_options.clone(), select_similar: s.select_similar, @@ -532,6 +546,7 @@ impl Choices { fn put(self, s: &mut Session) { s.prefs = self.prefs; s.caps_lock = self.caps_lock; + s.overprint_after_run = self.overprint_after_run; s.eyedropper_sample = self.eyedropper_sample; s.global_edit_options = self.global_edit_options; s.select_similar = self.select_similar; @@ -546,6 +561,7 @@ impl Choices { use std::mem::swap; swap(&mut self.prefs, &mut s.prefs); swap(&mut self.caps_lock, &mut s.caps_lock); + swap(&mut self.overprint_after_run, &mut s.overprint_after_run); swap(&mut self.eyedropper_sample, &mut s.eyedropper_sample); swap(&mut self.global_edit_options, &mut s.global_edit_options); swap(&mut self.select_similar, &mut s.select_similar); @@ -558,19 +574,35 @@ impl Choices { } /// The preferences after a run: `current`, the session's, which the app may have changed while the -/// run went on, with each preference the run changed from `start` set to the run's value. +/// run went on, with each preference the run changed from `start` set to the run's value. A +/// preference the run emptied, which is then left out of the saved form, is left out of the result. +/// The values scripts store with `app.preferences` are merged the same way one key at a time. fn merged_prefs(start: &crate::Prefs, run: &crate::Prefs, current: &crate::Prefs) -> crate::Prefs { - let (Ok(Value::Object(start)), Ok(Value::Object(run)), Ok(Value::Object(mut out))) = + const SCRIPT_KEYS: &str = "scriptPreferences"; + let (Ok(Value::Object(start_json)), Ok(Value::Object(run_json)), Ok(Value::Object(mut out))) = (serde_json::to_value(start), serde_json::to_value(run), serde_json::to_value(current)) else { return current.clone(); }; - for (key, value) in run { - if start.get(&key) != Some(&value) { + for key in start_json.keys().filter(|k| *k != SCRIPT_KEYS && !run_json.contains_key(*k)) { + out.remove(key); + } + for (key, value) in run_json { + if key != SCRIPT_KEYS && start_json.get(&key) != Some(&value) { out.insert(key, value); } } - serde_json::from_value(Value::Object(out)).unwrap_or_else(|_| current.clone()) + let mut merged: crate::Prefs = serde_json::from_value(Value::Object(out)).unwrap_or_else(|_| current.clone()); + let script = &mut merged.script_preferences; + for key in start.script_preferences.keys().filter(|k| !run.script_preferences.contains_key(*k)) { + script.remove(key); + } + for (key, value) in &run.script_preferences { + if start.script_preferences.get(key) != Some(value) { + script.insert(key.clone(), value.clone()); + } + } + merged } impl World { @@ -590,6 +622,7 @@ impl World { draw_mode: s.draw_mode, draw_inside: s.draw_inside, clipboard: s.clipboard.clone(), + clipboard_copied: s.clipboard_copied, untitled_counter: s.untitled_counter, menu: s.menu.clone(), last_solid: s.last_solid, @@ -613,6 +646,7 @@ impl World { swap(&mut self.draw_mode, &mut s.draw_mode); swap(&mut self.draw_inside, &mut s.draw_inside); swap(&mut self.clipboard, &mut s.clipboard); + swap(&mut self.clipboard_copied, &mut s.clipboard_copied); swap(&mut self.untitled_counter, &mut s.untitled_counter); swap(&mut self.menu, &mut s.menu); swap(&mut self.last_solid, &mut s.last_solid); @@ -624,9 +658,11 @@ impl World { } } -/// The commands that can change the clipboard and still fail, and that do not put it back -/// themselves. The clipboard can hold a great deal, so a savepoint copies it only for these. -const CAN_FAIL_AFTER_COPYING: &[&str] = &["action.batch", "edit.cut"]; +/// The commands that can change the clipboard and still fail, or still be put back because their +/// result cannot reach the script, and that do not put it back themselves. The clipboard can hold +/// a great deal, so a savepoint copies it only for these. +const CAN_FAIL_AFTER_COPYING: &[&str] = + &["action.batch", "artboard.copy", "artboard.cut", "clipboard.importSvg", "command.batch", "edit.copy", "edit.cut"]; /// The commands that remove a document's undo history, or the document: a savepoint keeps a whole /// copy of the histories for these. Any other command that removes or changes a step under the @@ -650,7 +686,8 @@ pub(crate) struct Savepoint { fill_active: bool, draw_mode: DrawMode, draw_inside: Option, - clipboard: Option, + /// The clipboard, [`Session::clipboard_copied`] and [`Session::copies`]. + clipboard: Option<(Clipboard, bool, u64)>, untitled_counter: u32, menu: cmd::menucmds::MenuState, last_solid: crate::Color, @@ -659,6 +696,8 @@ pub(crate) struct Savepoint { pending_paint: Option, choices: Choices, journal: usize, + /// The plug-in events queued before the command ([`Session::plugin_events_mark`]). + plugin_events: u64, } impl Savepoint { @@ -684,7 +723,7 @@ impl Savepoint { fill_active: s.fill_active, draw_mode: s.draw_mode, draw_inside: s.draw_inside, - clipboard: CAN_FAIL_AFTER_COPYING.contains(&id).then(|| s.clipboard.clone()), + clipboard: CAN_FAIL_AFTER_COPYING.contains(&id).then(|| (s.clipboard.clone(), s.clipboard_copied, s.copies)), untitled_counter: s.untitled_counter, menu: s.menu.clone(), last_solid: s.last_solid, @@ -693,6 +732,7 @@ impl Savepoint { pending_paint: s.pending_paint.clone(), choices: Choices::of(s), journal: s.journal.len(), + plugin_events: s.plugin_events_mark(), } } @@ -734,8 +774,10 @@ impl Savepoint { s.fill_active = self.fill_active; s.draw_mode = self.draw_mode; s.draw_inside = self.draw_inside; - if let Some(clipboard) = self.clipboard { + if let Some((clipboard, copied, copies)) = self.clipboard { s.clipboard = clipboard; + s.clipboard_copied = copied; + s.copies = copies; } s.untitled_counter = self.untitled_counter; s.menu = self.menu; @@ -745,6 +787,8 @@ impl Savepoint { s.pending_paint = self.pending_paint; self.choices.put(s); s.journal.truncate(self.journal); + // The documents the command opened are closed again: plug-ins are not told of them. + s.forget_plugin_opens_since(self.plugin_events); s.sync_front_profiles(); exact } @@ -771,6 +815,9 @@ struct Host { log: RefCell>, log_bytes: Cell, written: RefCell, + /// A command ran a Copy or Cut ([`Session::copies`]), also inside a batch or an action, and + /// the run kept it. + copied: Cell, /// The run's number in its session, and the script's name, which its console lines carry. run: u64, name: Arc, @@ -811,6 +858,8 @@ struct Host { started: Option, /// The time since [`Host::started`] at which a `$.sleep` ends. wake_at: Cell>, + /// The time since [`Host::started`] at which a ScriptUI `update()` last ended the slice. + drawn_at: Cell>, /// Set while a host function runs where the run can stop at the call ([`Realm::wait_flag`]). can_wait: Rc>, /// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one). @@ -819,10 +868,24 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, + /// The named engine the run is in; `None` for a new realm. + engine: Option, + /// The script file the run was read from; `None` for a script given as text. + file: Option, + /// For the run of a palette's handler, the palette's id and the event, until the palette takes + /// it ([`palettes`]). + palette_event: RefCell>, /// The run's state of the script object model (`app`). dom: dom::State, + /// While a slice runs: the documents the interface has open ([`World::docs`] of the run's + /// job), which a capture must not write over either. Empty between slices. + interface_docs: RefCell>, /// The actions `app.doScript` can play. actions: Vec, + /// While a palette's `update()` gives a waiting event to its palette, the actions of the run + /// that showed that palette, which `app.doScript` plays in place of [`Host::actions`]. A + /// palette's `paletteTake` sets them and its `palettePending` clears them. + palette_actions: RefCell>>, /// 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)>, @@ -1058,6 +1121,24 @@ impl Host { Ok(()) } + /// A palette's `update()` in the script's own code: in the app, ends the slice so the palette is + /// drawn as the script left it, at most once per [`UPDATE_INTERVAL`] of the run's time. → + /// whether it does, and the palette's controls are to be given now. Without a clock (the web + /// build), and in a run with nobody to draw for, the palette is drawn when the slice or the run + /// ends for another reason. + fn update_drawn(&self) -> bool { + if !self.framed { + return false; + } + let Some(now) = self.elapsed() else { return false }; + if self.drawn_at.get().is_some_and(|t| now.saturating_sub(t) < UPDATE_INTERVAL) { + return false; + } + self.drawn_at.set(Some(now)); + self.pause.set(true); + true + } + /// The time left of a `$.sleep`, or none when the run is not asleep. fn asleep(&self) -> Option { let wake = self.wake_at.get()?; @@ -1327,8 +1408,9 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value 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)); + // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. A + // query that fills the clipboard (`clipboard.importSvg`) takes one too, for the clipboard. + let save = ((mutating || CAN_FAIL_AFTER_COPYING.contains(&id)) && !host.dom.saving()).then(|| Savepoint::take(s, id)); let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); @@ -1336,7 +1418,10 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value // the open documents; it also reads the files the documents open when the run began link to, as the // person left them. A document a script's command opened gives it no file. let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect(); - let gate = host.disk.borrow().gate(documents, host.linked()); + // The linked files are fixed at the run's first step, also when that step is an exact open that gets none. + let linked = host.linked(); + let linked = if id == "document.open" && host.disk.borrow().exact { Default::default() } else { linked }; + let gate = host.disk.borrow().gate(documents, linked); let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect(); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); // What the command opened, changed or gave another file is not as the person left it. @@ -1426,9 +1511,9 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std:: let session = host.session.clone(); let started = clock(); let before = dom::before_command(host, id); - let r = { + let (copies, r) = { let mut s = session.borrow_mut(); - step(&mut s, host, id, params) + (s.copies, step(&mut s, host, id, params)) }; // Only commands that exist are timed, so the table holds at most one row per command. if let (Some(started), Some(spec)) = (started, crate::find_command(id)) { @@ -1459,19 +1544,26 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std:: if crossed.is_err() { host.put_growth_back(mark); } + let mut s = session.borrow_mut(); if let Some(save) = save { - let mut s = session.borrow_mut(); if crossed.is_ok() { save.keep(&mut s); } else if !save.restore(&mut s) { return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + // A Copy or Cut counts for the run only once what it put on the clipboard is kept. + if s.copies != copies { + host.copied.set(true); + } + drop(s); dom::after_command(host, before); // Style objects follow only a command that is kept. if crossed.is_ok() { - dom::see_points(host); + // The command stays kept when the look at its changes passes a limit, which ends the run. + let seen = dom::see_points(host); dom::after_kept_command(host); + seen?; } else { session.borrow_mut().script_style_trail = StyleTrail::default(); } @@ -1926,6 +2018,7 @@ impl Session { match gone { Some(engine) => { drop(engine); + self.keep_engines_palettes(); Ok(()) } None => Err(EngineError::Other(format!("there is no script engine named {name:?}"))), @@ -2072,12 +2165,28 @@ impl Session { self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting())).flatten() } + /// Whether [`Session::script_dialog`] is the confirm the app opened to turn off the external + /// script warning, which only a person answers Yes to. A script's own confirm with the same + /// text is not. + pub fn script_dialog_turns_warning_off(&self) -> bool { + self.script_dialog().is_some() && self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.asks_warning_off())).unwrap_or(false) + } + /// Gives the dialog the running script waits at its answer; the next [`Session::script_pump`] /// goes on from the call. → false when nothing waits, the answer is for another kind of - /// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`]. + /// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`]. Yes to a confirm the + /// app opened for the script ([`dialogs::Dialogs::ask`]) also does what it asked. pub fn script_answer(&mut self, answer: DialogAnswer) -> bool { let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false }; - with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) + with_job(k, |j| { + let given = j.host.dialogs.answer(&mut j.realm, answer); + // Between slices the run's preferences are in its working copy. + if let Some(dialogs::OnYes::ExternalScriptWarningOff) = j.host.dialogs.take_approved() { + j.world.choices.prefs.show_external_script_warning = false; + } + given + }) + .unwrap_or(false) } /// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run @@ -2197,6 +2306,9 @@ impl Session { lost }); drop(lost); + self.keep_engines_palettes(); + // The job's working copy went with it, with the documents the run opened. + self.plugin_events_script_ended(false); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -2216,6 +2328,10 @@ impl Session { /// A script can't start while a document holds a drag in progress or an undo group, which its /// one undo step could not take in. fn settle_for_script(&mut self) -> Result<()> { + #[cfg(test)] + if SETTLE_FAILS.with(Cell::get) { + return Err(EngineError::Other("the open edit could not be settled".into())); + } self.finish_tool_edit_later()?; if self.active().is_some() { cmd::settle_interaction(self)?; @@ -2228,6 +2344,7 @@ impl Session { /// Begins a run of `request`. → the run's name. pub(crate) fn script_start(&mut self, request: Request) -> Result { + let palette_event = self.script_palettes.starting.take(); self.settle_for_script()?; // In a build where a fault ends the program, every unsaved document has a copy first. if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { @@ -2287,13 +2404,16 @@ impl Session { // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read // code the way the script does. Its realm has `Promise`; a kept realm retains it. let es2015 = request.module || include::es2015_script(request.file.as_deref()); - let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() }; + // It also reads async functions and `await` (ECMAScript 2017). + let options = + Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, es2017: es2015, e4x: true, ..Options::default() }; let strict = options.strict; // A kept engine reads each run's code the way that run's script does. let mut realm = match realm { Some(mut realm) => { realm.set_limits(limits); realm.set_es2015(es2015); + realm.set_es2017(es2015); if es2015 { realm.add_es2015(); } @@ -2330,6 +2450,7 @@ impl Session { log: RefCell::new(Vec::new()), log_bytes: Cell::new(0), written: RefCell::new(Written::default()), + copied: Cell::new(false), run: self.script_runs, name: console::line_name(&name), console: RefCell::default(), @@ -2345,6 +2466,7 @@ impl Session { script: request.file.clone(), // The text with its included files, so a changed included file asks again. source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()), + own: palette_event.as_ref().and_then(|q| q.grants.clone()), data_dir: self.script_data_dir.clone(), engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| { let m = m.borrow(); @@ -2362,12 +2484,18 @@ impl Session { kept_maps, started: clock(), wake_at: Cell::new(None), + drawn_at: Cell::new(None), can_wait: realm.wait_flag(), eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), - dom: dom::State::new(heap_bytes), + engine: engine.clone(), + file: request.file.clone(), + palette_event: RefCell::new(palette_event), + dom: dom::State::new(self.documents(), heap_bytes), + interface_docs: RefCell::new(Vec::new()), actions: request.actions, + palette_actions: RefCell::new(None), active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), artboard_picks, run_docs: RefCell::new( @@ -2444,6 +2572,7 @@ impl Session { // error drops a kept one. let keep = !fresh && e.kind != RunErrorKind::Internal; self.return_engine(engine.as_deref(), &link, keep.then_some(realm)); + self.keep_engines_palettes(); let mut report = failure_report(&name, &e, file.as_deref(), &host, 0, 0); close_run(self, &host, &mut report, ending(&e.kind)); let message = failure_text(&report); @@ -2592,6 +2721,8 @@ impl Session { let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); close_run(self, &job.host, &mut report, ending(&e.kind)); self.end_job(job, e.kind == RunErrorKind::Internal); + self.keep_engines_palettes(); + self.plugin_events_script_ended(false); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -2668,6 +2799,9 @@ impl Session { self.script_stop.clear(); self.reset_tool(); cmd::compositefonts::sync(self); + if std::mem::take(&mut self.overprint_after_run) { + cmd::colormgmt::turn_on_overprint_preview(self); + } let host = &job.host; let mut report = json!({ "ok": true, @@ -2679,6 +2813,17 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + let start: Vec<(u64, usize)> = host.dom.boards_at_start.iter().chain(host.dom.boards_chosen_in_new.borrow().iter()).copied().collect(); + if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &start, self.documents()) { + report["activeArtboards"] = boards; + } + // The run ran a Copy or Cut, and the clipboard still holds what one put there. + if host.copied.get() + && self.clipboard_copied + && let Some(o) = report.as_object_mut() + { + o.insert("copied".into(), json!(true)); + } // The jobs it prepared for a printer wait for the frontend now that its changes are kept. let prints = host.dom.take_prints(); if !prints.is_empty() { @@ -2693,6 +2838,7 @@ impl Session { close_run(self, host, &mut report, console::Ending::Finished); let tool = host.dom.chosen_tool(); self.end_job(job, false); + self.plugin_events_script_ended(true); // The tool `app.selectTool` chose last becomes the current tool, as a choice on the // toolbar makes it; the run's changes are kept when the tool cannot be chosen. if let Some(id) = tool @@ -2722,7 +2868,7 @@ impl Session { } } -const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; +pub(crate) const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; const INVALID_RESULT: &str = "the script left a document that cannot be kept"; const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written"; const JOB_GONE: &str = "the script's run is no longer available"; @@ -2907,6 +3053,8 @@ fn failure_frame(report: &Value) -> (String, String) { fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result, String> { let depth = std::mem::replace(&mut s.depth, 0); job.world.swap(s); + // The interface's documents are the host's to read during the slice, and the job's again after. + std::mem::swap(&mut job.world.docs, &mut *job.host.interface_docs.borrow_mut()); // The run's front document draws and converts through its own profiles, and the interface's // again after the slice. s.sync_front_profiles(); @@ -2915,6 +3063,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result std::result::Result realm.refresh_script_ui().and_then(|()| { + dom::flush(host).map_err(end_flush_error)?; + Ok(Progress::Done(v)) + }), + // A failed run keeps its globals, so its palettes show what it left too; a refresh + // that fails as well (the fuel is spent, a stop) leaves them as they were, and the + // run's error keeps its place. + Err(e) if named && e.kind != RunErrorKind::Internal => { + realm.refresh_script_ui_after_error(); + Err(e) + } + r => r, + } }) }); if let Some(started) = started { @@ -2940,6 +3111,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result> = const { Cell::new(None) }; /// Tests: makes the next slice panic. pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; + /// Tests: makes settling the open edits before a run fail. + pub(crate) static SETTLE_FAILS: Cell = const { Cell::new(false) }; /// Tests: makes the next command a member runs past the script fence panic before it runs. pub(crate) static PANIC_WHILE_UNFENCED: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs new file mode 100644 index 0000000000..a63a712918 --- /dev/null +++ b/crates/engine/src/script/palettes.rs @@ -0,0 +1,536 @@ +//! ScriptUI palettes (`new Window("palette")`, [`vectorcraft_js::scriptui`]): windows a run in a +//! named engine (`#targetengine`) shows, which stay open after the run ends and take clicks and +//! changes while the person goes on working. +//! +//! A palette needs a named engine, which keeps its controls and handlers between runs: in a script +//! without `#targetengine`, or with `main`, `new Window("palette")` throws. `show()` returns at once. +//! Each click, change or close the person gives a palette waits here, and then runs as a run of its +//! own in the palette's engine, which takes the mutation lease like any other run: one event at a +//! time, oldest first, each starting only once no run is going. A new click, change or close replaces +//! the most recent waiting event of the same kind for the same control or palette only when that +//! event has the same file access scope. Otherwise the new event waits at the end of the line. A click or +//! close replaces an event only after its palette's last waiting change. A palette's `update()` in +//! a run of the palette's engine takes the events that wait for that engine's palettes and runs their +//! handlers in that run instead ([`Palettes::take_for`]). +//! +//! A palette closes when its script calls `close()` or the person closes it, unless `onClose` +//! returns `false`; when its engine is dropped or ends with an internal error; and with the session. +//! Hiding or closing a palette drops the events that wait for it. An error in a handler ends that +//! handler's run like any failed run, with its report, and leaves the palette open. +//! +//! The limits here are VectorCraft's own: [`MAX_PALETTES`] and [`MAX_WAITING`]. + +use std::collections::VecDeque; + +use serde_json::{Map, Value, json}; + +use super::actions::Playable; +use super::scriptui::{self, ScriptUiDialog, UiEvent, UiKind, UiValue}; +use crate::{EngineError, Result, Session}; + +/// The most palettes a session keeps, shown or hidden. +pub const MAX_PALETTES: usize = 16; +/// The most events that wait for a run, for every palette together. +pub const MAX_WAITING: usize = 64; + +/// A palette a run showed. +#[derive(Clone, Debug, PartialEq)] +pub struct ScriptPalette { + /// Its number in the session, which no other palette of the session has had. + pub id: u64, + /// The named engine its handlers run in. + pub engine: String, + /// The script file of the run that first showed it, whose folder its handlers read in; `None` + /// for a script given as text. + pub file: Option, + /// Its controls, as the last `show()`, `add()` or handler left them. + pub dialog: ScriptUiDialog, + pub visible: bool, + /// The SHA-256 the file grants of the script that first showed it are kept for, which its + /// handlers' runs keep using: the grants allowed with Always. A grant allowed once is the + /// showing run's alone, as for any later run of the script. + pub(crate) grants: String, +} + +/// What became of an event given to a palette. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Waiting { + /// It waits at the end of the line. + Added, + /// It took the place of a waiting event for the same control. + Merged, +} + +/// An event given to a palette, waiting for its run or handed to it. +#[derive(Clone, Debug)] +pub(crate) struct Queued { + pub(crate) palette: u64, + pub(crate) event: UiEvent, + /// The id of the control of a click or a change ([`super::scriptui::UiNode::id`]), by which the + /// event finds its control again when a run adds or removes controls before it; `None` for a + /// close. + pub(crate) element: Option, + /// For a list's change, the list's items as the palette showed them when the event was given and + /// the list's revision then ([`super::scriptui::UiNode::revision`]), which the run checks the list + /// still has. + pub(crate) list: Option<(Vec, f64)>, + /// Once its run starts, the SHA-256 the file grants of the palette's script are kept for, which + /// the run takes as its own ([`super::files::Setup::own`]). + pub(crate) grants: Option, + /// The file access scope of the request that gave the event, which its run keeps, narrowed to + /// the scope in force when the run starts ([`crate::file_access::ScopeHandle::within_current`]). + pub(crate) scope: crate::file_access::ScopeHandle, + /// The number of the request that gave the event last: an event that takes the place of a + /// waiting one takes a new number. + pub(crate) ticket: u64, +} + +/// The palettes of a session, and the events that wait for a run. +#[derive(Debug, Default)] +pub(crate) struct Palettes { + list: Vec, + /// The actions `app.doScript` plays in each palette's handlers, by palette id: those of the + /// run that first showed the palette. + actions: Vec<(u64, Vec)>, + waiting: VecDeque, + last_id: u64, + /// The number the last event given took ([`Queued::ticket`]). + last_ticket: u64, + /// The number of the event whose run started last. + started_ticket: Option, + /// While [`Session::script_palette_run_waiting`] runs an event, the numbers of the events its + /// run takes inside it (`update()`). + taken_inline: Option>, + /// The event the run that starts next handles ([`Session::script_palette_start`]). + pub(crate) starting: Option, +} + +/// Does `event`, for the control whose id is `element`, share the waiting `q`'s place in line: a +/// click on the same control, a change of it, or a close? +fn same_place(q: &Queued, event: &UiEvent, element: Option) -> bool { + let same_kind = matches!( + (&q.event, event), + (UiEvent::Click(_), UiEvent::Click(_)) | (UiEvent::Change(..), UiEvent::Change(..)) | (UiEvent::Close, UiEvent::Close) + ); + same_kind && q.element == element +} + +/// The control of a click or a change. +fn control_of(event: &mut UiEvent) -> Option<&mut usize> { + match event { + UiEvent::Click(c) | UiEvent::Change(c, _) => Some(c), + UiEvent::Close => None, + } +} + +impl Palettes { + fn find(&mut self, id: u64, engine: &str) -> Option<&mut ScriptPalette> { + self.list.iter_mut().find(|p| p.id == id && p.engine == engine) + } + + /// `show()`: shows the palette `id` of `engine` with `dialog`, or a new one without `id`, whose + /// handlers take the showing run's `actions`. → its id. + pub(crate) fn show( + &mut self, + id: Option, + engine: &str, + (file, grants, actions): (Option, String, &[Playable]), + dialog: ScriptUiDialog, + ) -> std::result::Result { + if let Some(p) = id.and_then(|id| self.find(id, engine)) { + p.dialog = dialog; + p.visible = true; + return Ok(p.id); + } + if self.list.len() >= MAX_PALETTES { + return Err(format!("show: a session keeps at most {MAX_PALETTES} script palettes; close one first")); + } + self.last_id += 1; + self.list.push(ScriptPalette { id: self.last_id, engine: engine.to_string(), file, dialog, visible: true, grants }); + if !actions.is_empty() { + self.actions.push((self.last_id, actions.to_vec())); + } + Ok(self.last_id) + } + + /// The palette's controls as a handler or `add()` left them. → false when it is closed. + pub(crate) fn update(&mut self, id: u64, engine: &str, dialog: ScriptUiDialog) -> bool { + let Some(p) = self.find(id, engine) else { return false }; + p.dialog = dialog; + true + } + + /// `hide()`. → false when it is closed. + pub(crate) fn hide(&mut self, id: u64, engine: &str) -> bool { + let Some(p) = self.find(id, engine) else { return false }; + p.visible = false; + self.waiting.retain(|q| q.palette != id); + true + } + + /// `close()`, once `onClose` allowed it. → false when it was closed already. + pub(crate) fn close(&mut self, id: u64, engine: &str) -> bool { + let before = self.list.len(); + self.list.retain(|p| !(p.id == id && p.engine == engine)); + let closed = self.list.len() != before; + if closed { + self.waiting.retain(|q| q.palette != id); + self.actions.retain(|(p, _)| *p != id); + } + closed + } + + /// Closes the palettes of the engines `keep` does not keep, with their waiting events. + fn keep_engines(&mut self, keep: impl Fn(&str) -> bool) { + self.list.retain(|p| keep(&p.engine)); + let open: Vec = self.list.iter().map(|p| p.id).collect(); + self.waiting.retain(|q| open.contains(&q.palette)); + self.actions.retain(|(p, _)| open.contains(p)); + } + + /// Puts `event` for the shown palette `id` in line, once it is checked against the palette. + fn wait(&mut self, id: u64, event: UiEvent) -> std::result::Result { + let Some(p) = self.list.iter().find(|p| p.id == id) else { return Err(format!("there is no script palette {id}")) }; + if !p.visible { + return Err(format!("the script palette {id} is hidden")); + } + let mut event = scriptui::check_event(&p.dialog, event)?; + let list = match &event { + UiEvent::Change(c, UiValue::Index(_)) => p.dialog.nodes.get(*c).map(|n| (n.items.clone(), n.revision)), + _ => None, + }; + let element = control_of(&mut event).and_then(|c| p.dialog.nodes.get(*c)).map(|n| n.id); + let scope = crate::file_access::ScopeHandle::capture(); + // Only the most recent event for the same place can merge, in the same file access scope. + // A click or close merges only after its palette's last waiting change, and a change only + // after its palette's last waiting click or close. + let closing = matches!(event, UiEvent::Click(_) | UiEvent::Close); + let after = self.waiting.iter().rposition(|q| q.palette == id && matches!(q.event, UiEvent::Change(..)) == closing).map_or(0, |at| at + 1); + let at = self.waiting.iter_mut().skip(after).rev().find(|q| q.palette == id && same_place(q, &event, element)); + let ticket = self.last_ticket.wrapping_add(1); + if let Some(slot) = at.filter(|q| q.scope.same(&scope)) { + slot.event = event; + slot.list = list; + slot.ticket = ticket; + self.last_ticket = ticket; + return Ok(Waiting::Merged); + } + if self.waiting.len() >= MAX_WAITING { + return Err(format!("{MAX_WAITING} script palette events already wait; this one was not kept")); + } + self.waiting.push_back(Queued { palette: id, event, element, list, grants: None, scope, ticket }); + self.last_ticket = ticket; + Ok(Waiting::Added) + } + + /// The oldest waiting event whose palette is still shown, given to its control in the palette + /// as the runs since left it, and that palette. An event whose control the palette + /// no longer has, or that the control can no longer take ([`scriptui::check_event`]), for + /// example because a handler disabled or hid it, is dropped. + fn next(&mut self) -> Option<(ScriptPalette, Queued)> { + while let Some(q) = self.waiting.pop_front() { + if let Some(taken) = self.checked(q) { + return Some(taken); + } + } + None + } + + /// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other + /// engines' palettes keep their places in line. Events whose file access scopes do not cover + /// the run's scope wait for runs of their own ([`Queued::scope`]). Eligible events run oldest + /// first, preserving the order within each scope. + fn next_of(&mut self, engine: &str) -> Option<(ScriptPalette, Queued)> { + loop { + let at = self.oldest_for(engine)?; + let q = self.waiting.remove(at)?; + if let Some(taken) = self.checked(q) { + return Some(taken); + } + } + } + + /// The taken event `q` given to its control in its palette, and that palette, or `None` when it + /// is dropped ([`Palettes::next`]). + fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> { + let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?; + if let Some(c) = control_of(&mut q.event) { + *c = p.dialog.index_of(q.element?)?; + } + // A list's change whose list a run changed since goes to its run, which ends with the + // error that says so, when the list can still take a change: the choice is checked + // without its item, which the list may no longer have. + let list_changed = match (&q.event, &q.list) { + (UiEvent::Change(c, UiValue::Index(_)), Some((_, revision))) => { + p.dialog.nodes.get(*c).is_some_and(|n| n.revision != *revision).then_some(*c) + } + _ => None, + }; + if let Some(c) = list_changed { + scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).ok()?; + } else { + q.event = scriptui::check_event(&p.dialog, q.event).ok()?; + } + Some((p.clone(), q)) + } + + /// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()` + /// in a run of that engine takes and hands to the palette at once ([`Palettes::next_of`]), with + /// the actions its handlers play: those of the run that first showed its palette. + pub(crate) fn take_for(&mut self, engine: &str) -> Option<(Queued, Vec)> { + let q = self.next_of(engine).map(|(_, q)| q)?; + if let Some(taken) = self.taken_inline.as_mut() { + taken.push(q.ticket); + } + let actions = self.actions.iter().find(|(id, _)| *id == q.palette).map(|(_, a)| a.clone()).unwrap_or_default(); + Some((q, actions)) + } + + /// Whether an event waits for a palette of the engine `engine`, which [`Palettes::take_for`] + /// would then check and take. + pub(crate) fn waits_for(&self, engine: &str) -> bool { + self.oldest_for(engine).is_some() + } + + /// The place of the oldest event for a palette of `engine`, when a palette's `update()` in a + /// run of that engine may take it ([`Palettes::next_of`]): the run reaches the same files the + /// event's scope reaches, so the handler runs with neither more nor less access than in a run + /// of its own. Any other event waits for a run of its own. + fn oldest_for(&self, engine: &str) -> Option { + self.waiting.iter().position(|q| q.scope.matches_current() && self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) + } +} + +/// `name` in a `#targetengine` line, quoted with a quote it does not hold. +fn engine_line(name: &str) -> String { + let quote = if name.contains('"') { '\'' } else { '"' }; + format!("#targetengine {quote}{name}{quote}") +} + +/// The source of a palette's handler run: its engine, and the call that hands the event to the +/// palette, which takes it from the run's host. +fn handler_source(engine: &str) -> String { + format!("{}\nthis[{:?}]();\n", engine_line(engine), vectorcraft_js::scriptui::PALETTE_EVENT_GLOBAL) +} + +/// The event `event` (`click`, `change` or `close`) for `dialog`, from `script.palette.event`'s +/// `control` (a control's index, or its name or text) and `value` (an edit field's text, a slider's +/// number, or a list's item index or null). +pub(crate) fn parse_event( + dialog: &ScriptUiDialog, + event: &str, + control: Option<&Value>, + value: Option<&Value>, +) -> std::result::Result { + if event == "close" { + if control.is_some() || value.is_some() { + return Err("a close takes no `control` and no `value`".into()); + } + return Ok(UiEvent::Close); + } + let id = match control { + Some(Value::Number(n)) => n.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`control` must be a control's index, name or text")?, + Some(Value::String(s)) => dialog.find(s).ok_or_else(|| format!("the palette has no control named {}", super::dialogs::cut_to(s, 64)))?, + _ => return Err("`control` must be a control's index, name or text".into()), + }; + let list = dialog.nodes.get(id).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox)); + let event = match (event, value) { + ("click", None) => UiEvent::Click(id), + ("click", Some(_)) => return Err("a click takes no `value`".into()), + ("change", Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), + ("change", Some(Value::Number(v))) if list => match scriptui::list_index(v) { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))), + None => return Err("a list's `value` must be an item index or null".into()), + }, + ("change", Some(Value::Number(v))) => UiEvent::Change(id, UiValue::Number(v.as_f64().unwrap_or(f64::NAN))), + ("change", Some(Value::Null)) if list => UiEvent::Change(id, UiValue::Index(None)), + ("change", _) => return Err("a change's `value` must be a string, a number, or for a list an item index or null".into()), + _ => return Err("`event` must be click, change or close".into()), + }; + scriptui::check_event(dialog, event) +} + +/// A palette as `script.palettes` lists it. +pub(crate) fn palette_json(p: &ScriptPalette) -> Value { + let controls: Vec = p + .dialog + .nodes + .iter() + .enumerate() + .skip(1) + .map(|(i, n)| { + let mut c = Map::new(); + c.insert("index".into(), json!(i)); + c.insert("kind".into(), json!(kind_id(n.kind))); + c.insert("name".into(), json!(n.name)); + c.insert("text".into(), json!(n.text)); + c.insert("enabled".into(), json!(n.enabled)); + c.insert("visible".into(), json!(n.visible)); + match n.kind { + UiKind::CheckBox | UiKind::RadioButton => { + c.insert("value".into(), json!(n.checked)); + } + UiKind::Slider | UiKind::ProgressBar => { + c.insert("value".into(), json!(n.value)); + } + UiKind::DropDownList | UiKind::ListBox => { + c.insert("items".into(), json!(n.items)); + c.insert("selection".into(), json!(n.selection)); + } + _ => {} + } + Value::Object(c) + }) + .collect(); + json!({"id": p.id, "engine": p.engine, "title": p.dialog.title(), "visible": p.visible, "controls": controls}) +} + +fn kind_id(kind: UiKind) -> &'static str { + match kind { + UiKind::Dialog => "palette", + UiKind::Group => "group", + UiKind::Panel => "panel", + UiKind::StaticText => "statictext", + UiKind::EditText => "edittext", + UiKind::Button => "button", + UiKind::CheckBox => "checkbox", + UiKind::RadioButton => "radiobutton", + UiKind::DropDownList => "dropdownlist", + UiKind::ListBox => "listbox", + UiKind::Slider => "slider", + UiKind::ProgressBar => "progressbar", + } +} + +impl Session { + /// The palettes the named engines' runs showed and have not closed, shown or hidden, in the + /// order they were first shown. + pub fn script_palettes(&self) -> &[ScriptPalette] { + &self.script_palettes.list + } + + /// How many palette events wait for a run. + pub fn script_palette_events_waiting(&self) -> usize { + self.script_palettes.waiting.len() + } + + /// The changes that wait for a run, as (palette id, the id of the control they change). + pub fn script_palette_changes_waiting(&self) -> Vec<(u64, u64)> { + self.script_palettes + .waiting + .iter() + .filter(|q| matches!(q.event, UiEvent::Change(..))) + .filter_map(|q| q.element.map(|e| (q.palette, e))) + .collect() + } + + /// Whether [`Session::script_palette_start`] can start a waiting event's run now: an event + /// waits, no run is going, and no undo group is open, which a run cannot start in, nor a drag + /// in a document other than the active one. A drag in the active document is not counted, + /// since starting the run settles it. + pub fn script_palette_can_start(&self) -> bool { + !self.script_palettes.waiting.is_empty() && !self.script_running() && !self.palette_run_blocked() + } + + /// Whether an open edit keeps a palette event's run from starting: an undo group, the + /// session's or a document's, or a drag in a document other than the active one (starting the + /// run settles a drag in the active one). + pub(crate) fn palette_run_blocked(&self) -> bool { + let active = self.active().map(|d| d.uid); + self.undo_group_open() || self.docs.iter().any(|d| d.interaction.is_some() && Some(d.uid) != active) + } + + /// Whether an undo group is open, the session's or a document's, which a run cannot start in. + pub(crate) fn undo_group_open(&self) -> bool { + self.explicit_undo_group.is_some() || self.docs.iter().any(|d| d.undo_group.is_some()) + } + + /// Puts `event` for the shown palette `id` in line, to run in its engine once no run is going + /// ([`Session::script_palette_start`]). → an error when there is no such shown palette, it + /// cannot take the event ([`scriptui::check_event`]), or [`MAX_WAITING`] events already wait. + pub fn script_palette_event(&mut self, id: u64, event: UiEvent) -> std::result::Result { + self.script_palettes.wait(id, event) + } + + /// Starts the run of the oldest waiting palette event, when no run is going. → `None` when a + /// run is going or no event waits; otherwise the run's name, or the error that ended it before + /// it began. An open edit that cannot be settled gives its error, and the events keep waiting. + pub fn script_palette_start(&mut self) -> Option> { + if self.script_running() || self.script_palettes.waiting.is_empty() { + return None; + } + // An event waits while a drag or an undo group is open, which a run cannot start in. + if let Err(e) = self.settle_for_script() { + return Some(Err(e)); + } + let (palette, mut queued) = self.script_palettes.next()?; + self.script_palettes.started_ticket = Some(queued.ticket); + queued.grants = Some(palette.grants.clone()); + let title = palette.dialog.title(); + let name = if title.is_empty() { "palette".to_string() } else { super::dialogs::cut_to(title, super::dialogs::MAX_TITLE_BYTES).to_string() }; + let locale = super::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language)); + let actions = self.script_palettes.actions.iter().find(|(id, _)| *id == palette.id).map(|(_, a)| a.clone()).unwrap_or_default(); + let request = super::Request { + name, + name_given: true, + file: palette.file.clone(), + checked_real: None, + source: handler_source(&palette.engine), + args: Map::new(), + fuel: super::DEFAULT_FUEL, + locale, + answers: Vec::new(), + module: false, + actions, + }; + // The run takes the scope of the request that gave the event, within the scope in force now. + let scope = queued.scope.clone().within_current(); + self.script_palettes.starting = Some(queued); + let r = scope.run(|| self.script_start(request)); + self.script_palettes.starting = None; + Some(r) + } + + /// Closes the palettes whose engine the session no longer keeps. + pub(crate) fn keep_engines_palettes(&mut self) { + let names: Vec = self.script_engines().into_iter().map(|(name, ..)| name).collect(); + self.script_palettes.keep_engines(|e| names.iter().any(|n| n == e)); + } + + /// `script.palette.event` with no run going and nobody to ask: runs the waiting events in turn, + /// in their order in line. → the report of the event just given, wherever it waited, or an + /// error when it was dropped without a run. An event whose run could not begin, for example + /// because the recovery copies could not be saved, ends this, and the events after it keep + /// waiting: with its error, or with the given event's result when that one has run. An open + /// edit that cannot be settled ends this with its error, and the given event no longer waits. + pub(crate) fn script_palette_run_waiting(&mut self) -> Result { + let want = self.script_palettes.last_ticket; + let mut mine = None; + loop { + if !self.script_running() + && !self.script_palettes.waiting.is_empty() + && let Err(e) = self.settle_for_script() + { + // A caller that gives the event again then does not give it twice. + self.script_palettes.waiting.retain(|q| q.ticket != want); + return mine.unwrap_or(Err(e)); + } + let Some(started) = self.script_palette_start() else { break }; + // A later event whose run cannot begin leaves the given event's result as it is. + if let Err(e) = started { + return mine.unwrap_or(Err(e)); + } + self.script_palettes.taken_inline = Some(Vec::new()); + let r = self.script_run_to_end(); + // A run of the same engine can take the event while it runs (`update()`): its report + // is then the event's. + let inline = self.script_palettes.taken_inline.take().is_some_and(|t| t.contains(&want)); + if mine.is_none() && (self.script_palettes.started_ticket == Some(want) || inline) { + mine = Some(r); + } + } + mine.unwrap_or_else(|| { + Err(EngineError::Other("the script palette event was dropped without a run: its palette or control can no longer take it".into())) + }) + } +} diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 4226196239..04216386bc 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -1,6 +1,9 @@ //! 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. +//! person or `script.run`'s `answers` give back. A palette (`new Window("palette")`) is described +//! and laid out the same way; [`super::palettes`] keeps it and its events, and the host functions +//! `palette`, `paletteShow`, `paletteUpdate`, `paletteHide`, `paletteClose` and `paletteEvent` here +//! act for a run in a named engine, and throw [`PALETTE_NEEDS_ENGINE`] in any other. //! //! 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 @@ -36,6 +39,7 @@ 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; +use super::palettes::Queued; /// The largest size or place, in pixels, of a dialog or a control in it. pub const MAX_EXTENT: f32 = 8192.0; @@ -143,6 +147,9 @@ pub struct UiNode { /// list from one that holds the same texts again. pub items_revision: u64, pub selection: Option, + /// How many times a list's items were added or removed, which a palette's waiting change of + /// the list is checked against. + pub revision: f64, pub multiline: bool, pub readonly: bool, pub rect: UiRect, @@ -208,6 +215,12 @@ impl ScriptUiDialog { }; by(true).or_else(|| by(false)) } + + /// The index in [`Self::nodes`] of the control whose id ([`UiNode::id`]) is `id`, if the dialog + /// has one. + pub fn index_of(&self, id: u64) -> Option { + self.nodes.iter().position(|n| n.id == id).filter(|i| *i > 0) + } } /// A value a control takes in a change. @@ -516,6 +529,7 @@ pub fn parse(d: &Data) -> Result { items, items_revision: number(field(f, "itemsRevision")).map_or(0, |n| n as u64), selection, + revision: number(field(f, "revision")).unwrap_or(0.0), multiline: flag("multiline"), readonly: flag("readonly"), rect: UiRect::default(), @@ -709,7 +723,132 @@ fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result /// 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))]) + realm.define_script_ui(vec![ + ("open".into(), function(link, open)), + ("wait".into(), function(link, wait)), + ("end".into(), function(link, end)), + ("palette".into(), function(link, palette)), + ("paletteShow".into(), function(link, palette_show)), + ("paletteUpdate".into(), function(link, palette_update)), + ("paletteHide".into(), function(link, palette_hide)), + ("paletteClose".into(), function(link, palette_close)), + ("paletteEvent".into(), function(link, palette_event)), + ("paletteTake".into(), function(link, palette_take)), + ("palettePending".into(), function(link, palette_pending)), + ("paletteDraw".into(), function(link, palette_draw)), + ]) +} + +/// The error of `new Window("palette")` in a run without a named engine. +pub const PALETTE_NEEDS_ENGINE: &str = "Window: a palette needs a named engine, which keeps its controls and handlers after the script ends; put a #targetengine line with a name other than main at the top of the script"; + +/// The named engine of the run, for a palette. +fn palette_engine(host: &Host) -> Result<&str, HostError> { + host.engine.as_deref().ok_or_else(|| HostError::Error(PALETTE_NEEDS_ENGINE.into())) +} + +/// A palette's id as a script holds it: a whole number from 1, or none. +fn palette_id(d: Option<&Data>) -> Option { + match d { + Some(Data::Number(n)) if *n >= 1.0 && n.fract() == 0.0 && *n < 9.0e15 => Some(*n as u64), + _ => None, + } +} + +/// `new Window("palette")`: refused in a run without a named engine. +fn palette(host: &Host, _: &[Data]) -> Result { + palette_engine(host)?; + Ok(Data::Undefined) +} + +/// A palette's `show()`, with its description and its id (none the first time). → its id. +fn palette_show(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let dialog = described(host, args)?; + let id = palette_id(args.get(1)); + let grants = host.disk.borrow().own().to_string(); + let shown = host.session.borrow_mut().script_palettes.show(id, &engine, (host.file.clone(), grants, &host.actions), dialog); + shown.map(|id| Data::Number(id as f64)).map_err(HostError::Range) +} + +/// The palette `id`'s controls as a handler, `add()` or `update()` left them. +fn palette_update(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let dialog = described(host, args)?; + if let Some(id) = palette_id(args.get(1)) { + host.session.borrow_mut().script_palettes.update(id, &engine, dialog); + } + Ok(Data::Undefined) +} + +/// A palette's `update()` in the script's own code asks whether the app draws the palette now +/// ([`Host::update_drawn`]). → `true` when it does, and the script then gives the palette's +/// controls through `paletteUpdate`. +fn palette_draw(host: &Host, _: &[Data]) -> Result { + palette_engine(host)?; + Ok(Data::Bool(host.update_drawn())) +} + +/// A palette's `update()` takes the oldest event the person gave a palette of the run's engine, +/// which no run has handled yet, as `paletteEvent` gives it; `null` when none waits. Until the next +/// `palettePending`, `app.doScript` plays the actions of the run that showed the event's palette. +fn palette_take(host: &Host, _: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let taken = host.session.borrow_mut().script_palettes.take_for(&engine); + let (data, actions) = match taken { + Some((queued, actions)) => (event_data(queued), Some(actions)), + None => (Data::Null, None), + }; + *host.palette_actions.borrow_mut() = actions; + Ok(data) +} + +/// Whether an event waits for a palette of the run's engine, which a palette's `update()` asks +/// before it gives the palettes' controls and takes the event with `paletteTake`, and once more +/// after the event's handlers end. `app.doScript` then plays the run's own actions again. +fn palette_pending(host: &Host, _: &[Data]) -> Result { + *host.palette_actions.borrow_mut() = None; + let engine = palette_engine(host)?.to_string(); + Ok(Data::Bool(host.session.borrow().script_palettes.waits_for(&engine))) +} + +fn palette_hide(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + if let Some(id) = palette_id(args.first()) { + host.session.borrow_mut().script_palettes.hide(id, &engine); + } + Ok(Data::Undefined) +} + +fn palette_close(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + if let Some(id) = palette_id(args.first()) { + host.session.borrow_mut().script_palettes.close(id, &engine); + } + Ok(Data::Undefined) +} + +/// The event a palette handler's run is for, once: `{palette, event, id, value, element, items}`, +/// as `show()` takes a dialog's event with the palette's id added, the id of a click's or a +/// change's control (`element`, [`UiNode::id`]), which the run finds the control by, and for a +/// list's change the items the palette showed; `null` for any other run, and after the first call. +fn palette_event(host: &Host, _: &[Data]) -> Result { + let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) }; + Ok(event_data(queued)) +} + +/// The waiting event `queued` as a script takes it ([`palette_event`]). +fn event_data(queued: Queued) -> Data { + let Data::Object(mut fields) = queued.event.data() else { return Data::Null }; + fields.push(("palette".into(), Data::Number(queued.palette as f64))); + if let Some(element) = queued.element { + fields.push(("element".into(), Data::Number(element as f64))); + } + if let Some((items, revision)) = queued.list { + fields.push(("items".into(), Data::Array(items.into_iter().map(Data::String).collect()))); + fields.push(("revision".into(), Data::Number(revision))); + } + Data::Object(fields) } fn described(host: &Host, args: &[Data]) -> Result { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 4669876304..367334a008 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -54,6 +54,8 @@ impl Session { paint: PaintDefaults::default(), fill_active: true, clipboard: Clipboard::default(), + copies: 0, + clipboard_copied: false, journal: Journal::default(), history_budget: crate::default_history_budget(), histories_seen: None, @@ -136,10 +138,12 @@ impl Session { batch_stash: None, batch_steps: None, batch_paint_docs: Vec::new(), + swatch_renames: Vec::new(), composite_names: Vec::new(), composite_names_registered: HashSet::new(), reading: false, place_hand_off: None, + image_only: std::cell::Cell::new(None), queue_hand_off: None, place_queue_roots: None, place_queue_loads: 0, @@ -151,6 +155,8 @@ impl Session { screens_hand_off: None, recovery: Default::default(), in_tool_actions: false, + plugin_events: Default::default(), + plugin_event_frames: false, settled_warnings: None, held_interaction: None, previewing: false, @@ -192,6 +198,8 @@ impl Session { script_high_water: Default::default(), script_style_trail: Default::default(), script_in_run: false, + script_palettes: Default::default(), + overprint_after_run: false, script_unfenced: None, script_printers: None, script_prints: Vec::new(), @@ -422,6 +430,7 @@ impl Session { { self.begin_named_undo_group(label); } + self.plugin_events_see_new_documents(); i } @@ -496,6 +505,28 @@ impl Session { true } + /// Measure the type not measured yet in the open document with [`DocState::uid`] `uid` when it is + /// in the back, as [`Session::measure_back_document`] does, so bounds read from it are the ones + /// it has once it comes to the front. A document in front, or one with all its type measured, + /// is left as it is. A document unchanged since it was last measured or checked here is not + /// walked again ([`DocState::measured_in_own`]; with no composite font names kept, its coming + /// to the front measures again what it would have measured without the check). + pub(crate) fn measure_back_type(&mut self, uid: u64) { + let Some(index) = self.docs.iter().position(|d| d.uid == uid) else { return }; + if self.active == Some(index) { + return; + } + let st = &mut self.docs[index]; + if st.measured_in_own.as_ref().is_some_and(|(doc, _)| std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))) { + return; + } + if text_trees(&st.doc).any(|n| has_text_where(n, &mut |t| t.cached_bounds.is_none())) { + self.measure_back_document(index); + } else { + st.measured_in_own = Some((Arc::downgrade(&st.doc), HashSet::new())); + } + } + /// Measure the type not measured yet in open document `index`, which is in the back, in its own /// composite fonts, lent for the measuring, so its type has the bounds it will have when the /// document comes to the front: type naming a composite font the document does not define is diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index bb8982b0cf..05908c8616 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -5,6 +5,12 @@ use super::{ use crate::doc_state::{kept_from, objects_only}; impl Session { + /// Takes committed swatch renames as (document uid, old name, new name) in execution order and leaves the record empty. + /// The uid identifies the originating document through [`crate::DocState::uid`]. + pub fn take_swatch_renames(&mut self) -> Vec<(u64, String, String)> { + std::mem::take(&mut self.swatch_renames) + } + /// Run `f` on a mutable copy of the active document. Outside an interaction this records one /// undo step labelled `label`; inside one it just mutates (the interaction commits later). pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result) -> Result { @@ -394,32 +400,34 @@ impl Session { // A change the command made to the new-art paints stays when the next preview or a cancel // puts back the paints the interaction began with (the Live Paint Bucket's colors); the // parts it left alone keep the interaction's. The pattern lists every field, so a field - // added to `PaintDefaults` does not compile until it is handled here. + // added to `PaintDefaults` does not compile until it is handled here. The paints a preview + // took its new-art paints over from take the change as well. let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = &self.paint; - let start = &mut it.paint; - if *fill != paint.fill { - start.fill.clone_from(fill); - } - if *stroke != paint.stroke { - start.stroke.clone_from(stroke); - } - if *stroke_width != paint.stroke_width { - start.stroke_width = *stroke_width; - } - if *appearance != paint.appearance { - start.appearance.clone_from(appearance); - } - if *opacity != paint.opacity { - start.opacity = *opacity; - } - if *blend != paint.blend { - start.blend = *blend; - } - if *style != paint.style { - start.style.clone_from(style); - } - if *inherited != paint.inherited { - start.inherited = *inherited; + for start in std::iter::once(&mut it.paint).chain(it.inherited_preview_paint.as_mut()) { + if *fill != paint.fill { + start.fill.clone_from(fill); + } + if *stroke != paint.stroke { + start.stroke.clone_from(stroke); + } + if *stroke_width != paint.stroke_width { + start.stroke_width = *stroke_width; + } + if *appearance != paint.appearance { + start.appearance.clone_from(appearance); + } + if *opacity != paint.opacity { + start.opacity = *opacity; + } + if *blend != paint.blend { + start.blend = *blend; + } + if *style != paint.style { + start.style.clone_from(style); + } + if *inherited != paint.inherited { + start.inherited = *inherited; + } } let active = self.active().is_some_and(|d| d.uid == uid); let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { return }; @@ -549,8 +557,13 @@ impl Session { revision: st.revision, preview: None, tool: false, + tool_joined: false, paint, used_defaults_only: false, + preserve_paint_on_cancel: false, + inherited_preview_paint: None, + inherited_preview_paint_used: false, + last_preview_paint: None, preview_paint: None, color_mode_paints: None, tool_paints: false, @@ -581,7 +594,8 @@ impl Session { // preview starts from the colors the interaction began with; so does a preview with // `defaultsOnly: true`, and one after it. let tool_paints = self.tool_paints(false) || self.tool_paints(true); - let (paint, restore_paint) = { + let new_art_basic = self.prefs.new_art_basic; + let (paint, restore_paint, inherited, last_preview_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; @@ -596,13 +610,19 @@ impl Session { // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. it.used_defaults_only |= cmd::asks_defaults_only(params); + it.preserve_paint_on_cancel |= cmd == "addon.document.floodFillArtboards"; it.tool_paints |= tool_paints; let restore_paint = it.tool_paints || cmd == "command.batch" || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) - || it.color_mode_paints.is_some(); + || it.color_mode_paints.is_some() + || (!new_art_basic && it.selection.is_empty() && it.preview.is_some() && cmd.starts_with("paint.")); let paint = it.paint.clone(); + let last_preview_paint = it.last_preview_paint.take().filter(|_| it.preview.is_some()); + // A preview that took the new-art paints from the art it drew puts back the paints it + // started from, which an earlier paint preview may have set. + let inherited = it.inherited_preview_paint.take(); it.preview_paint = None; it.color_mode_paints = None; it.deferred_color_mode = None; @@ -619,11 +639,25 @@ impl Session { // undone with it. st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); - (paint, restore_paint) + (paint, restore_paint, inherited, last_preview_paint) + }; + // The paints before the previews that build on each other: a preview that starts from the + // interaction's paints (or from the inherited ones) starts a new run of them. A field that + // no longer holds what the last preview left was changed outside the previews. + let base = if restore_paint || inherited.is_some() { + None + } else { + last_preview_paint.map(|(mut base, left)| { + take_changed_paints(&mut base, &left, &self.paint); + base + }) }; if restore_paint { self.paint = paint.clone(); + } else if let Some(before) = &inherited { + self.paint.clone_from(before); } + let base = base.unwrap_or_else(|| self.paint.clone()); self.pending_paint = None; // The previous preview's Assign Profile is undone with it. self.sync_front_profiles(); @@ -642,6 +676,13 @@ impl Session { } let params = self.noted(params); let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone()); + // A failed preview leaves the document at the snapshot, so the new-art paints that earlier + // previews changed (a `paint.*` preview with nothing selected) go back to the paints from + // before them as well. A change made outside the previews stays. + if r.is_err() { + self.paint.clone_from(&base); + } + let after_paint = r.is_ok().then(|| (base, self.paint.clone())); let after_item = self.active_appearance_item.clone(); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { @@ -651,6 +692,14 @@ impl Session { // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). it.preview = r.is_ok().then(|| (cmd.to_string(), params)); + it.last_preview_paint = after_paint; + // After a failed preview a cancel still puts back the paints the interaction began with. + if r.is_err() && !restore_paint && it.inherited_preview_paint.is_none() { + it.inherited_preview_paint.clone_from(&inherited); + } + if r.is_ok() && !restore_paint && inherited.is_some() { + it.inherited_preview_paint_used = true; + } if it.color_mode_paints.is_some() { it.preview_paint = batch_paint.clone(); } @@ -665,10 +714,15 @@ impl Session { // The interaction is taken below, so its starting state is read first: the commit is what // the previews that came before it changed. let before = (self.depth == 0).then(|| self.active().and_then(|st| st.interaction.as_ref().map(|it| st.layers_view_before(it)))).flatten(); + // Plug-in events wait for an open interaction only: a commit with none open ends nothing. + let open = self.in_interaction() || self.holds_interaction(); let r = self.commit_interaction_unwatched(); if let Some(before) = before { self.reveal_since(&before); } + if r.is_ok() && open { + self.plugin_events_interaction_ended(); + } r } @@ -679,6 +733,15 @@ impl Session { if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) { self.paint = paint; } + // A failed last preview leaves nothing to commit, so the paints an earlier preview set go too. + if let Some(paint) = self + .active() + .and_then(|st| st.interaction.as_ref()) + .filter(|it| it.preview.is_none() && (it.inherited_preview_paint.is_some() || it.inherited_preview_paint_used)) + .map(|it| it.paint.clone()) + { + self.paint = paint; + } self.remember_pending_paint(); cmd::colormgmt::commit_new_art_colors(self)?; let paint = self.paint.clone(); @@ -774,6 +837,7 @@ impl Session { } pub fn cancel_interaction(&mut self) -> Result<()> { + let open = self.in_interaction() || self.holds_interaction(); self.put_back_interaction(); self.restore_preview_appearance_item(); self.clear_deferred_overlay_cache(); @@ -784,6 +848,10 @@ impl Session { // it does a color previewed with `defaultsOnly: true`. let tool_paints = self.tool_paints(false) || self.tool_paints(true); let used_defaults_only = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.used_defaults_only); + let preserve_paint = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.preserve_paint_on_cancel); + // With New Art Has Basic Appearance off, a preview that selected new art from an empty + // selection gave that art's appearance to the new-art paints; after the undo nothing is + // selected to take them from, so the cancel puts back the paints the interaction began with. if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) @@ -791,8 +859,12 @@ impl Session { tool_paints || it.tool_paints || it.used_defaults_only + || it.preserve_paint_on_cancel || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() + || it.inherited_preview_paint.is_some() + || it.inherited_preview_paint_used + || (!self.prefs.new_art_basic && it.preview.is_some() && it.selection.is_empty()) }) .map(|it| it.paint.clone()) { @@ -808,9 +880,12 @@ impl Session { // With New Art Has Basic Appearance off, new art takes the appearance of the selection as // the document has it again, not as a preview left it. An interaction that changed only the // defaults (`defaultsOnly: true`) leaves the defaults it began with. - if !used_defaults_only { + if !used_defaults_only && !preserve_paint { self.inherit_new_art(); } + if open { + self.plugin_events_interaction_ended(); + } Ok(()) } @@ -819,6 +894,40 @@ impl Session { } } +/// Copy into `target` each field of `now` that differs from `left`. The pattern lists every field, +/// so a field added to `PaintDefaults` does not compile until it is handled here. +fn take_changed_paints( + target: &mut vectorcraft_tools::PaintDefaults, + left: &vectorcraft_tools::PaintDefaults, + now: &vectorcraft_tools::PaintDefaults, +) { + let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = now; + if left.fill != *fill { + target.fill.clone_from(fill); + } + if left.stroke != *stroke { + target.stroke.clone_from(stroke); + } + if left.stroke_width != *stroke_width { + target.stroke_width = *stroke_width; + } + if left.appearance != *appearance { + target.appearance.clone_from(appearance); + } + if left.opacity != *opacity { + target.opacity = *opacity; + } + if left.blend != *blend { + target.blend = *blend; + } + if left.style != *style { + target.style.clone_from(style); + } + if left.inherited != *inherited { + target.inherited = *inherited; + } +} + /// The selection a drag began with, without the objects that a command run during it removed, /// hid or locked in `doc`. fn drag_selection(began: &Selection, doc: &Document) -> Selection { diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 90f5f024dd..94b943120a 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -132,6 +132,9 @@ impl Session { if self.script_in_run && self.depth > 0 && r.is_ok() { crate::script::note_style_lists(self); } + if self.depth == 0 { + self.plugin_events_after_command(); + } r } diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 5991d656ee..afaf70b090 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -1319,11 +1319,13 @@ impl Session { } /// Installs what `load` has loaded so far, without waiting, in `turn`. + /// Records the installed plug-ins' event baseline now, or after an open interaction ends. fn install_plugin_load(&mut self, load: &mut PluginLoad, turn: &StoreTurn) { match load { PluginLoad::Stored(load) => self.install_stored_plugins(load, turn), PluginLoad::Folder(load) => crate::cmd::plugin::install_folder(self, load, turn), } + self.plugins_changed_for_events(); } /// Ends `load` once [`PluginLoad::done`], in `turn` → its report. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index edb9a1e631..0e6269d511 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -154,6 +154,7 @@ mod perspgrid; mod pixelalign; mod place; mod placed_document; +mod plugin_events; mod plugins; mod prefs; mod prefs_file; @@ -184,13 +185,19 @@ mod script_dialogs; mod script_dollar; mod script_dom; mod script_dom_defaults; +mod script_dom_images; mod script_dom_paths; +mod script_dom_prefs; +mod script_dom_tracing; +mod script_dom_transform; mod script_engines; mod script_folder; mod script_include; mod script_io; mod script_modules; +mod script_palettes; mod script_print; +mod script_raster_capture; mod script_run; mod script_save_open; mod script_scriptui; @@ -5183,6 +5190,39 @@ fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() { assert!(!s.doc().unwrap().selection.contains(b)); } +/// The selection commands and Curvature edits refuse a mode or op they do not know, and leave the +/// selection, the document and the undo history as they were. +#[test] +fn an_unknown_selection_mode_or_curvature_op_is_refused_without_changes() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 30.0, 20.0); + let b = rect(&mut s, 50.0, 10.0, 30.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let objects = s.doc().unwrap().selection.objects.clone(); + let anchors = s.doc().unwrap().selection.anchors.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let mut wrong = vec![]; + for (cmd, p, says) in [ + ("select.segments", json!({"id": a.0, "segments": [[0, 0]], "mode": "bogus"}), "unknown mode"), + ("select.anchorsMany", json!({"items": [{"id": a.0, "anchors": [[0, 0]]}], "mode": "bogus"}), "unknown mode"), + ("select.magicWand", json!({"id": a.0, "mode": "bogus"}), "unknown mode"), + ("path.curvatureEdit", json!({"id": a.0, "op": "bogus", "anchor": 0, "x": 0, "y": 0}), "unknown op"), + ] { + match s.execute(cmd, &p) { + Err(e) if e.to_string().contains(says) => {} + other => wrong.push(format!("{cmd}: {other:?}")), + } + let st = s.doc().unwrap(); + let changed = st.selection.objects != objects || st.selection.anchors != anchors || st.doc != doc || st.history.undo.len() != undo; + if changed { + wrong.push(format!("{cmd} changed the selection, the document or the undo history")); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + /// #1232: through the session, Direct Selection's corner widgets pick corners across paths. With /// a corner of `a` picked and `b` selected whole, a Shift-click on a widget of `b` deselects that /// corner and keeps `b`'s other corners and `a`'s pick; one on a widget of `a` that is not picked diff --git a/crates/engine/src/tests/anchor_edit_work.rs b/crates/engine/src/tests/anchor_edit_work.rs index 38bb94a6f3..c640c08e26 100644 --- a/crates/engine/src/tests/anchor_edit_work.rs +++ b/crates/engine/src/tests/anchor_edit_work.rs @@ -225,6 +225,7 @@ fn a_linked_handle_makes_the_anchor_smooth() { json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": 1}), json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": true}), json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": "no"}), + json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "symmetric": true}), json!({"id": id.0, "anchor": 100, "which": "out", "x": 0, "y": 0, "link": true}), json!({"id": id.0, "anchor": 7, "which": "out", "x": 1.7e308, "y": 1.7e308, "link": true}), json!({"id": id.0, "anchor": 7, "which": "out", "x": 0, "y": -1e9, "link": true}), diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index b967e6e3ed..8cb96c6a8a 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -888,6 +888,44 @@ fn apply_reports_the_index_in_the_object_whose_row_it_names() { assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(1)), "a's row 0 holds two effects"); } +#[test] +fn aligned_effect_move_uses_the_shared_fill_or_stroke_in_each_target() { + let mut s = session(); + let (a, b) = reversed_pair(&mut s); + for (id, item) in [(a, 1), (b, 2)] { + for effect in ["distort.twist", "distort.roughen"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "item": item, "effect": effect})); + } + } + run(&mut s, "select.set", json!({"ids": [b.0, a.0]})); + let appearances = |s: &Session| [a, b].map(|id| node(s, id).appearance.clone()); + let before = appearances(&s); + for (params, reply_item) in [(json!({"from": 1, "to": 0, "aligned": true}), 2), (json!({"from": 1, "to": 0, "toItem": 1, "aligned": true}), 1)] { + run(&mut s, "appearance.setActiveItem", json!({"index": 2})); + let moved = run(&mut s, "effect.move", params); + assert_eq!(moved["item"], json!(reply_item), "the reply addresses the destination's anchor"); + assert_eq!(moved["index"], json!(0)); + for (appearance, item) in appearances(&s).iter().zip([1, 2]) { + let ids: Vec<_> = appearance.effects_at(Some(item)).unwrap().iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, ["distort.roughen", "distort.twist"]); + assert!(appearance.effects_at(Some(0)).unwrap().is_empty()); + } + run(&mut s, "edit.undo", json!({})); + assert_eq!(appearances(&s), before); + } + + run(&mut s, "appearance.setActiveItem", json!({"index": 2})); + for destination in [0, 2] { + assert!(s.execute("effect.move", &json!({"from": 1, "to": 0, "toItem":destination, "aligned":true})).is_err()); + assert_eq!(appearances(&s), before, "a different or invalid destination must not change either list"); + } + + run(&mut s, "effect.apply", json!({"ids": [a.0], "item": 1, "effect": "stylize.feather"})); + let before = appearances(&s); + assert!(s.execute("effect.move", &json!({"ids": [b.0, a.0], "fromItem": 2, "from": 1, "to": 0, "aligned": true})).is_err()); + assert_eq!(appearances(&s), before, "no effect moves if a target lacks the shared row"); +} + /// `effect.move`'s reply names where the effect landed in the object whose row the active item is /// (the first selected object), also when that object paints above the others. #[test] diff --git a/crates/engine/src/tests/arrowheads.rs b/crates/engine/src/tests/arrowheads.rs index 0cdc3312ff..656f034be7 100644 --- a/crates/engine/src/tests/arrowheads.rs +++ b/crates/engine/src/tests/arrowheads.rs @@ -444,3 +444,20 @@ fn a_group_used_as_the_clipping_path_adds_none_of_its_own_fills() { let b = read.heads[0].path.bounds().unwrap(); assert!((b.width() - 4.0).abs() < 1e-3 && (b.height() - 4.0).abs() < 1e-3, "the square alone: {b:?}"); } + +/// An arrowheads file over the size limit is refused from its size: no heads are listed, and the +/// error says why. +#[test] +fn an_arrowheads_file_over_the_size_limit_lists_no_heads() { + let dir = folder("too-big"); + let file = dir.join(arrowheads::FILE_NAME); + // Sparse: no data blocks are written. + std::fs::File::create(&file).unwrap().set_len(arrowheads::MAX_FILE_BYTES + 1).unwrap(); + let (mut s, _) = session_with_line(); + s.attach_arrowheads_file(file.to_string_lossy().to_string()); + let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(list["arrowheads"], json!([])); + let error = list["error"].as_str().unwrap_or_default(); + assert!(error.contains(&format!("larger than {} MB", arrowheads::MAX_FILE_BYTES >> 20)), "{list}"); +} diff --git a/crates/engine/src/tests/blendspine.rs b/crates/engine/src/tests/blendspine.rs index 7f7c7fffa4..88a5c7b4b1 100644 --- a/crates/engine/src/tests/blendspine.rs +++ b/crates/engine/src/tests/blendspine.rs @@ -456,6 +456,7 @@ fn a_linked_spine_handle_makes_the_point_smooth() { for bad in [ json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": "yes"}), json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true, "independent": true}), + json!({"anchor": 1, "handle": "out", "x": 60, "y": 40, "link": true, "symmetric": true}), json!({"anchor": 1, "x": 75, "y": 25, "link": true}), ] { assert!(s.execute("object.blend.spine.moveAnchor", &bad).is_err(), "{bad}"); diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 7b72a06089..c9126f5f52 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -1870,6 +1870,51 @@ fn front_and_back_beside_a_compound_paths_member_go_beside_the_compound_path() { assert_eq!(members(&s), [before[0], path[0], before[1]]); } +/// The ids of `n`, its members and its opacity-mask art, in depth. +fn ids_in(n: &Node, out: &mut Vec) { + out.push(n.id); + n.children().into_iter().flatten().for_each(|c| ids_in(c, out)); + if let Some(m) = n.extras().mask.as_deref() { + ids_in(&m.art, out); + } +} + +#[test] +fn a_copied_member_of_a_compound_path_pastes_with_its_transparency_and_opacity_mask() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0); + let b = rect(&mut s, 10.0, 0.0, 40.0, 40.0); + sel(&mut s, &[a, b]); + let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let art = rect(&mut s, 5.0, 5.0, 20.0, 20.0); + sel(&mut s, &[c, art]); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("transparency.setOpacityMask", &json!({"ids": [c.0], "invert": true})).unwrap(); + let set = json!({"ids": [c.0], "opacity": 30, "blend": "screen", "isolate": true, "knockout": "on"}); + s.execute("object.setProps", &set).unwrap(); + let member = node(&s, c).children().unwrap()[0].id; + copy(&mut s, &[member]); + s.execute("edit.paste", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects.clone(); + assert_eq!(pasted.len(), 1); + let p = node(&s, pasted[0]); + assert!(matches!(p.kind, NodeKind::Path { .. }), "the member pastes as a path"); + assert!((p.opacity - 0.3).abs() < 1e-6, "opacity {}", p.opacity); + assert_eq!(p.blend, vectorcraft_color::BlendMode::Screen); + assert!(p.isolate, "Isolate Blending"); + assert_eq!(p.knockout, vectorcraft_doc::Knockout::On, "Knockout Group"); + let m = p.extras().mask.as_deref().expect("the pasted path has the compound path's opacity mask"); + assert!(m.invert, "Invert Mask comes along"); + assert_ne!(m.art.id, art, "the pasted mask art has an id of its own"); + // Every id in the document, mask art included, is used once. + let mut ids = vec![]; + doc(&s).layers.iter().for_each(|l| ids_in(l, &mut ids)); + let count = ids.len(); + ids.sort_by_key(|i| i.0); + ids.dedup(); + assert_eq!(ids.len(), count, "ids are unique"); +} + #[test] fn paste_in_back_of_a_clipping_path_keeps_it_the_clipping_path() { let mut s = session(); diff --git a/crates/engine/src/tests/compoundpaint.rs b/crates/engine/src/tests/compoundpaint.rs index 4e22e31d3f..ffcc542e8a 100644 --- a/crates/engine/src/tests/compoundpaint.rs +++ b/crates/engine/src/tests/compoundpaint.rs @@ -2,7 +2,8 @@ //! compound holds the paint, so a member's own appearance is never drawn. use serde_json::{Value, json}; -use vectorcraft_color::Paint; +use vectorcraft_color::{BlendMode, Paint}; +use vectorcraft_doc::Knockout; use crate::*; @@ -87,3 +88,126 @@ fn a_group_with_a_compound_still_paints_the_compound_once() { assert_eq!(paint(&s, compound, false), solid("#ff0000")); assert_eq!(paint(&s, loose, false), solid("#ff0000")); } + +/// The opacity, blend mode, Isolate Blending, Knockout Group and Knockout Shape of `id`. +fn transparency(s: &Session, id: NodeId) -> (f32, BlendMode, bool, Knockout, bool) { + let n = s.doc().unwrap().doc.node(id).unwrap(); + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) +} + +/// The id and the clip and invert settings of `id`'s opacity mask, `None` when it has none. +fn mask(s: &Session, id: NodeId) -> Option<(NodeId, bool, bool)> { + let n = s.doc().unwrap().doc.node(id).unwrap(); + n.extras().mask.as_deref().map(|m| (m.art.id, m.clip, m.invert)) +} + +/// An opacity mask made from a new rectangle for `id`, with Invert Mask on → the mask art's id. +fn give_mask(s: &mut Session, id: NodeId) -> NodeId { + let art = rect(s, 5.0); + run(s, "select.set", json!({"ids": [id.0, art.0]})); + run(s, "transparency.makeOpacityMask", json!({})); + run(s, "transparency.setOpacityMask", json!({"ids": [id.0], "invert": true})); + art +} + +#[test] +fn release_gives_each_path_the_compound_paths_transparency() { + let (mut s, compound, members, _) = compound(); + let set = json!({"ids": [compound.0], "opacity": 50, "blend": "multiply", "isolate": true, "knockout": "on", "knockoutShape": true}); + run(&mut s, "object.setProps", set); + run(&mut s, "select.set", json!({"ids": [compound.0]})); + run(&mut s, "object.compoundPath.release", json!({})); + let released = s.doc().unwrap().selection.objects.clone(); + assert_eq!(released, members); + for id in released { + assert_eq!(transparency(&s, id), (0.5, BlendMode::Multiply, true, Knockout::On, true), "path {id:?}"); + assert_eq!(paint(&s, id, true), solid("#000000")); + } +} + +#[test] +fn release_gives_each_path_the_compound_paths_opacity_mask() { + let (mut s, compound, members, _) = compound(); + let art = give_mask(&mut s, compound); + run(&mut s, "select.set", json!({"ids": [compound.0]})); + run(&mut s, "object.compoundPath.release", json!({})); + // The mask art is in document coordinates, so each path masked by it draws as its part of the + // masked compound path did. The first path keeps the art; the others get copies with ids of + // their own, since stored art is in the document once. + let masks: Vec<_> = members.iter().map(|id| mask(&s, *id)).collect(); + assert_eq!(masks[0], Some((art, true, true))); + let (copy, clip, invert) = masks[1].unwrap(); + assert!((clip, invert) == (true, true) && copy != art, "{masks:?}"); + let geometry = |id: NodeId, art: NodeId| { + let n = s.doc().unwrap().doc.node(id).unwrap(); + let m = n.extras().mask.as_deref().unwrap(); + assert_eq!(m.art.id, art); + m.art.geometric_bounds() + }; + assert_eq!(geometry(members[0], art), geometry(members[1], copy)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(mask(&s, compound), Some((art, true, true)), "one undo step gives the compound path its mask back"); +} + +#[test] +fn make_takes_the_backmost_objects_transparency_and_release_gives_it_back() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 100})); + let (back, front) = (rect(&mut s, 0.0), rect(&mut s, 10.0)); + run(&mut s, "object.setProps", json!({"ids": [back.0], "opacity": 50, "blend": "screen", "knockout": "off"})); + run(&mut s, "object.setProps", json!({"ids": [front.0], "opacity": 80})); + run(&mut s, "select.set", json!({"ids": [back.0, front.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + assert_eq!(transparency(&s, compound), (0.5, BlendMode::Screen, false, Knockout::Off, false)); + run(&mut s, "object.compoundPath.release", json!({})); + for id in [back, front] { + assert_eq!(transparency(&s, id), (0.5, BlendMode::Screen, false, Knockout::Off, false), "path {id:?}"); + } +} + +#[test] +fn make_takes_the_backmost_objects_opacity_mask() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 100})); + let (back, front) = (rect(&mut s, 0.0), rect(&mut s, 10.0)); + let art = give_mask(&mut s, back); + run(&mut s, "select.set", json!({"ids": [back.0, front.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + assert_eq!(mask(&s, compound), Some((art, true, true))); + // The backmost path gives its mask to the compound path rather than keeping a second one. + assert_eq!(mask(&s, back), None); + run(&mut s, "edit.undo", json!({})); + assert_eq!(mask(&s, back), Some((art, true, true)), "one undo step gives the path its mask back"); +} + +#[test] +fn make_from_a_group_takes_the_groups_transparency() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 100})); + let (back, front) = (rect(&mut s, 0.0), rect(&mut s, 10.0)); + run(&mut s, "object.setProps", json!({"ids": [back.0], "opacity": 80})); + run(&mut s, "select.set", json!({"ids": [back.0, front.0]})); + let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "object.setProps", json!({"ids": [group.0], "opacity": 50, "blend": "multiply"})); + let art = give_mask(&mut s, group); + run(&mut s, "select.set", json!({"ids": [group.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + // The group's 50% applied to the backmost path's 80%. + assert_eq!(transparency(&s, compound), (0.4, BlendMode::Multiply, false, Knockout::Neutral, false)); + assert_eq!(mask(&s, compound), Some((art, true, true))); +} + +#[test] +fn release_of_an_unmasked_compound_path_keeps_a_front_paths_own_mask() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 100})); + let (back, front) = (rect(&mut s, 0.0), rect(&mut s, 10.0)); + let art = give_mask(&mut s, front); + run(&mut s, "select.set", json!({"ids": [back.0, front.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + assert_eq!(mask(&s, compound), None); + run(&mut s, "select.set", json!({"ids": [compound.0]})); + run(&mut s, "object.compoundPath.release", json!({})); + assert_eq!(mask(&s, front), Some((art, true, true))); + assert_eq!(mask(&s, back), None); +} diff --git a/crates/engine/src/tests/css.rs b/crates/engine/src/tests/css.rs index 39fb6a5bc2..982bf51d24 100644 --- a/crates/engine/src/tests/css.rs +++ b/crates/engine/src/tests/css.rs @@ -43,6 +43,34 @@ fn a_rounded_rectangle_gives_background_border_and_radius() { assert!(s.execute("css.selection", &json!({"units": "furlong"})).is_err(), "unknown units are refused"); } +#[test] +fn round_dots_are_a_dotted_border_without_a_note() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 120, "height": 60})); + run(&mut s, "paint.setStroke", json!({"color": "#000000"})); + run(&mut s, "stroke.set", json!({"cap": "round", "dash": [0, 4]})); + let r = run(&mut s, "css.selection", json!({})); + assert!(css(&r).contains("border: 1px dotted #000000;"), "{}", css(&r)); + assert!(r["rules"][0].get("unsupported").is_none(), "{r}"); + // Squares, dots fitted to corners, dots mixed with dashes and unevenly spaced dots are not what + // `dotted` draws. + let others = [json!({"cap": "projecting"}), json!({"alignDashes": true}), json!({"dash": [0, 4, 6, 4]}), json!({"dash": [0, 4, 0, 40]})]; + for p in others { + run(&mut s, "stroke.set", json!({"cap": "round", "dash": [0, 4], "alignDashes": false})); + run(&mut s, "stroke.set", p.clone()); + let r = run(&mut s, "css.selection", json!({})); + assert!(r["rules"][0].get("unsupported").is_some(), "{p}: {r}"); + } + // A gradient border image draws the border whole, without its dots or dashes. + run(&mut s, "paint.setStroke", json!({"gradient": {"kind": "linear"}})); + for dash in [json!([0, 4]), json!([4, 2])] { + run(&mut s, "stroke.set", json!({"cap": "round", "dash": dash, "alignDashes": false})); + let r = run(&mut s, "css.selection", json!({})); + assert!(css(&r).contains("border-image: linear-gradient("), "{}", css(&r)); + assert_eq!(r["rules"][0]["unsupported"], json!("dashes or dots on a gradient border"), "{dash}"); + } +} + #[test] fn type_gives_font_properties_and_gradients_css_gradients() { let mut s = session(); @@ -79,6 +107,48 @@ fn gradients_mixed_around_the_hue_wheel_give_css_the_stops_on_their_way() { } } +/// A round-capped dash that starts with a 0 length is a dotted border, any other dash a dashed +/// one, and a gradient stroke a border with a `border-image`. +#[test] +fn dashed_dotted_and_gradient_strokes_give_border_styles() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 120, "height": 60})); + run(&mut s, "paint.setStroke", json!({"color": "#000000"})); + let border = |s: &mut Session| { + let text = css(&run(s, "css.selection", json!({}))).to_string(); + let line = text.lines().find(|l| l.trim_start().starts_with("border:")).unwrap_or_else(|| panic!("a border in {text}")).trim().to_string(); + (line, text) + }; + run(&mut s, "stroke.set", json!({"weight": 1, "cap": "round", "dash": [0, 4]})); + let (line, text) = border(&mut s); + assert_eq!(line, "border: 1px dotted #000000;", "{text}"); + run(&mut s, "stroke.set", json!({"cap": "butt", "dash": [6, 3]})); + assert_eq!(border(&mut s).0, "border: 1px dashed #000000;"); + run(&mut s, "stroke.set", json!({"dash": null})); + run(&mut s, "paint.setStroke", json!({"gradient": {"kind": "linear"}})); + let (line, text) = border(&mut s); + assert_eq!(line, "border: 1px solid;", "{text}"); + let image = text.lines().find(|l| l.trim_start().starts_with("border-image:")).unwrap_or_else(|| panic!("a border-image in {text}")); + assert!(image.contains("linear-gradient(") && image.trim_end().ends_with(" 1;"), "{image}"); +} + +/// A pen-drawn upright rectangle is written as a rectangle: a background with square corners. The +/// same path turned is not, and gets the note for a shape CSS cannot draw. +#[test] +fn a_drawn_upright_rectangle_is_a_rectangle_and_a_turned_one_is_not() { + let mut s = session(); + let id = run(&mut s, "path.create", json!({"d": "M10 20 H130 V80 H10 Z"}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"color": "#3366cc"})); + let r = run(&mut s, "css.selection", json!({"ids": [id]})); + let text = css(&r); + assert!(text.contains("background-color: #3366cc;"), "{text}"); + assert!(!text.contains("border-radius"), "{text}"); + assert!(r["rules"][0].get("unsupported").is_none(), "{r}"); + run(&mut s, "object.rotate", json!({"angle": 30})); + let r = run(&mut s, "css.selection", json!({"ids": [id]})); + assert_eq!(r["rules"][0]["unsupported"], json!("a shape other than a rectangle or an ellipse"), "{r}"); +} + #[test] fn generate_covers_the_document_and_an_empty_selection_has_none() { let mut s = session(); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 516e4fb3b0..3be402bb94 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -6802,6 +6802,80 @@ fn join_two_subpaths_of_same_path_node() { assert_eq!(pd.subpaths[0].anchors[3].p, Point::new(250.0, 0.0)); } +/// A path with one open two-anchor subpath per pair of points. +fn path_of_lines(s: &mut Session, lines: &[[Point; 2]]) -> NodeId { + let p = line(s, lines[0][0].x, lines[0][0].y, lines[0][1].x, lines[0][1].y); + let rest: Vec<_> = lines[1..].iter().map(|l| vectorcraft_geom::SubPath::polyline(l, false)).collect(); + s.edit("Add Subpaths", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(p).unwrap().kind { + path.subpaths.extend(rest); + } + Ok(()) + }) + .unwrap(); + p +} + +fn subpath_points(s: &Session, id: NodeId) -> Vec> { + path(s, id).subpaths.iter().map(|sp| sp.anchors.iter().map(|a| a.p).collect()).collect() +} + +/// `path.join` with the same id twice and `subpaths` joins two subpaths of one path. Here the later +/// subpath comes first, so the earlier one is removed and the joined subpath takes the later one's +/// place, the coincident junction anchors become one, and the subpath between them stays as it was. +/// One undo step brings back all three subpaths. +#[test] +fn join_of_one_path_by_ids_and_subpaths_merges_the_junction_and_keeps_the_other_subpath() { + let mut s = session(); + let pt = Point::new; + let p = path_of_lines(&mut s, &[[pt(100.0, 0.0), pt(110.0, 0.0)], [pt(500.0, 0.0), pt(510.0, 0.0)], [pt(0.0, 0.0), pt(100.0, 0.0)]]); + let before = subpath_points(&s, p); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("path.join", &json!({"ids": [p.0, p.0], "subpaths": [2, 0], "ends": ["last", "first"]})).unwrap(); + + assert_eq!(subpath_points(&s, p), vec![vec![pt(500.0, 0.0), pt(510.0, 0.0)], vec![pt(0.0, 0.0), pt(100.0, 0.0), pt(110.0, 0.0)]]); + assert!(path(&s, p).subpaths.iter().all(|sp| !sp.closed)); + assert_eq!(s.doc().unwrap().selection.objects, vec![p]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(subpath_points(&s, p), before); +} + +/// With both ends of one open subpath direct-selected, Join closes that subpath and leaves the +/// other open subpath of the same path as it is, instead of joining the two. +#[test] +fn join_with_both_ends_of_one_subpath_selected_closes_that_subpath() { + let mut s = session(); + let pt = Point::new; + let p = path_of_lines(&mut s, &[[pt(0.0, 0.0), pt(100.0, 0.0)], [pt(0.0, 50.0), pt(100.0, 50.0)]]); + s.execute("select.anchors", &json!({"id": p.0, "anchors": [[1, 0], [1, 1]], "mode": "set"})).unwrap(); + s.execute("path.join", &json!({})).unwrap(); + + assert_eq!(subpath_points(&s, p), vec![vec![pt(0.0, 0.0), pt(100.0, 0.0)], vec![pt(0.0, 50.0), pt(100.0, 50.0)]]); + let pd = path(&s, p); + assert!(!pd.subpaths[0].closed, "the other subpath stays open"); + assert!(pd.subpaths[1].closed, "the subpath with both ends selected is closed"); +} + +/// With both ends of one line selected and only the first end of another, Join takes the nearest +/// pair of selected ends: the second line's unselected end is nearer but is not joined. +#[test] +fn join_with_both_ends_of_one_line_selected_takes_the_nearest_selected_pair() { + let mut s = session(); + let pt = Point::new; + let a = line(&mut s, 0.0, 0.0, 100.0, 0.0); + let b = line(&mut s, 300.0, 0.0, 105.0, 0.0); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + s.execute("path.join", &json!({})).unwrap(); + + let joined = paths(&s); + assert_eq!(joined.len(), 1, "{joined:?}"); + let pts: Vec = joined[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(pts, vec![pt(0.0, 0.0), pt(100.0, 0.0), pt(300.0, 0.0), pt(105.0, 0.0)]); +} + /// Direct-selecting 2 open endpoints in a complex compound path with multiple open segments joins only those 2. #[test] fn join_complex_compound_path_direct_endpoints() { diff --git a/crates/engine/src/tests/editcolors.rs b/crates/engine/src/tests/editcolors.rs index a42f2c4ca7..1539ece240 100644 --- a/crates/engine/src/tests/editcolors.rs +++ b/crates/engine/src/tests/editcolors.rs @@ -70,6 +70,21 @@ fn balance_previews_and_commits_one_step() { assert_eq!(fill_of(&s, a).to_hex(), "#808080"); } +/// An `objectOnly` paint during an open interaction keeps the remembered colors: the paint it would +/// leave waiting for the commit is not added to Recent Colors when the interaction commits. +#[test] +fn object_only_paint_in_an_interaction_keeps_recent_colors() { + let mut s = session(); + let a = rect(&mut s, json!("#808080")); + s.recent_colors.clear(); + let recent = (s.recent_colors.clone(), s.last_solid); + s.begin_interaction("Adjust Colors").unwrap(); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000", "objectOnly": true})).unwrap(); + assert_eq!(fill_of(&s, a).to_hex(), "#ff0000"); + s.commit_interaction().unwrap(); + assert_eq!((s.recent_colors.clone(), s.last_solid), recent, "the recent colors are as they were"); +} + /// Saturate needs its intensity: a call without one, or with one that is not a number, is an error /// that changes nothing and records no undo step. A number outside −100..100 counts as its nearest end. #[test] diff --git a/crates/engine/src/tests/flatten.rs b/crates/engine/src/tests/flatten.rs index 042f741e0e..959c58e9f3 100644 --- a/crates/engine/src/tests/flatten.rs +++ b/crates/engine/src/tests/flatten.rs @@ -350,6 +350,41 @@ fn gradients_rasterize_and_flat_areas_stay_vector() { } } +/// A rasterized area is stored as a PNG written with fast compression: its zlib header (RFC 1950) +/// gives compression level 0, the fastest. +#[test] +fn rasterized_areas_are_png_with_fast_compression() { + let _settings = settings_lock(); + let mut s = session(); + let g = rect(&mut s, 10.0, 10.0, 100.0, 100.0, "#000000"); + run( + &mut s, + "paint.setFill", + json!({"ids": [g], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ); + run(&mut s, "transparency.set", json!({"ids": [g], "opacity": 40})); + let (ids, _, rasterized) = flatten(&mut s, json!({"ids": [g], "preset": "high"})); + assert_eq!(rasterized, 1); + let mut keys = vec![]; + node(&s, ids[0]).walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind { + keys.push(im.key.clone()); + } + }); + let [key] = &keys[..] else { panic!("one image: {keys:?}") }; + let png = &s.doc().unwrap().doc.images[key].bytes; + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG"); + let mut at = 8; + let level = loop { + let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) else { panic!("a PNG with image data") }; + if kind == b"IDAT" { + break png[at + 9] >> 6; + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + }; + assert_eq!(level, 0, "zlib FLEVEL of the stored PNG"); +} + #[test] fn a_long_rasterized_area_is_placed_whole() { let _settings = settings_lock(); diff --git a/crates/engine/src/tests/fontfiles.rs b/crates/engine/src/tests/fontfiles.rs index e90aec1df9..fc8d72ead2 100644 --- a/crates/engine/src/tests/fontfiles.rs +++ b/crates/engine/src/tests/fontfiles.rs @@ -143,8 +143,8 @@ fn the_fonts_folder_next_to_a_document_is_an_absolute_path() { let (_dir, root) = folder("relative"); std::fs::create_dir_all(root.join("pkg/Fonts")).unwrap(); let cwd = std::env::current_dir().unwrap(); - let up = "../".repeat(cwd.components().count().saturating_sub(1)); - let relative = format!("{up}{}", root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap().display()); + let up: PathBuf = cwd.components().skip(1).map(|_| std::path::Component::ParentDir).collect(); + let relative = up.join(root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap()).display().to_string(); assert!(Path::new(&relative).is_relative()); let mut s = session_for(&root); let mut doc = vectorcraft_doc::Document::new(100.0, 100.0); diff --git a/crates/engine/src/tests/halftone.rs b/crates/engine/src/tests/halftone.rs index d836502baa..c7ec58549c 100644 --- a/crates/engine/src/tests/halftone.rs +++ b/crates/engine/src/tests/halftone.rs @@ -66,6 +66,65 @@ fn halftone_options() { } } +/// The dot path Vector Halftone makes from a gray square with `params`. +fn dots_of(params: serde_json::Value) -> vectorcraft_geom::PathData { + let mut s = session(); + red_rect(&mut s); + s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap(); + let r = s.execute("object.vectorHalftone", ¶ms).unwrap(); + let g = node(&s, NodeId(r["id"].as_u64().unwrap())); + g.children().unwrap()[0].path_data().unwrap().clone() +} + +#[test] +fn halftone_styles_set_the_shape_and_angle_unless_given() { + assert_eq!(dots_of(json!({"frequency": 18, "style": "gridDots"})), dots_of(json!({"frequency": 18, "shape": "circle", "angle": 0}))); + assert_eq!(dots_of(json!({"frequency": 18, "style": "gridAngle"})), dots_of(json!({"frequency": 18, "shape": "euclidean", "angle": 45}))); + assert_ne!(dots_of(json!({"frequency": 18, "style": "grid"})), dots_of(json!({"frequency": 18}))); + // A given shape or angle wins over the style's. + assert_eq!(dots_of(json!({"frequency": 18, "style": "grid", "shape": "circle"})), dots_of(json!({"frequency": 18, "angle": 0}))); + assert_ne!(dots_of(json!({"frequency": 18, "style": "grid", "shape": "circle"})), dots_of(json!({"frequency": 18, "style": "grid"}))); + assert_eq!(dots_of(json!({"frequency": 18, "style": "gridDots", "angle": 45})), dots_of(json!({"frequency": 18, "style": "gridDotsAngle"}))); + // An unknown style is refused and leaves the document as it was. + let mut s = session(); + red_rect(&mut s); + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("object.vectorHalftone", &json!({"style": "checker"})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); +} + +#[test] +fn halftone_refuses_null_and_non_string_styles() { + for style in [json!(null), json!(42), json!(true), json!([]), json!({})] { + let mut s = session(); + red_rect(&mut s); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let result = s.execute("object.vectorHalftone", &json!({"style": style})); + assert!(matches!(result, Err(EngineError::BadParams { .. })), "{style}: {result:?}"); + assert_eq!(s.doc().unwrap().doc, before, "{style}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{style}"); + } + assert_eq!(dots_of(json!({"style": "custom"})), dots_of(json!({}))); +} + +/// The live effect refuses an unknown style when applied or edited, and leaves the document as it +/// was; a known style in another letter case is taken. +#[test] +fn halftone_effect_refuses_an_unknown_style() { + const HALFTONE: &str = "addon.color.halftone"; + let mut s = session(); + red_rect(&mut s); + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"style": "gridDot"}})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); + s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"style": "GRIDDOTS"}})).unwrap(); + let applied = s.doc().unwrap().doc.clone(); + assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"style": "gridDot"}})).is_err()); + assert_eq!(s.doc().unwrap().doc, applied); + s.execute("effect.setParams", &json!({"index": 0, "params": {"style": "custom"}})).unwrap(); +} + #[test] fn halftone_refuses_a_param_of_the_wrong_type() { for bad in [ diff --git a/crates/engine/src/tests/interaction_commands.rs b/crates/engine/src/tests/interaction_commands.rs index d0d12cce94..00588ecf0c 100644 --- a/crates/engine/src/tests/interaction_commands.rs +++ b/crates/engine/src/tests/interaction_commands.rs @@ -808,6 +808,25 @@ fn a_fill_chosen_during_a_bucket_drag_stays() { } } +/// With New Art Has Basic Appearance off, a fill chosen during a rectangle drag from an empty +/// selection is the fill the drag's next preview and its release draw with. +#[test] +fn a_fill_chosen_during_a_rectangle_drag_draws_the_rectangle() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, _) = session(real_time); + s.prefs.new_art_basic = false; + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": []})).unwrap(); + let blue = s.paint.fill.clone(); + pointer(&mut s, PointerKind::Drag, 200.0, 180.0); + pointer(&mut s, PointerKind::Up, 200.0, 180.0); + let drawn = s.doc().unwrap().selection.objects[0]; + assert_eq!(s.doc().unwrap().doc.node(drawn).unwrap().appearance.fill_paint(), blue, "{at}"); + } +} + /// A command run during a Quick Pen press still runs inside the press, so it records no undo /// step of its own while the press is held. #[test] diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index 0b35b2f772..35f86fa582 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -966,6 +966,45 @@ fn canceling_an_undo_group_keeps_a_batchs_steps_in_other_documents() { assert_eq!(r.active_index(), s.active_index()); } +/// A batch step in the canceled group that leaves another document in front (switching to the +/// grouped document measures its type again in its own composite font) is dropped from the batch's +/// journal entry and replaced by that switch, so the edit made after the group replays in the +/// document it was made in. +#[test] +fn canceling_an_undo_group_keeps_the_switch_of_a_dropped_batch_step() { + let mut s = Session::new(); + let fonts = |size: i32| { + let parts = json!({"kanji": {"font": "Source Sans 3"}, "roman": {"font": "JetBrains Mono", "size": size}}); + json!({"fonts": [{"name": "CF Undo Group", "parts": parts}]}) + }; + s.execute("file.new", &json!({"created": null})).unwrap(); + s.execute("type.compositeFonts.set", &fonts(50)).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab", "size": 20, "font": "CF Undo Group"})).unwrap(); + s.execute("file.new", &json!({"created": null})).unwrap(); + s.execute("type.compositeFonts.set", &fonts(75)).unwrap(); + let objects = |s: &Session| s.documents().iter().map(|d| d.doc.node_count()).collect::>(); + let before = objects(&s); + let activate = |index: usize| json!({"command": "document.activate", "params": {"index": index}}); + let steps = json!([rect_step(10), activate(0)]); + for (id, p) in [ + ("document.activate", json!({"index": 0})), + ("edit.undoGroup.begin", json!({})), + ("shape.rectangle", rect_step(50)["params"].clone()), + ("document.activate", json!({"index": 1})), + ("command.batch", json!({ "commands": steps })), + ("edit.undoGroup.end", json!({"cancel": true})), + ("shape.rectangle", rect_step(30)["params"].clone()), + ] { + s.execute(id, &p).unwrap(); + } + assert_eq!(objects(&s), vec![before[0] + 1, before[1] + 1]); + let (_, batch) = s.journal.iter().find(|(id, _)| id == "command.batch").unwrap(); + assert_eq!(batch["commands"], json!([steps[0], activate(0)])); + let r = replayed(&s); + assert_eq!(documents(&r), documents(&s)); + assert_eq!(r.active_index(), s.active_index()); +} + /// The edits made in an undo group (a scrubbed numeric field, #400) are one undo step, journaled /// one by one; a cancelled group undoes them and leaves the journal as it was. #[test] @@ -1074,6 +1113,25 @@ fn an_undo_group_begun_by_command_opens_in_each_document_created_before_its_end( assert!(s.doc().unwrap().undo_group.is_none()); } +/// Between `edit.undoGroup.begin` and `edit.undoGroup.end`, a document added outside a command (a +/// template the app opens itself) opens an undo group with the begun group's name too: its edits are +/// one undo step there. +#[test] +fn an_undo_group_begun_by_command_opens_in_a_document_added_outside_a_command() { + let mut s = Session::new(); + let rect = json!({"x": 10, "y": 10, "width": 100, "height": 50}); + let labels = |s: &Session| s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect::>(); + let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + s.execute("edit.undoGroup.begin", &json!({"label": "Job"})).unwrap(); + s.add_document(vectorcraft_doc::Document::new(400.0, 300.0), None); + s.execute("shape.rectangle", &rect).unwrap(); + s.execute("shape.ellipse", &rect).unwrap(); + s.execute("edit.undoGroup.end", &json!({})).unwrap(); + assert_eq!(labels(&s), ["Job"]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(objects(&s), 0, "one undo takes back both edits"); +} + /// Between `edit.undoGroup.begin` and `edit.undoGroup.end`, a command that creates a document and /// edits it (a `command.batch`) keeps its edits as an undo step of its own in that document, and the /// edits after it are the group's step. A cancel undoes only those, keeps the document and the diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index e2ea567acd..b105a3fd90 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -1020,6 +1020,31 @@ fn moves_are_validated() { assert_eq!(parent(&s, sub), None); } +/// `node.move` keeps a clip group's clipping path at its bottom: the path does not leave the group +/// or move up in it, and a row moved to index 0 goes directly above it. +#[test] +fn node_move_keeps_a_clip_groups_clipping_path_at_the_bottom() { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 30.0), rect(&mut s, 60.0)); + let layer = parent(&s, a).unwrap(); + run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]})); + let g = id(&run(&mut s, "object.clippingMask.make", json!({}))); + let before = children(&s, g); + let mask = before[0]; + for p in [json!({"id": mask.0, "parent": layer.0, "index": 0}), json!({"id": mask.0, "parent": g.0, "index": 2})] { + let err = s.execute("node.move", &p).unwrap_err().to_string(); + assert!(err.contains("clipping path stays at the bottom"), "{p}: {err}"); + assert_eq!(children(&s, g), before, "{p}"); + } + run(&mut s, "node.move", json!({"id": mask.0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g), before, "the clipping path stays where it is"); + let d = rect(&mut s, 90.0); + run(&mut s, "node.move", json!({"id": d.0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g)[..2], [mask, d], "the row goes directly above the clipping path"); + run(&mut s, "node.move", json!({"id": before[2].0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g)[..2], [mask, before[2]]); +} + /// The Layers panel's commands refuse a switch given as text or as another value that is not true /// or false, and leave the document, the selection, the highlighted rows and the undo history as /// they were; true, false and null still work. diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index cf5fc3c269..1ee23ef47d 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -1299,3 +1299,26 @@ fn a_library_is_exported_to_a_file_and_imported_from_it() { v.libraries.set_dir(Some(folder)); assert_eq!(groups(&mut v), [("Logos".into(), refs(&[("graphic", &g)]))]); } + +/// A library file over 512 MB is refused from its size before it is opened: the file here cannot +/// be opened at all, so only the size check gives this error. +#[cfg(unix)] +#[test] +fn a_library_file_over_the_size_limit_is_refused_before_it_is_read() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("vc-library-too-big-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("big.vclibrary"); + // Sparse: no data blocks are written. + std::fs::File::create(&path).unwrap().set_len((512 << 20) + 1).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap(); + // A process that may read any file (root) opens it: nothing to check. + let opened = std::fs::File::open(&path).is_ok(); + let r = (!opened).then(|| session().execute("library.import", &json!({"path": path.to_string_lossy()}))); + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); + let _ = std::fs::remove_dir_all(&dir); + let Some(r) = r else { return }; // root opened the file: the size check is not what refuses it + let e = r.err().unwrap_or_else(|| panic!("the file was imported")).to_string(); + assert!(e.contains("the file is larger than 512 MB"), "{e}"); +} diff --git a/crates/engine/src/tests/link_paths.rs b/crates/engine/src/tests/link_paths.rs index ebc2b5d1c6..f9ebd99b85 100644 --- a/crates/engine/src/tests/link_paths.rs +++ b/crates/engine/src/tests/link_paths.rs @@ -100,6 +100,20 @@ fn places_named_from_a_share_are_not_followed_after_a_save_elsewhere() { assert_eq!(follow_from(link, on_share, Some(r"C:\b\poster.vectorcraft"), resolve), None); } +#[test] +fn capture_sources_exclude_paths_the_document_cannot_follow() { + let dir = Folder::new("capture-paths"); + let mut paths = far(&dir); + paths.push(dir.file("local.png")); + let path = save_linked(&dir, &paths); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": path})).unwrap(); + let st = s.active().unwrap(); + let places = crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st)); + assert_eq!(far_reads(&places), Vec::<&String>::new(), "{places:?}"); + assert!(places.contains(&dir.file("local.png")), "local links remain capture sources: {places:?}"); +} + /// The final path Windows gives a folder of the drive `Z:` mapped to `\\server\share`. The /// share's root folder has no trailing separator (`\\?\UNC\server\share`). fn on_share(folder: &str) -> Option { diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index a0f001afe6..e04296d26d 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -133,6 +133,18 @@ fn spot_gradients_export_as_separation_shadings() { assert!(pdf.contains("/ShadingType 2") && pdf.contains("/Separation/Ink/DeviceCMYK"), "an Ink → paper gradient is a Separation shading"); // Its function runs over the tints: 80 % (204 / 255) to 0 %. assert!(pdf.contains("/C0[0.8]/C1[0]"), "the shading's tints"); + // An off-center midpoint adds a stop there at the mean tint, still in the one spot ink. + run( + &mut s, + "paint.editGradient", + json!({"stops": [{"offset": 0, "swatch": "Ink", "tint": 80, "midpoint": 0.3}, {"offset": 1, "color": "#ffffff"}]}), + ); + let (pdf, _) = pdf_of(&s); + assert!(pdf.contains("/Separation/Ink/DeviceCMYK") && !pdf.contains("/DeviceN"), "still one spot ink"); + let functions: Vec<_> = pdf.match_indices("/C0[").filter_map(|(i, _)| pdf.get(i..i + 24)).collect(); + assert!(pdf.contains("/C0[0.8]/C1[0.4]") && pdf.contains("/C0[0.4]/C1[0]"), "the tints through the midpoint: {functions:?}"); + let bounds: Vec<_> = pdf.match_indices("/Bounds").filter_map(|(i, _)| pdf.get(i..i + 16)).collect(); + assert!(pdf.contains("/Bounds[0.3]"), "the midpoint stop sits at 30 %: {bounds:?}"); // Mixing the spot ink with an RGB color writes the gradient without the spot ink, with a warning. run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#00ff00"}]})); let (pdf, warnings) = pdf_of(&s); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 6e1623c00e..21cc4af602 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -137,6 +137,45 @@ fn a_preset_starts_the_document_and_params_change_it() { assert_eq!(s.doc().unwrap().doc.units, Unit::Pixels); } +#[test] +fn a_bad_preset_or_preset_category_is_an_error() { + let s = new_doc(json!({"preset": "A4", "presetCategory": "print"})); + assert!((s.doc().unwrap().doc.artboards[0].rect.height() - 841.89).abs() < 0.01); + for p in [ + json!({"preset": "A4", "presetCategory": "Napkins"}), + json!({"preset": "A4", "presetCategory": 5}), + json!({"preset": "A4", "presetCategory": ""}), + json!({"preset": "A4", "presetCategory": " Print "}), + json!({"presetCategory": "Print"}), + json!({"presetCategory": "Napkins"}), + json!({"preset": 5}), + json!({"preset": true, "presetCategory": "Print"}), + ] { + assert!(Session::new().execute("file.new", &p).is_err(), "file.new {p}"); + let mut save = p.clone(); + save["name"] = json!("Mine"); + assert!(Session::new().execute("file.newPresets.save", &save).is_err(), "file.newPresets.save {save}"); + } + let e = Session::new().execute("file.new", &json!({"preset": "A4", "presetCategory": "Napkins"})).unwrap_err().to_string(); + assert!(e.contains("unknown category `Napkins`"), "{e}"); + // Null leaves a param out. + Session::new().execute("file.new", &json!({"preset": null, "presetCategory": null})).unwrap(); + // A step this version took replays, and one an earlier version took still plays as it did then. + let recorded = new_doc(json!({"preset": "A4", "presetCategory": "print"})); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); + let mut recorded = new_doc(json!({})); + recorded.journal.last_mut().unwrap().1["presetCategory"] = json!("Print"); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); +} + #[test] fn ppi_overprint_preview_and_bad_params() { // Overprint Preview is process-wide. @@ -219,6 +258,8 @@ fn replayed_counts_keep_their_rounding_and_range_rules() { ("rows", 2.4, 2), ("rows", 0.6, 1), ("rows", 1000.4, 1000), + ("rows", 1000.6, 1000), + ("rows", 5000.0, 1000), ] { let mut p = json!({"width": 10, "height": 10, "artboards": 4, "artboardLayout": {"layout": "gridByColumn", "spacing": 0}}); @@ -236,8 +277,11 @@ fn replayed_counts_keep_their_rounding_and_range_rules() { p["artboardLayout"][key] = json!(expected); } assert_eq!(boards(&s), boards(&new_doc(p))); + if key == "rows" { + assert_eq!(presets(&mut s, "Recent")[0]["artboardLayout"]["rows"], json!(expected), "{value}"); + } } - for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] { + for layout in [json!({"columns": 0.6}), json!({"rows": 0.4})] { let mut p = json!({"artboardLayout": layout}); p["artboardLayout"]["layout"] = json!("gridByColumn"); let mut s = Session::new(); @@ -345,6 +389,25 @@ fn a_saved_preset_with_values_out_of_range_reads_in_range() { assert_eq!(boards(&s).iter().map(|r| r.x0).collect::>(), [0.0, 100.0, 200.0], "side by side, not overlapping"); } +/// A saved preset whose rows the preferences hold above the most `file.new` takes reads as that +/// most, so `file.new` takes the preset as `file.newPresets` lists it; no rows stay no rows. +#[test] +fn a_saved_preset_with_too_many_rows_reads_in_range() { + let mut s = Session::new(); + let prefs = json!({ + "newDocPresets": [ + {"name": "Tall", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 1001}, + {"name": "Plain", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 0}, + ], + }); + s.apply_prefs(serde_json::from_value(prefs).unwrap()); + let saved = presets(&mut s, "Saved"); + assert_eq!(saved[0]["artboardLayout"]["rows"], json!(1000), "{}", saved[0]); + assert_eq!(saved[1]["artboardLayout"].get("rows"), None, "{}", saved[1]); + s.execute("file.new", &saved[0]).unwrap(); + assert_eq!(boards(&s).len(), 4); +} + /// `file.new` and `artboard.new` take the same largest artboard side (the canvas less the largest /// bleed on both sides) and refuse a side just past it, or of 0 or less, with an error that names /// the limit in points and, when the document's units aren't points, in those units too. diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 802748e407..d1b5197012 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -123,6 +123,86 @@ fn intersect_disjoint_is_error_and_no_change() { assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); } +/// Pathfinder refuses a selection that holds no paths (an image alone) and paths with an anchor +/// that is not a finite number, and leaves the document and the undo history as they were. +#[test] +fn pathfinder_refuses_a_selection_without_paths_and_invalid_coordinates() { + let mut s = session(); + let image = s + .edit("Place", |d, sel| { + d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(vec![0; 8])); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 2, + height: 2, + xf: Default::default(), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo_len = s.doc().unwrap().history.undo.len(); + let e = s.execute("object.pathfinder.unite", &json!({})).unwrap_err().to_string(); + assert!(e.contains("select paths"), "{e}"); + assert!(s.doc().unwrap().doc == before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); + + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 5.0, 0.0, 10.0, 10.0); + s.edit("Break", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(a).unwrap().kind { + path.subpaths[0].anchors[1].p.x = f64::NAN; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let undo_len = s.doc().unwrap().history.undo.len(); + let e = s.execute("object.pathfinder.unite", &json!({})).unwrap_err().to_string(); + assert!(e.contains("invalid coordinates"), "{e}"); + assert!(s.doc().unwrap().doc.node(a).is_some() && s.doc().unwrap().doc.node(b).is_some()); + assert!(s.doc().unwrap().doc.node(image).is_some()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); +} + +/// Divide refuses a cutting line with more segments than its planar map takes, instead of +/// dividing the square without the line, and leaves the document and the undo history as they were. +#[test] +fn divide_refuses_cutting_lines_past_the_segment_cap() { + let mut s = session(); + let base = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let cutter = NodeId(s.execute("path.create", &json!({"anchors": [{"x": -10, "y": 50}, {"x": 110, "y": 50}]})).unwrap()["id"].as_u64().unwrap()); + // A zigzag across the square with one segment more than the cap, the square's four sides aside. + let segments = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS - 3; + s.edit("zigzag", |d, sel| { + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((-10.0, 40.0)); + for i in 1..=segments { + let x = -10.0 + 120.0 * i as f64 / segments as f64; + bp.line_to((x, if i % 2 == 0 { 40.0 } else { 60.0 })); + } + // Unfilled, so the zigzag stays open and cuts. + let n = d.node_mut(cutter).unwrap(); + n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into(); + n.kind = NodeKind::Path { path: PathData::from_bezpath(&bp), rule: FillRule::NonZero, live: None, clipping: false, guide: false }; + sel.set([cutter, base]); + Ok(()) + }) + .unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo_len = s.doc().unwrap().history.undo.len(); + let e = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string(); + assert!(e.contains("select fewer paths"), "{e}"); + assert!(s.doc().unwrap().doc == before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); +} + #[test] fn exclude_makes_compound() { let mut s = session(); diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index a655002a4d..301ae6622e 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -479,6 +479,25 @@ fn paths_added_to_or_moved_in_an_aligned_compound_path_keep_it_aligned() { assert!(halves(&pts), "slice: {pts:?}"); } +/// A path that `node.move` puts into a pixel-aligned compound path snaps with it, though neither +/// the path nor where it came from was pixel-aligned. +#[test] +fn a_path_node_move_puts_into_an_aligned_compound_path_snaps() { + let mut s = new_doc(); + let a = path(&mut s, "M100 100 L110 100 L110 110 L100 110 Z", 1.0); + let b = path(&mut s, "M200 100 L210 100 L210 110 L200 110 Z", 1.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [c]})).unwrap(); + let loose = path(&mut s, "M300.25 100 L310 100 L310 110 L300.25 110 Z", 1.0); + assert!(!aligned(&s, loose)); + s.execute("node.move", &json!({"id": loose, "parent": c, "index": 99})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(NodeId(loose)), Some(NodeId(c))); + let pts = compound_points(&s, c); + assert_eq!(pts.len(), 12); + assert!(halves(&pts), "{pts:?}"); +} + /// Art moved by Artboard Options with Move Artwork with Artboard, and the art copies of an /// artboard copied with its art, stay on the pixel grid. #[test] @@ -578,23 +597,29 @@ fn the_art_of_a_linked_opacity_mask_keeps_it_aligned() { let m = path(&mut s, "M12 23 L39 23 L39 28 L12 28 Z", 2.0); s.execute("object.setPixelAligned", &json!({"ids": [m]})).unwrap(); s.execute("transparency.makeOpacityMask", &json!({"ids": [o, m]})).unwrap(); - let mask_points = |s: &Session| { - let n = s.doc().unwrap().doc.node(NodeId(o)).unwrap().clone(); + let mask_points = |s: &Session, id: u64| { + let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone(); let mask = n.extras().mask.clone().expect("an opacity mask"); assert!(mask.art.extras().pixel_aligned); mask.art.path_data().unwrap().anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect::>() }; s.execute("select.set", &json!({"ids": [o]})).unwrap(); s.execute("object.move", &json!({"dx": 0.3, "dy": 0.4})).unwrap(); - assert_eq!(mask_points(&s), [(12.0, 23.0), (39.0, 23.0), (39.0, 28.0), (12.0, 28.0)]); - // The masked path inside a pixel-aligned compound path. + assert_eq!(mask_points(&s, o), [(12.0, 23.0), (39.0, 23.0), (39.0, 28.0), (12.0, 28.0)]); + // A pixel-aligned compound path made with the masked path at the back takes its mask. + // The masked path in front keeps its own mask inside it. let other = path(&mut s, "M110 21 L141 21 L141 30 L110 30 Z", 2.0); + let om = path(&mut s, "M112 23 L139 23 L139 28 L112 28 Z", 2.0); + s.execute("object.setPixelAligned", &json!({"ids": [om]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [other, om]})).unwrap(); s.execute("select.set", &json!({"ids": [o, other]})).unwrap(); let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("object.setPixelAligned", &json!({"ids": [c]})).unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); s.execute("object.move", &json!({"dx": 0.3, "dy": 0.4})).unwrap(); - assert!(whole(&mask_points(&s)), "{:?}", mask_points(&s)); + assert!(s.doc().unwrap().doc.node(NodeId(o)).unwrap().extras().mask.is_none()); + assert!(whole(&mask_points(&s, c)), "{:?}", mask_points(&s, c)); + assert!(whole(&mask_points(&s, other)), "{:?}", mask_points(&s, other)); } /// The start point of path object `id`'s placed gradient fill. diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs new file mode 100644 index 0000000000..f7ac63e770 --- /dev/null +++ b/crates/engine/src/tests/plugin_events.rs @@ -0,0 +1,1080 @@ +//! Events plug-ins react to (`events`, `vc_event`): each event reaches the plug-ins that name it, +//! once, after the change; a burst of selection changes in one frame is one event; a handler only +//! reads; and a handler that keeps failing stops being called. + +use serde_json::{Value, json}; +use vectorcraft_plugins::LogLevel; +use vectorcraft_plugins::wat as tpl; + +use crate::*; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// A session with a 400 × 200 document that takes `grant` from requests. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + s.allow_plugin_grants_from_requests(); + s +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap()) +} + +/// Installs plug-in `id` that reacts to `events` (a JSON list) with the vc_event body `handler`, +/// writes log lines and also has the permissions `more`; `imports` are module fields its handler +/// uses besides the host imports, and `allowlist` the commands it may call. +fn install(s: &mut Session, id: &str, events: &str, more: &[&str], imports: &str, handler: &str, allowlist: &[&str]) { + let mut grant = vec!["progress", "events"]; + grant.extend_from_slice(more); + let allow = if allowlist.is_empty() { String::new() } else { format!(r#","commandAllowlist":{}"#, json!(allowlist)) }; + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{},"events":{events}{allow}}}"#, json!(grant)); + let wasm = wat::parse_str(tpl::reacting(&manifest, &format!("{} {imports}", tpl::HOST_IMPORTS), handler)).unwrap(); + run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); +} + +fn local_session() -> Session { + let mut s = Session::new(); + s.plugin_events.test_subscribers = Some(Vec::new()); + run(&mut s, "file.new", json!({"width": 400, "height": 200})); + s +} + +fn subscribe(s: &mut Session, id: &str, events: &str, handler: &str) { + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":{events}}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, handler)).unwrap(); + let plugin = vectorcraft_plugins::Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap(); + s.plugin_events.test_subscribers.as_mut().unwrap().push(std::sync::Arc::new(plugin)); + s.plugins_changed_for_events(); +} + +/// The events plug-in `id`'s handler was given since the last call, as it logged them. +fn given(s: &mut Session, id: &str) -> Vec { + let notices = s.take_plugin_event_notices(); + notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Info).map(|n| serde_json::from_str(&n.text).unwrap()).collect() +} + +fn types(events: &[Value]) -> Vec<&str> { + events.iter().map(|e| e["type"].as_str().unwrap()).collect() +} + +#[test] +fn a_headless_gesture_delivers_events_when_its_actions_finish() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let id = "test.events.headless_gesture"; + for real_time in [true, false] { + let mut s = session(); + s.prefs.real_time_drawing = real_time; + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("rectangle", view).unwrap(); + for (kind, x, y) in [(PointerKind::Down, 50.0, 50.0), (PointerKind::Drag, 100.0, 100.0)] { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + assert!(given(&mut s, id).is_empty(), "the drag is still open"); + s.pointer(&PointerEvent::new(PointerKind::Up, 100.0, 100.0), view).unwrap(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["selection.changed"]); + assert_eq!(got[0]["ids"], json!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::>())); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the event is delivered once"); + run(&mut s, "plugin.remove", json!({"id": id})); + } +} + +#[test] +fn a_set_aside_drag_holds_events_and_their_baseline() { + use vectorcraft_plugins::events::Event; + let id = "test.events.held_drag"; + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed","document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let doc = s.doc().unwrap().uid; + s.note_plugin_event(Event::DocumentSaved, doc); + s.begin_interaction("Move").unwrap(); + s.active_mut().unwrap().interaction.as_mut().unwrap().tool = true; + s.outside_interaction("select.set", &json!({"ids": [r.0]}), |s| { + assert!(s.holds_interaction()); + assert!(s.docs.iter().all(|d| d.interaction.is_none())); + s.active_mut().unwrap().selection.objects = vec![r]; + s.deliver_plugin_events(); + assert!(given(s, id).is_empty(), "the drag is set aside"); + Ok(Value::Null) + }) + .unwrap(); + s.cancel_interaction().unwrap(); + s.deliver_plugin_events(); + assert_eq!(types(&given(&mut s, id)), ["document.saved"], "the temporary selection did not advance the baseline"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn batch_steps_compare_new_documents_with_their_initial_state() { + let id = "test.events.batch_new"; + let mut s = session(); + install(&mut s, id, r#"["selection.changed","document.opened","layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].clone(); + for first in [ + json!({"command": "file.new", "params": {}}), + json!({"command": "document.open", "params": {"name": "batch.vectorcraft", "dataBase64": data}}), + ] { + let opened = first["command"] == "document.open"; + run( + &mut s, + "command.batch", + json!({"commands": [first, {"command": "layer.new", "params": {"name": "Notes"}}, + {"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 10, "height": 10}}]}), + ); + let got = given(&mut s, id); + let expected = + if opened { vec!["document.opened", "selection.changed", "layer.changed"] } else { vec!["selection.changed", "layer.changed"] }; + assert_eq!(types(&got), expected); + assert!(got.iter().all(|e| e["document"] == s.doc().unwrap().uid)); + assert!(got.last().unwrap()["reasons"].as_array().unwrap().contains(&json!("added"))); + } + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn background_installs_record_the_baseline_before_the_next_edit() { + let id = "test.events.background_baseline"; + let folder = crate::tests_links::Folder::new("event-background-baseline"); + let mut writer = session(); + writer.attach_plugin_store(folder.0.clone()); + install(&mut writer, id, r#"["selection.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + assert!(vectorcraft_plugins::registry::remove(id)); + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + s.plugin_event_frames = true; + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + s.finish_plugin_loads(); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + assert!(given(&mut s, id).is_empty(), "changes before loading are not replayed"); + run(&mut s, "select.set", json!({"ids": [r.0]})); + s.deliver_plugin_events(); + assert_eq!(types(&given(&mut s, id)), ["selection.changed"]); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn background_installs_during_a_drag_record_the_settled_baseline() { + let id = "test.events.background_drag_baseline"; + let folder = crate::tests_links::Folder::new("event-background-drag-baseline"); + let mut writer = session(); + writer.attach_plugin_store(folder.0.clone()); + install(&mut writer, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + assert!(vectorcraft_plugins::registry::remove(id)); + for commit in [false, true] { + for tool_actions in [false, true] { + for edit_before_delivery in [true, false] { + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + s.plugin_event_frames = true; + s.begin_interaction("Select").unwrap(); + s.preview("select.set", &json!({"ids": [r.0]})).unwrap(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + s.finish_plugin_loads(); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + assert!(!s.deliver_plugin_events(), "the preview holds delivery"); + assert!(given(&mut s, id).is_empty()); + s.in_tool_actions = tool_actions; + if commit { + s.commit_interaction().unwrap(); + } else { + s.cancel_interaction().unwrap(); + } + s.in_tool_actions = false; + if !edit_before_delivery { + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "neither the preview nor its rollback is replayed"); + } + let ids = if commit { vec![] } else { vec![r.0] }; + run(&mut s, "select.set", json!({"ids": ids})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["selection.changed"], "commit={commit}, tool_actions={tool_actions}"); + assert_eq!(got[0]["ids"], json!(ids)); + assert!(vectorcraft_plugins::registry::remove(id)); + } + } + } +} + +#[test] +fn silent_handlers_report_when_another_frame_is_needed() { + use vectorcraft_plugins::events::Event; + let id = "test.events.silent_pending"; + let mut s = local_session(); + subscribe(&mut s, id, r#"["document.saved"]"#, "(i32.const 0)"); + s.plugin_event_frames = true; + let doc = s.doc().unwrap().uid; + for _ in 0..=crate::plugin_events::MAX_FRAME_HANDLERS { + s.note_plugin_event(Event::DocumentSaved, doc); + } + s.begin_plugin_event_frame(); + assert!(s.deliver_plugin_events(), "silent handlers still need another frame"); + assert!(s.take_plugin_event_notices().is_empty()); + s.begin_plugin_event_frame(); + assert!(!s.deliver_plugin_events(), "the next frame drains the remaining handler"); + assert!(s.take_plugin_event_notices().is_empty()); +} + +#[test] +fn deliveries_in_one_frame_share_the_handler_budget() { + use vectorcraft_plugins::events::Event; + let id = "test.events.shared_frame_budget"; + let mut s = local_session(); + subscribe(&mut s, id, r#"["document.saved"]"#, tpl::LOG_EVENT); + s.plugin_event_frames = true; + let doc = s.doc().unwrap().uid; + for _ in 0..(crate::plugin_events::MAX_FRAME_HANDLERS * 2) { + s.note_plugin_event(Event::DocumentSaved, doc); + } + s.begin_plugin_event_frame(); + assert!(s.deliver_plugin_events()); + assert_eq!(given(&mut s, id).len(), crate::plugin_events::MAX_FRAME_HANDLERS); + assert!(s.deliver_plugin_events(), "the UI pass still has queued handlers"); + assert!(given(&mut s, id).is_empty(), "background delivery already used this frame's budget"); + s.begin_plugin_event_frame(); + assert!(!s.deliver_plugin_events()); + assert_eq!(given(&mut s, id).len(), crate::plugin_events::MAX_FRAME_HANDLERS); +} + +#[test] +fn frame_delivery_bounds_handlers_and_resumes_remaining_recipients() { + use vectorcraft_plugins::events::Event; + let mut s = local_session(); + s.plugin_event_frames = true; + let ids: Vec = (0..=crate::plugin_events::MAX_FRAME_HANDLERS).map(|i| format!("test.events.frame_budget_{i}")).collect(); + for id in &ids { + subscribe(&mut s, id, r#"["document.saved"]"#, tpl::LOG_EVENT); + } + let doc = s.doc().unwrap().uid; + s.note_plugin_event(Event::DocumentSaved, doc); + s.note_plugin_event(Event::DocumentSaved, doc); + let mut delivered = Vec::new(); + for _ in 0..(ids.len() * 2) { + s.begin_plugin_event_frame(); + s.deliver_plugin_events(); + let notices: Vec<_> = s.take_plugin_event_notices().into_iter().filter(|n| ids.contains(&n.plugin)).collect(); + assert!(notices.len() <= crate::plugin_events::MAX_FRAME_HANDLERS); + delivered.extend(notices.into_iter().map(|n| n.plugin)); + } + assert_eq!(delivered.len(), ids.len() * 2); + for id in &ids { + assert_eq!(delivered.iter().filter(|got| *got == id).count(), 2, "{id}"); + } +} + +#[test] +fn coalesced_changes_serve_waiting_recipients_before_readded_recipients() { + let mut s = local_session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + let ids: Vec = (0..9).map(|i| format!("test.events.fair_selection_{i}")).collect(); + for id in &ids { + subscribe(&mut s, id, r#"["selection.changed"]"#, tpl::LOG_EVENT); + } + s.plugin_event_frames = true; + let mut delivered = Vec::new(); + for frame in 0..3 { + s.begin_plugin_event_frame(); + let selection = if frame % 2 == 0 { vec![r.0] } else { Vec::new() }; + run(&mut s, "select.set", json!({"ids": selection})); + assert!(s.deliver_plugin_events()); + let notices = s.take_plugin_event_notices(); + assert_eq!(notices.len(), crate::plugin_events::MAX_FRAME_HANDLERS); + delivered.extend(notices.into_iter().map(|n| n.plugin)); + } + for id in &ids { + assert!(delivered.contains(id), "{id} was not served while selection kept changing"); + } +} + +#[test] +fn delivery_indexes_subscribers_and_preserves_pending_recipient_order() { + use vectorcraft_plugins::events::Event; + let mut s = local_session(); + let ids: Vec = (0..32).map(|i| format!("test.events.indexed_{i}")).collect(); + for id in &ids { + subscribe(&mut s, id, r#"["document.saved"]"#, tpl::LOG_EVENT); + } + let doc = s.doc().unwrap().uid; + s.note_plugin_event(Event::DocumentSaved, doc); + s.plugin_events.test_subscribers.as_mut().unwrap().reverse(); + crate::plugin_events::RECIPIENT_IDENTITIES.with(|count| count.set(0)); + assert!(!s.deliver_plugin_events()); + let identities = crate::plugin_events::RECIPIENT_IDENTITIES.with(|count| count.get()); + let delivered: Vec<_> = s.take_plugin_event_notices().into_iter().map(|n| n.plugin).collect(); + assert_eq!(delivered, ids); + assert!(identities <= ids.len() * 8, "{identities} recipient identities for {} subscribers", ids.len()); +} + +#[test] +fn a_subscriber_loaded_during_a_drag_receives_the_batch_changes() { + let id = "test.events.batch_drag_baseline"; + for frames in [false, true] { + let mut s = local_session(); + s.plugin_event_frames = frames; + s.begin_interaction("Add layer").unwrap(); + s.preview("layer.new", &json!({"name": "Drag preview"})).unwrap(); + subscribe(&mut s, id, r#"["layer.changed"]"#, tpl::LOG_EVENT); + assert!(!s.deliver_plugin_events()); + assert!(given(&mut s, id).is_empty()); + run(&mut s, "command.batch", json!({"commands": [{"command": "layer.new", "params": {"name": "Batch layer"}}]})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty()); + } +} + +/// A batch with no interaction to settle keeps the last check's state: a selection it puts back +/// as it was is not a change. +#[test] +fn a_batch_without_an_interaction_keeps_the_event_baseline() { + let id = "test.events.batch_no_interaction"; + let mut s = local_session(); + s.plugin_event_frames = true; + rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + subscribe(&mut s, id, r#"["selection.changed"]"#, tpl::LOG_EVENT); + s.deliver_plugin_events(); + given(&mut s, id); + run(&mut s, "select.all", json!({})); + run(&mut s, "command.batch", json!({"commands": [{"command": "select.none", "params": {}}]})); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the selection is as it was at the last delivery"); +} + +/// A plug-in installed since the last check, without this session hearing of it, is given the +/// changes of a batch that settles no interaction. +#[test] +fn a_batch_gives_its_changes_to_a_plugin_installed_since_the_last_check() { + let id = "test.events.batch_new_subscriber"; + let mut s = local_session(); + s.plugin_event_frames = true; + subscribe(&mut s, "test.events.batch_earlier", r#"["selection.changed"]"#, tpl::LOG_EVENT); + s.deliver_plugin_events(); + s.take_plugin_event_notices(); + let manifest = + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":["layer.changed"]}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + let plugin = vectorcraft_plugins::Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap(); + s.plugin_events.test_subscribers.as_mut().unwrap().push(std::sync::Arc::new(plugin)); + run(&mut s, "command.batch", json!({"commands": [{"command": "layer.new", "params": {"name": "Batch layer"}}]})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); +} + +#[test] +fn script_batches_compare_layers_only_after_the_script_commits() { + let id = "test.events.script_batch_layers"; + for frames in [false, true] { + for kept in [false, true] { + let mut s = local_session(); + subscribe(&mut s, id, r#"["layer.changed"]"#, tpl::LOG_EVENT); + s.plugin_event_frames = frames; + let before = s.doc().unwrap().doc.layers.len(); + let ending = if kept { "" } else { "throw new Error('stop');" }; + let source = format!("vc.run('command.batch', {{commands: [{{command: 'layer.new', params: {{name: 'Script layer'}}}}]}}); {ending}"); + let result = s.execute("script.run", &json!({"source": source, "name": "batch.js"})); + assert_eq!(result.is_ok(), kept, "{result:?}"); + if !kept { + assert_eq!(s.doc().unwrap().doc.layers.len(), before, "the failed script's layer was rolled back"); + } + s.deliver_plugin_events(); + let got = given(&mut s, id); + if kept { + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); + } else { + assert!(got.is_empty(), "the script's layer was rolled back: {got:?}"); + } + run(&mut s, "layer.new", json!({"name": "Committed"})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); + } + } +} + +#[test] +fn a_failed_batch_drops_layer_changes_from_a_settled_interaction() { + let id = "test.events.rolled_back_layer"; + for frames in [false, true] { + let mut s = local_session(); + subscribe(&mut s, id, r#"["layer.changed","document.opened"]"#, tpl::LOG_EVENT); + s.plugin_event_frames = frames; + let before = s.doc().unwrap().doc.clone(); + let error = s + .execute( + "command.batch", + &json!({"commands": [ + {"command": "layer.new", "params": {"name": "Notes"}}, + {"command": "edit.newDocumentFromState", "params": {}}, + {"command": "no.such.command", "params": {}} + ]}), + ) + .unwrap_err(); + assert!(error.to_string().contains("batch step 2"), "{error}"); + assert_eq!(s.documents().len(), 1); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the batch's layer was rolled back"); + run(&mut s, "layer.new", json!({"name": "Committed"})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); + } +} + +/// A selection change, a new layer, a save and an open each reach the plug-in that names them once, +/// after the change, with the document they happened in; a plug-in that names only `document.saved` +/// is given only the save. +#[test] +fn each_event_reaches_the_plugins_that_name_it_once() { + let (all, saves) = ("test.events.all", "test.events.saves"); + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + install(&mut s, all, r#"["selection.changed","document.opened","document.saved","layer.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + install(&mut s, saves, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + assert!(given(&mut s, all).is_empty(), "installing replays nothing"); + let doc = s.doc().unwrap().uid; + + run(&mut s, "select.set", json!({"ids": [r.0]})); + let notices = s.take_plugin_event_notices(); + let got: Vec = notices.iter().filter(|n| n.plugin == all).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": [r.0], "truncated": false})]); + assert!(notices.iter().all(|n| n.plugin != saves), "not named, not given"); + + run(&mut s, "select.set", json!({"ids": [r.0]})); + assert!(given(&mut s, all).is_empty(), "the same selection again is no change"); + + let layer = run(&mut s, "layer.new", json!({"name": "Notes"}))["id"].as_u64().unwrap(); + let got = given(&mut s, all); + assert_eq!(types(&got), ["layer.changed"]); + assert_eq!(got[0]["layer"], json!(layer)); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added")), "{}", got[0]); + + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("events.vectorcraft").to_string_lossy().into_owned(); + run(&mut s, "document.save", json!({"path": path})); + let notices = s.take_plugin_event_notices(); + for id in [all, saves] { + let got: Vec = notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "document.saved", "document": doc})], "{id}"); + } + + run(&mut s, "document.open", json!({"path": path})); + let opened = s.doc().unwrap().uid; + assert_ne!(opened, doc); + assert_eq!(given(&mut s, all), [json!({"type": "document.opened", "document": opened})], "a new document's own selection is no change"); + + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": all})); + run(&mut s, "plugin.remove", json!({"id": saves})); +} + +/// A save of a document that closes before the frame's delivery still reaches the plug-in, with +/// the document's number; its selection change does not. So does a save written on another thread +/// that finishes after its document closed. +#[test] +fn a_save_reaches_the_plugin_when_its_document_closes_first() { + let id = "test.events.closed"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed","document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + run(&mut s, "select.set", json!({"ids": [r.0]})); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-closed-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("closed.vectorcraft").to_string_lossy()})); + run(&mut s, "file.close", json!({})); + assert!(s.docs.iter().all(|d| d.uid != doc), "the document closed"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let later = s.doc().unwrap().uid; + let p = json!({"path": dir.join("later.vectorcraft").to_string_lossy()}); + let plan = crate::cmd::fileio::save_plan(&s, crate::cmd::fileio::SaveMode::SaveAs, &p).unwrap(); + let job = crate::cmd::fileio::save_job(&mut s, plan).unwrap(); + job.write(|path, bytes| std::fs::write(path, bytes).map_err(|e| EngineError::Other(e.to_string()))).unwrap(); + run(&mut s, "file.close", json!({})); + assert!(s.docs.iter().all(|d| d.uid != later), "the document closed"); + job.complete(&mut s, later); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": later})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in installed after a save or a selection change, before the frame's delivery, is given +/// neither; the plug-in installed before is given both, and the next change reaches both. +#[test] +fn a_plugin_installed_before_the_delivery_gets_no_earlier_events() { + let (early, late) = ("test.events.early", "test.events.late"); + let events = r#"["selection.changed","document.saved"]"#; + let mut s = session(); + let doc = s.doc().unwrap().uid; + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, early, events, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-late-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("late.vectorcraft").to_string_lossy()})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + install(&mut s, late, events, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let of = |id: &str| -> Vec { notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect() }; + assert_eq!(types(&of(early)), ["document.saved", "selection.changed"]); + assert!(of(late).is_empty(), "{:?}", of(late)); + run(&mut s, "select.set", json!({"ids": [b.0]})); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + for id in [early, late] { + let got: Vec = notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": null, "truncated": false})], "{id}"); + } + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": early})); + run(&mut s, "plugin.remove", json!({"id": late})); +} + +/// With delivery once a frame, a selection change made after a plug-in was installed, in the same +/// frame, reaches it. +#[test] +fn a_change_after_the_install_in_the_same_frame_reaches_the_plugin() { + let id = "test.events.same_frame"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + s.plugin_event_frames = true; + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + run(&mut s, "select.set", json!({"ids": [r.0]})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": [r.0], "truncated": false})]); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// With delivery once a frame, a change made to a document created or opened since the last +/// delivery gives its event at the next one; an opened document's `document.opened` comes first, +/// once. +#[test] +fn a_change_to_a_document_opened_since_the_last_delivery_gives_its_event() { + let id = "test.events.new_doc"; + let mut s = session(); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-new-doc-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("new-doc.vectorcraft").to_string_lossy().into_owned(); + run(&mut s, "document.save", json!({"path": path})); + install(&mut s, id, r#"["selection.changed","document.opened","layer.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty()); + + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let created = s.doc().unwrap().uid; + let r = rect(&mut s, 10.0); + run(&mut s, "select.set", json!({"ids": [r.0]})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "selection.changed", "document": created, "count": 1, "ids": [r.0], "truncated": false})]); + + run(&mut s, "document.open", json!({"path": path})); + let opened = s.doc().unwrap().uid; + let layer = run(&mut s, "layer.new", json!({"name": "Notes"}))["id"].as_u64().unwrap(); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["document.opened", "layer.changed"], "{got:?}"); + assert_eq!((got[0]["document"].clone(), got[1]["document"].clone(), got[1]["layer"].clone()), (json!(opened), json!(opened), json!(layer))); + assert!(got[1]["reasons"].as_array().unwrap().contains(&json!("added")), "{}", got[1]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "once"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A save waiting for delivery is not given to the same module removed and installed again before +/// the delivery. +#[test] +fn a_module_installed_again_gets_no_event_from_before_its_removal() { + let id = "test.events.again"; + let mut s = session(); + s.plugin_event_frames = true; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-again-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("again.vectorcraft").to_string_lossy()})); + run(&mut s, "plugin.remove", json!({"id": id})); + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the save came before this install"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A save waiting in one session is not given to the same module that another session removed and +/// installed again before this session's delivery. +#[test] +fn a_module_installed_again_by_another_session_gets_no_earlier_event() { + let id = "test.events.again_elsewhere"; + let mut s = session(); + s.plugin_event_frames = true; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-elsewhere-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("elsewhere.vectorcraft").to_string_lossy()})); + let mut other = session(); + run(&mut other, "plugin.remove", json!({"id": id})); + install(&mut other, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the save came before this install"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in installed between two layer changes waiting for the same delivery is given only the +/// reason of the change after its install; the plug-in installed before is given both. +#[test] +fn a_plugin_installed_between_layer_changes_gets_only_the_later_reason() { + let (early, late) = ("test.events.reasons_early", "test.events.reasons_late"); + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let second = NodeId(run(&mut s, "layer.new", json!({"name": "Two"}))["id"].as_u64().unwrap()); + install(&mut s, early, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + run(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})); + install(&mut s, late, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let reasons = |id: &str| -> Vec { + notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str::(&n.text).unwrap()["reasons"].clone()).collect() + }; + assert_eq!(reasons(early), [json!(["current", "options"])]); + assert_eq!(reasons(late), [json!(["current"])], "the rename came before this install"); + run(&mut s, "plugin.remove", json!({"id": early})); + run(&mut s, "plugin.remove", json!({"id": late})); +} + +/// A save waiting for delivery is held while an interaction is open, and given at the first +/// delivery after it ends. +#[test] +fn waiting_events_are_held_while_an_interaction_is_open() { + let id = "test.events.interaction"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-interaction-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("interaction.vectorcraft").to_string_lossy()})); + s.begin_interaction("Move").unwrap(); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "not while the interaction is open"); + s.cancel_interaction().unwrap(); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A save in a batch whose later step fails is still given to the plug-in when the request ends; +/// an open in that batch, which the rollback closes again, is not. +#[test] +fn a_save_before_a_failed_batch_step_is_delivered() { + let id = "test.events.failed_batch"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-failed-batch-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("failed-batch.vectorcraft").to_string_lossy().into_owned(); + let steps = json!([ + {"command": "document.save", "params": {"path": path}}, + {"command": "document.open", "params": {"path": path}}, + {"command": "no.such.command", "params": {}} + ]); + assert!(s.execute("command.batch", &json!({"commands": steps})).is_err()); + assert!(std::path::Path::new(&path).exists(), "the save was written"); + assert_eq!(s.documents().len(), 1, "the opened document was closed again"); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A document a script opened before it failed is discarded with the run's working copy, so the +/// plug-in is not told of it. The save the script made before failing is still given, and so is a +/// document the frontend opened while the run was paused. +#[test] +fn a_failed_script_gives_its_save_but_not_its_open() { + let id = "test.events.failed_script"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-failed-script-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("failed-script.vectorcraft").to_string_lossy()})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + + s.script_frames = true; + let source = format!( + "vc.run('document.save', {{}}); vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}}); \ + for (var i = 0; i < 3000000; i++) {{}} throw new Error('stop');" + ); + assert_eq!(run(&mut s, "script.run", json!({"source": source, "name": "t.js"}))["running"], true); + assert!(s.script_pump().is_none(), "paused after its first slice"); + let bytes = vectorcraft_format::base64_decode(&data).unwrap(); + let index = crate::cmd::fileio::open_bytes(&mut s, "front.vectorcraft", &bytes, None).unwrap()["index"].as_u64().unwrap(); + let front = s.documents()[index as usize].uid; + let mut slices = 0; + let r = loop { + slices += 1; + assert!(slices < 100_000, "the script ends"); + if let Some(r) = s.script_pump() { + break r; + } + }; + assert!(r.is_err(), "the script threw"); + assert!(s.docs.iter().all(|d| d.uid == doc || d.uid == front), "the script's document was discarded"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc}), json!({"type": "document.opened", "document": front})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A delivery between a script's slices, as a frontend makes one for a command it runs while the +/// script is paused, gives the frontend's open but holds the open and the save the script queued +/// until the run ends: the run fails, so its open is never given, and its save is given after it. +#[test] +fn a_delivery_between_script_slices_holds_the_script_events() { + let id = "test.events.between_slices"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-between-slices-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("between-slices.vectorcraft").to_string_lossy()})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + + s.script_frames = true; + let source = format!( + "vc.run('document.save', {{}}); vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}}); \ + for (var i = 0; i < 3000000; i++) {{}} throw new Error('stop');" + ); + assert_eq!(run(&mut s, "script.run", json!({"source": source, "name": "t.js"}))["running"], true); + assert!(s.script_pump().is_none(), "paused after its first slice"); + let bytes = vectorcraft_format::base64_decode(&data).unwrap(); + let index = crate::cmd::fileio::open_bytes(&mut s, "front.vectorcraft", &bytes, None).unwrap()["index"].as_u64().unwrap(); + let front = s.documents()[index as usize].uid; + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.opened", "document": front})], "only the frontend's open, while the run is paused"); + let mut slices = 0; + let r = loop { + slices += 1; + assert!(slices < 100_000, "the script ends"); + if let Some(r) = s.script_pump() { + break r; + } + }; + assert!(r.is_err(), "the script threw"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})], "the script's save, and not its open"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one +/// with it lists the selected ids. +#[test] +fn selected_ids_need_doc_read() { + let id = "test.events.noread"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + install(&mut s, id, r#"["selection.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let got = given(&mut s, id); + assert_eq!(got.len(), 1); + assert_eq!((got[0]["count"].clone(), got[0]["ids"].clone()), (json!(2), Value::Null)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// With delivery once a frame, the selection changes of one frame are one event with the selection +/// the frame ended with, and changes that end where they started are none. +#[test] +fn selection_changes_in_one_frame_are_one_event() { + let id = "test.events.burst"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + for ids in [vec![a.0], vec![b.0], vec![], vec![a.0, b.0], vec![b.0]] { + run(&mut s, "select.set", json!({"ids": ids})); + } + assert!(given(&mut s, id).is_empty(), "nothing before the frame"); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["selection.changed"]); + assert_eq!(got[0]["ids"], json!([b.0])); + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "select.set", json!({"ids": [b.0]})); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "back where the frame started"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// `layer.changed` names what changed: a new name is `options`, the same name again is no change, +/// another current layer is `current`, a moved layer `reordered` and a deleted one `deleted`. +#[test] +fn layer_changes_name_their_reasons() { + let id = "test.events.layers"; + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let second = NodeId(run(&mut s, "layer.new", json!({"name": "Two"}))["id"].as_u64().unwrap()); + install(&mut s, id, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + let reasons = |s: &mut Session, cmd: &str, p: Value| { + run(s, cmd, p); + given(s, id).iter().map(|e| e["reasons"].clone()).collect::>() + }; + assert_eq!(reasons(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})), [json!(["options"])]); + assert!(reasons(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})).is_empty(), "same name, no change"); + assert_eq!(reasons(&mut s, "layer.setCurrent", json!({"id": first.0})), [json!(["current"])]); + assert_eq!(reasons(&mut s, "layer.move", json!({"ids": [first.0], "target": second.0, "place": "above"})), [json!(["reordered"])]); + let deleted = reasons(&mut s, "layer.delete", json!({"ids": [second.0]})); + assert_eq!(deleted.len(), 1); + assert!(deleted[0].as_array().unwrap().contains(&json!("deleted")), "{deleted:?}"); + + // A sublayer moved past an object beside it is reordered; an object drawn beside it is not. + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + given(&mut s, id); + let sub = NodeId(run(&mut s, "layer.newSublayer", json!({"parent": first.0, "name": "Sub"}))["id"].as_u64().unwrap()); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + given(&mut s, id); + let r = rect(&mut s, 10.0); + assert!(given(&mut s, id).is_empty(), "drawing beside a sublayer moves no layer"); + assert_eq!(reasons(&mut s, "layer.move", json!({"ids": [sub.0], "target": r.0, "place": "above"})), [json!(["reordered"])]); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A handler may call a command listed for handlers, and is given its result; one that calls a +/// command that changes the document or the current layer, or a read not listed for handlers, is +/// refused with an error that names the event, and the selection, the current layer and the undo +/// history stay as the user left them. +#[test] +fn a_handler_only_reads() { + let (reads, edits) = ("test.events.reads", "test.events.edits"); + let (unlisted, layers) = ("test.events.unlisted", "test.events.layer"); + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let other = run(&mut s, "layer.new", json!({"name": "Other"}))["id"].as_u64().unwrap(); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + let (a, _) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + let expected = run(&mut s, "variable.list", json!({})); + // The read's result, copied with `vc_call_result`, is written as a log line. + let (imports, call) = calling("variable.list", "{}"); + let imports = format!(r#"{imports} (import "env" "vc_call_result" (func $vc_call_result (param i32 i32) (result i32)))"#); + let handler = format!( + "(drop {call}) (drop (call $vc_log (i32.const 2) (i32.const 0x4000) (call $vc_call_result (i32.const 0x4000) (i32.const 0x4000)))) (i32.const 0)" + ); + install(&mut s, reads, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["variable.list"]); + assert!(!find_command("addon.cleanup.check").unwrap().journal, "a query the journal does not record"); + let (imports, handler) = calling("addon.cleanup.check", "{}"); + install(&mut s, unlisted, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["addon.cleanup.check"]); + let (imports, handler) = calling("select.all", "{}"); + install(&mut s, edits, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["select.all"]); + let (imports, handler) = calling("layer.setCurrent", &format!(r#"{{"id":{other}}}"#)); + install(&mut s, layers, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["layer.setCurrent"]); + let (undo, rows) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().layer_rows.clone()); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let notices = s.take_plugin_event_notices(); + let read: Vec = notices.iter().filter(|n| n.plugin == reads).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(read, [expected], "the read call succeeds and gives its result: {notices:?}"); + for (id, cmd) in [(unlisted, "addon.cleanup.check"), (edits, "select.all"), (layers, "layer.setCurrent")] { + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{failed:?}"); + assert!(failed[0].contains(&format!("a selection.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + } + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, [a], "the selection the user made"); + assert_eq!((st.active_layer, &st.layer_rows), (Some(first), &rows), "the current layer the user chose"); + assert_eq!(st.history.undo.len(), undo, "no undo step"); + let info = run(&mut s, "plugin.info", json!({"id": edits})); + assert!(info["lastEventError"].as_str().unwrap().contains("only reads"), "{info}"); + assert_eq!(info["eventsOff"], json!(false)); + assert_eq!(info["events"], json!(["selection.changed"])); + run(&mut s, "plugin.remove", json!({"id": reads})); + run(&mut s, "plugin.remove", json!({"id": unlisted})); + run(&mut s, "plugin.remove", json!({"id": edits})); + run(&mut s, "plugin.remove", json!({"id": layers})); +} + +/// A handler that calls a query the journal does not record but that changes the selection (Select +/// All Instances) is refused before the query runs: the document, its revision, selection and undo +/// history, and the session's paint and Appearance state, are as the user left them. +#[test] +fn a_handler_query_that_selects_is_refused_before_it_runs() { + let id = "test.events.selects"; + let (cmd, args) = ("symbol.selectInstances", r#"{"name":"Dot"}"#); + assert!(!find_command(cmd).unwrap().journal, "a query the journal does not record"); + let mut s = session(); + let dot = rect(&mut s, 10.0); + run(&mut s, "symbol.new", json!({"name": "Dot", "ids": [dot.0]})); + let b = rect(&mut s, 40.0); + run(&mut s, "select.none", json!({})); + let (imports, handler) = calling(cmd, args); + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &[cmd]); + s.plugin_event_frames = true; + run(&mut s, "select.set", json!({"ids": [b.0]})); + let st = s.doc().unwrap(); + let (doc, revision, undo) = (st.doc.clone(), st.revision, st.history.undo.len()); + let (paint, appearance, fill_active) = (s.paint.clone(), format!("{:?}", s.active_appearance_item), s.fill_active); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{notices:?}"); + assert!(failed[0].contains(&format!("a selection.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + let st = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &doc), "the same document"); + assert_eq!((st.revision, st.history.undo.len()), (revision, undo), "the same revision and undo history"); + assert_eq!(st.selection.objects, [b], "the selection the user made"); + assert_eq!((&s.paint, format!("{:?}", s.active_appearance_item), s.fill_active), (&paint, appearance, fill_active)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A refused handler call leaves the Appearance panel's active row and the Fill or Stroke in +/// front as the user chose them, also when the query it called selected art. +#[test] +fn a_refused_handler_call_keeps_the_active_appearance_row() { + let id = "test.events.appearance"; + let (cmd, args) = ("addon.cleanup.show", r#"{"kind":"duplicateObjects","scope":"document"}"#); + assert!(!find_command(cmd).unwrap().journal, "a query the journal does not record"); + let mut s = session(); + let (a, _) = (rect(&mut s, 10.0), rect(&mut s, 10.0)); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let (imports, handler) = calling(cmd, args); + install(&mut s, id, r#"["layer.changed"]"#, &["doc.read", "commands"], &imports, &handler, &[cmd]); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + let fill_active = s.fill_active; + run(&mut s, "layer.new", json!({"name": "Other"})); + let notices = s.take_plugin_event_notices(); + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{notices:?}"); + assert!(failed[0].contains(&format!("a layer.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + assert_eq!(s.doc().unwrap().selection.objects, [a], "the selection the user made"); + assert!(s.active_appearance_item.is_some(), "the active Appearance row"); + assert_eq!(s.fill_active, fill_active); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Module fields that import `vc_call` and hold `cmd` and `args`, and a `vc_event` body that calls +/// `cmd` with `args` and returns what the call returned. +fn calling(cmd: &str, args: &str) -> (String, String) { + let imports = format!( + r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (data (i32.const 0x2000) "{}") (data (i32.const 0x2100) "{}")"#, + tpl::string(cmd), + tpl::string(args) + ); + let handler = format!("(call $vc_call (i32.const 0x2000) (i32.const {}) (i32.const 0x2100) (i32.const {}))", cmd.len(), args.len()); + (imports, handler) +} + +/// A handler that fails is reported once; after three failures in a row its events stop for the +/// session, while each selection the user makes stays. +#[test] +fn a_handler_that_keeps_failing_is_turned_off() { + let id = "test.events.failing"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed"]"#, &[], "", "unreachable", &[]); + let mut notices = Vec::new(); + for ids in [vec![a.0], vec![b.0], vec![a.0], vec![b.0], vec![a.0]] { + run(&mut s, "select.set", json!({"ids": ids.clone()})); + assert_eq!(s.doc().unwrap().selection.objects.iter().map(|i| i.0).collect::>(), ids, "the user's selection stays"); + notices.extend(s.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text)); + } + assert_eq!(notices.len(), 2, "{notices:?}"); + assert!(notices[0].starts_with("its selection.changed handler failed") && notices[0].contains("trapped"), "{}", notices[0]); + assert!(notices[1].contains("after 3 failed handlers in a row"), "{}", notices[1]); + let info = run(&mut s, "plugin.info", json!({"id": id})); + assert_eq!(info["eventsOff"], json!(true)); + // Installing the same module again turns its events back on. + install(&mut s, id, r#"["selection.changed"]"#, &[], "", "unreachable", &[]); + let info = run(&mut s, "plugin.info", json!({"id": id})); + assert_eq!(info["eventsOff"], json!(false), "a new installation starts with no failures"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A commit or cancel with no interaction open ends nothing: it records no baseline, so a change +/// made and undone before the next delivery gives no event. +#[test] +fn a_commit_or_cancel_without_an_interaction_records_no_baseline() { + let id = "test.events.no_interaction"; + for commit in [true, false] { + let mut s = local_session(); + s.plugin_event_frames = true; + let a = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + subscribe(&mut s, id, r#"["selection.changed"]"#, tpl::LOG_EVENT); + s.deliver_plugin_events(); + let _ = given(&mut s, id); + run(&mut s, "select.set", json!({"ids": [a.0]})); + if commit { + s.commit_interaction().unwrap(); + } else { + s.cancel_interaction().unwrap(); + } + run(&mut s, "select.none", json!({})); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "commit: {commit}"); + } +} + +/// A document added before any check of a plug-in that reacts to events is compared with how it +/// was when it was added, so its first selection change gives an event. +#[test] +fn a_document_added_before_the_first_check_gives_its_first_change() { + let id = "test.events.first_document"; + let mut s = Session::new(); + s.plugin_event_frames = true; + let manifest = + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":["selection.changed"]}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + let plugin = vectorcraft_plugins::Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap(); + s.plugin_events.test_subscribers = Some(vec![std::sync::Arc::new(plugin)]); + run(&mut s, "file.new", json!({"width": 400, "height": 200})); + rect(&mut s, 10.0); + s.deliver_plugin_events(); + assert_eq!(types(&given(&mut s, id)), ["selection.changed"]); +} diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 54c599d5fd..42728c7fa6 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2739,6 +2739,78 @@ fn stored_files_whose_reads_fail_leave_the_store_budget_to_the_others() { assert!(vectorcraft_plugins::registry::remove(id)); } +/// Sets the bytes the stored plug-ins of this thread's stores may read together, and puts the +/// usual budget back when dropped, a failed assertion included. +struct StoreBudget; + +impl StoreBudget { + fn set(bytes: u64) -> Self { + crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(bytes)); + StoreBudget + } +} + +impl Drop for StoreBudget { + fn drop(&mut self) { + crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(crate::store::MAX_PLUGIN_STORE)); + } +} + +/// The failure listed for each stored file of `folder`, as (file name, reason), sorted. +fn stored_failures_in(folder: &std::path::Path) -> Vec<(String, String)> { + let mut rows: Vec<(String, String)> = crate::store::failed_stored_plugins(folder) + .into_iter() + .map(|(p, why)| (p.file_name().unwrap().to_string_lossy().into_owned(), why)) + .collect(); + rows.sort(); + rows +} + +/// Once the stored plug-ins have used up the bytes a store may read, the stored files after them +/// are listed as failed and are not installed. +#[test] +fn stored_plugins_past_the_store_budget_are_listed_as_failed() { + let (folder, first) = store_with("plugin-budget-used-up", "test.engine.budgetused.a"); + for id in ["test.engine.budgetused.b", "test.engine.budgetused.c"] { + let module = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap(); + std::fs::write(folder.0.join(format!("{id}.wasm")), module).unwrap(); + } + let len = std::fs::metadata(&first).unwrap().len(); + let mut s = session(); + { + let _budget = StoreBudget::set(len); + s.attach_plugin_store(folder.0.clone()); + } + let installed: Vec = + ["a", "b", "c"].iter().map(|n| vectorcraft_plugins::registry::get(&format!("test.engine.budgetused.{n}")).is_some()).collect(); + let failed = stored_failures_in(&folder.0); + for n in ["a", "b", "c"] { + vectorcraft_plugins::registry::remove(&format!("test.engine.budgetused.{n}")); + } + assert_eq!(installed, [true, false, false], "only the first file fits the budget"); + let why = format!("the stored plug-ins hold more than {} bytes together", crate::store::MAX_PLUGIN_STORE); + let expected: Vec<(String, String)> = ["b", "c"].iter().map(|n| (format!("test.engine.budgetused.{n}.wasm"), why.clone())).collect(); + assert_eq!(failed, expected); +} + +/// A stored file longer than the bytes the store may still read is skipped and listed as failed. +#[test] +fn a_stored_plugin_larger_than_the_store_budget_is_skipped() { + let id = "test.engine.budgetsmall"; + let (folder, module) = store_with("plugin-budget-small", id); + let len = std::fs::metadata(&module).unwrap().len(); + let mut s = session(); + { + let _budget = StoreBudget::set(len - 1); + s.attach_plugin_store(folder.0.clone()); + } + let installed = vectorcraft_plugins::registry::remove(id); + assert!(!installed, "a file over the budget is not read"); + let failed = stored_failures_in(&folder.0); + assert_eq!(failed.len(), 1, "{failed:?}"); + assert!(failed[0].1.contains(&format!("larger than {} bytes", len - 1)), "{failed:?}"); +} + /// A stored file replaced after its module loaded, by one of the same length with the same modified /// time, is skipped: its content no longer holds the module. That holds for a file modified moments /// ago and for one modified an hour ago. diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 01493efda5..1e7dd7e9d1 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -3105,3 +3105,28 @@ fn pixel_snapping_options_read_set_and_reset() { s.execute("prefs.reset", &json!({})).unwrap(); assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all); } + +/// User Interface › Tool Icons is Classic by default and in preferences saved before it existed. Current, +/// once set, is saved and read back by a new session; a value that is neither is refused and changes nothing. +#[test] +fn tool_icons_default_to_classic_and_current_survives_a_restart() { + assert_eq!(Prefs::default().ui_tool_icons, "classic"); + let older: Prefs = serde_json::from_value(json!({"keyboardIncrement": 4})).unwrap(); + assert_eq!(older.ui_tool_icons, "classic"); + + let mut first = Session::new(); + assert_eq!(first.execute("prefs.get", &json!({"key": "uiToolIcons"})).unwrap(), json!("classic")); + for bad in [json!("modern"), json!(""), json!(true), json!(1)] { + assert!(first.execute("prefs.set", &json!({"key": "uiToolIcons", "value": bad})).is_err(), "{bad}"); + assert_eq!(first.prefs.ui_tool_icons, "classic", "{bad} left the preference as it was"); + } + first.execute("prefs.set", &json!({"key": "uiToolIcons", "value": "current"})).unwrap(); + let saved = first.prefs.to_json(); + assert_eq!(saved["uiToolIcons"], "current"); + + let mut restarted = Session::new(); + restarted.apply_prefs(serde_json::from_value(saved).unwrap()); + assert_eq!(restarted.execute("prefs.get", &json!({"key": "uiToolIcons"})).unwrap(), json!("current")); + restarted.execute("prefs.reset", &json!({"category": "User Interface"})).unwrap(); + assert_eq!(restarted.prefs.ui_tool_icons, "classic"); +} diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 278e7e0f3d..4640055546 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -858,6 +858,263 @@ fn a_rows_tint_tints_the_spot_color_the_art_links_to() { assert!(e.to_string().contains("`tint` must be a number"), "{e}"); } +/// A row's `swatch` (the swatch its new color was picked from) links its art to that swatch without +/// Limit to Library: a spot or global swatch gives linked tints, and a process swatch, a swatch +/// whose color is not the row's new color and a swatch that is not there link nothing. A `swatch` +/// that is not `{name, library?}` is refused. Randomize moves the swatch with its color. +#[test] +fn a_rows_swatch_links_its_art_without_limit_to_library() { + for (options, linked) in [(json!({"spot": true}), true), (json!({"global": true}), true), (json!({}), false)] { + let mut s = session(); + let mut w = json!({"name": "Ink", "color": "cmyk 0 100 0 0"}); + w.as_object_mut().unwrap().extend(options.as_object().unwrap().clone()); + run(&mut s, "swatch.new", w); + let dark = rect(&mut s, json!("gray 80")); + let light = rect(&mut s, json!("gray 40")); + select_all(&mut s); + let row = |swatch: Value| json!([{"from": ["gray 80", "gray 40"], "to": "cmyk 0 100 0 0", "swatch": swatch}]); + run(&mut s, "recolor.apply", json!({"map": row(json!({"name": "Ink"})), "method": "scaleTints"})); + let d = &s.doc().unwrap().doc; + let paint = |id: NodeId| match d.node(id).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { color, swatch, tint } => (color, swatch, tint), + p => panic!("{p:?}"), + }; + let ((c1, l1, t1), (c2, l2, t2)) = (paint(dark), paint(light)); + assert_eq!(l1.is_some() && l2.is_some(), linked, "{options}: {l1:?} {l2:?}"); + // A process swatch's row keeps the art's gray model (see the next test). + if linked { + assert!(t1 > t2 && t2 > 0.0, "{options}: the lighter gray is a lighter tint: {t1} {t2}"); + assert!(close(c1, Color::cmyk(0.0, 1.0, 0.0, 0.0)), "{options}: {c1:?}"); + } + assert!(!close(c2, c1), "{options}: {c1:?} {c2:?}"); + // Without the swatch the same row gives tints with no link. + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + run(&mut s, "recolor.apply", json!({"map": row(Value::Null), "method": "scaleTints"})); + assert_eq!(paint_link(&s, dark), None, "{options}: no swatch, no link"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // A swatch of another color than the row's new color links nothing. + let other = json!([{"from": ["gray 80", "gray 40"], "to": "#00ff00", "swatch": {"name": "Ink", "library": "document"}}]); + run(&mut s, "recolor.apply", json!({"map": other, "method": "scaleTints"})); + assert_eq!(paint_link(&s, dark), None, "{options}: another color"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // With a Global Adjust the art takes the adjusted colors, not the swatch. + let adjust = json!({"saturation": -40}); + run(&mut s, "recolor.apply", json!({"map": row(json!({"name": "Ink"})), "method": "scaleTints", "globalAdjust": adjust})); + assert_eq!(paint_link(&s, dark), None, "{options}: adjusted"); + assert!(!close(fill(&s, dark), Color::cmyk(0.0, 1.0, 0.0, 0.0)), "{options}: the adjustment applies"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // A swatch or library that is not there (deleted since the pick) links nothing, and the result + // names it. + for gone in [json!({"name": "Missing"}), json!({"name": "Ink", "library": "nowhere"})] { + let r = run(&mut s, "recolor.apply", json!({"map": row(gone.clone()), "method": "scaleTints"})); + assert_eq!(paint_link(&s, dark), None, "{options}: {gone}"); + assert_eq!(r["swatchesNotFound"], json!([gone["name"]]), "{options}: {r}"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + } + for bad in [json!("Ink"), json!({"name": ""}), json!({"name": "Ink", "library": 3})] { + let e = s.execute("recolor.apply", &json!({"map": row(bad.clone())})).unwrap_err(); + assert!(e.to_string().contains("`swatch` must be"), "{bad}: {e}"); + } + let two = json!([ + {"from": ["gray 80"], "to": "cmyk 0 100 0 0", "swatch": {"name": "Ink"}}, + {"from": ["gray 40"], "to": "#00ff00"}, + ]); + let r = run(&mut s, "recolor.randomize", json!({"map": two, "seed": 3})); + let rows = r["map"].as_array().unwrap(); + let ink = rows.iter().find(|r| r["to"] == "cmyk 0 100 0 0").unwrap(); + let green = rows.iter().find(|r| r["to"] == "rgb 0 255 0").unwrap(); + assert_eq!(ink["swatch"], json!({"name": "Ink", "library": "document"}), "{r}"); + assert!(green.get("swatch").is_none(), "{r}"); + let r = run(&mut s, "recolor.randomize", json!({"map": two, "order": false, "saturationBrightness": true, "seed": 3})); + let rows = r["map"].as_array().unwrap(); + assert_eq!(rows.len(), 2, "{r}"); + assert!(rows.iter().all(|r| r.get("swatch").is_none()), "a changed color drops its swatch: {r}"); + } +} + +/// A swatch whose components are finer than a color key's hundredths still links the art of the row +/// whose new color is its key. +#[test] +fn a_rows_swatch_with_a_finer_color_than_its_key_still_links() { + let mut s = session(); + let ink = Color::cmyk(0.123_456, 0.876_543, 0.0, 0.0); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0.123_456, "m": 0.876_543, "y": 0.0, "k": 0.0}, "spot": true})); + let id = rect(&mut s, json!("gray 50")); + select_all(&mut s); + let to = vectorcraft_color::recolor::ColorKey::of(&ink).to_string(); + run(&mut s, "recolor.apply", json!({"map": [{"from": ["gray 50"], "to": to, "swatch": {"name": "Ink"}}], "method": "scaleTints"})); + assert_eq!(paint_link(&s, id).as_deref(), Some("Ink")); + assert!(close(fill(&s, id), ink), "the swatch's own color: {:?}", fill(&s, id)); +} + +/// A row's `swatch` that is a global swatch of the group being rewritten with another color links +/// nothing: the row's art takes the row's new color as with no swatch, in its own model and without +/// the row's tint of the swatch. A swatch of the group that keeps its color still links the art. +#[test] +fn a_rows_swatch_in_the_rewritten_group_keeps_the_rows_new_color() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Red Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Blue Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.newGroup", json!({"name": "G", "swatches": ["Red Ink", "Blue Ink"]})); + let red = rect(&mut s, json!("#ff0000")); + let blue = rect(&mut s, json!("#0000ff")); + select_all(&mut s); + let map = |first: &str| { + json!([ + {"from": ["#ff0000"], "to": first}, + {"from": ["#0000ff"], "to": "#ff0000", "swatch": {"name": "Red Ink"}}, + ]) + }; + run(&mut s, "recolor.apply", json!({"map": map("#00ff00"), "group": "G"})); + let ink = |s: &Session| s.doc().unwrap().doc.swatch("Red Ink").unwrap().paint.color().unwrap().to_hex(); + assert_eq!(ink(&s), "#00ff00", "the group is rewritten"); + assert_eq!(fill(&s, red).to_hex(), "#00ff00"); + assert_eq!(fill(&s, blue).to_hex(), "#ff0000", "the blue art keeps its row's new color"); + assert_eq!(paint_link(&s, blue), None); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // Also at a row tint of 0, where Red Ink's old and new colors both show white. + let mut zero = map("#00ff00"); + zero[1]["tint"] = json!(0); + run(&mut s, "recolor.apply", json!({"map": zero, "group": "G"})); + assert_eq!(paint_link(&s, blue), None, "at a tint of 0"); + assert_eq!(fill(&s, blue).to_hex(), "#ff0000", "the row's new color, as with no swatch"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // Red Ink is rewritten with its own color, so the blue art links to it. + run(&mut s, "recolor.apply", json!({"map": map("#ff0000"), "group": "G"})); + assert_eq!(ink(&s), "#ff0000"); + assert_eq!(fill(&s, blue).to_hex(), "#ff0000"); + assert_eq!(paint_link(&s, blue).as_deref(), Some("Red Ink")); + run(&mut s, "edit.undo", json!({})); + // A CMYK swatch of a group rewritten with another color: the RGB art takes the row's new color + // as the row without the swatch gives it, in the art's own model. + run(&mut s, "swatch.new", json!({"name": "Cyan Ink", "color": "cmyk 100 0 0 0", "global": true})); + run(&mut s, "swatch.newGroup", json!({"name": "C", "swatches": ["Cyan Ink"]})); + let result = |s: &mut Session, swatch: Value| { + select_all(s); + let map = json!([{"from": ["#0000ff"], "to": "cmyk 100 0 0 0", "swatch": swatch}]); + let r = run(s, "recolor.apply", json!({"map": map, "group": "C", "groupColors": ["#00ff00"]})); + let out = (fill(s, blue), paint_link(s, blue), r.get("note").cloned()); + run(s, "edit.undo", json!({})); + out + }; + let alone = result(&mut s, Value::Null); + assert!(alone.2.is_some(), "the RGB art keeps its model: {alone:?}"); + assert_eq!(result(&mut s, json!({"name": "Cyan Ink"})), alone); +} + +/// A row's `swatch` from a loaded library links the art to it and adds it to the document's +/// swatches; of two library swatches with the same name, the one with the row's new color is used, +/// and rows that pick the same one link to one added swatch; of a process and a spot swatch with +/// one name and color, the first is used; and a process swatch recolors as the row's new color +/// alone does, in the color model `model` gives. +#[test] +fn a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "cmyk 0 100 0 0", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Twin", "color": "cmyk 100 0 0 0", "spot": true})); + let data = run(&mut s, "swatch.library.save", json!({"names": ["Ink", "Twin"], "name": "Inks"}))["data"].as_str().unwrap().to_string(); + // Both of the library's swatches are named Ink. + let data = data.replace("\"Twin\"", "\"Ink\""); + let lib = run(&mut s, "swatch.library.load", json!({"data": data, "name": "inks.vcswatches"}))["library"].as_str().unwrap().to_string(); + run(&mut s, "swatch.delete", json!({"names": ["Ink", "Twin"]})); + let id = rect(&mut s, json!("gray 50")); + select_all(&mut s); + let row = |to: &str| json!([{"from": ["gray 50"], "to": to, "swatch": {"name": "Ink", "library": lib}}]); + let r = run(&mut s, "recolor.apply", json!({"map": row("cmyk 100 0 0 0"), "method": "scaleTints"})); + assert_eq!(r["swatches"], json!(["Ink"]), "{r}"); + let d = &s.doc().unwrap().doc; + let w = d.swatch("Ink").unwrap(); + assert!(w.spot && close(w.paint.color().unwrap(), Color::cmyk(1.0, 0.0, 0.0, 0.0)), "the swatch of the row's color joined: {w:?}"); + assert_eq!(paint_link(&s, id).as_deref(), Some("Ink")); + assert!(close(fill(&s, id), Color::cmyk(1.0, 0.0, 0.0, 0.0)), "{:?}", fill(&s, id)); + run(&mut s, "edit.undo", json!({})); + + // Three rows that pick the magenta, the cyan and again the cyan Ink: the two cyan rows link to + // one swatch added to the document. + let more = [rect(&mut s, json!("gray 20")), rect(&mut s, json!("gray 80"))]; + select_all(&mut s); + let three = json!([ + {"from": ["gray 50"], "to": "cmyk 0 100 0 0", "swatch": {"name": "Ink", "library": lib}}, + {"from": ["gray 20"], "to": "cmyk 100 0 0 0", "swatch": {"name": "Ink", "library": lib}}, + {"from": ["gray 80"], "to": "cmyk 100 0 0 0", "swatch": {"name": "Ink", "library": lib}}, + ]); + let r = run(&mut s, "recolor.apply", json!({"map": three, "method": "scaleTints"})); + assert_eq!(r["swatches"].as_array().map(Vec::len), Some(2), "{r}"); + let (a, b, c) = (paint_link(&s, id), paint_link(&s, more[0]), paint_link(&s, more[1])); + assert!(a.is_some() && b.is_some() && a != b && b == c, "{a:?} {b:?} {c:?}"); + run(&mut s, "edit.undo", json!({})); + + // Of a process and a spot swatch with one name and color, the first, the process one, is used. + run(&mut s, "swatch.new", json!({"name": "Pair", "color": "cmyk 0 0 100 0"})); + run(&mut s, "swatch.new", json!({"name": "Pear", "color": "cmyk 0 0 100 0", "spot": true})); + let data = run(&mut s, "swatch.library.save", json!({"names": ["Pair", "Pear"], "name": "Pairs"}))["data"] + .as_str() + .unwrap() + .replace("\"Pear\"", "\"Pair\""); + let pairs = run(&mut s, "swatch.library.load", json!({"data": data, "name": "pairs.vcswatches"}))["library"].as_str().unwrap().to_string(); + run(&mut s, "swatch.delete", json!({"names": ["Pair", "Pear"]})); + select_all(&mut s); + let map = json!([{"from": ["gray 50"], "to": "cmyk 0 0 100 0", "swatch": {"name": "Pair", "library": pairs}}]); + run(&mut s, "recolor.apply", json!({"map": map, "method": "scaleTints"})); + assert_eq!(paint_link(&s, id), None, "the process swatch"); + run(&mut s, "edit.undo", json!({})); + + // A global process Ink and a spot Ink of one color, from two libraries, while the document's Ink + // is another color: each row links to its own added swatch. + let mut libraries = vec![]; + for (file, kind) in [("global.vcswatches", json!({"global": true})), ("spot.vcswatches", json!({"spot": true}))] { + let mut w = json!({"name": "Ink", "color": "cmyk 0 0 0 100"}); + w.as_object_mut().unwrap().extend(kind.as_object().unwrap().clone()); + run(&mut s, "swatch.new", w); + let data = run(&mut s, "swatch.library.save", json!({"names": ["Ink"], "name": file}))["data"].as_str().unwrap().to_string(); + libraries.push(run(&mut s, "swatch.library.load", json!({"data": data, "name": file}))["library"].as_str().unwrap().to_string()); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + } + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#00ff00"})); + select_all(&mut s); + let two = json!([ + {"from": ["gray 50"], "to": "cmyk 0 0 0 100", "swatch": {"name": "Ink", "library": libraries[0]}}, + {"from": ["gray 20"], "to": "cmyk 0 0 0 100", "swatch": {"name": "Ink", "library": libraries[1]}}, + ]); + let r = run(&mut s, "recolor.apply", json!({"map": two, "method": "scaleTints"})); + assert_eq!(r["swatches"].as_array().map(Vec::len), Some(2), "{r}"); + let (global, spot) = (paint_link(&s, id).unwrap(), paint_link(&s, more[0]).unwrap()); + let d = &s.doc().unwrap().doc; + assert!(global != spot && !d.swatch(&global).unwrap().spot && d.swatch(&spot).unwrap().spot, "{global} {spot}"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + select_all(&mut s); + + run(&mut s, "swatch.new", json!({"name": "Leaf", "color": "cmyk 60 0 100 10"})); + select_all(&mut s); + let fills = |s: &mut Session, swatch: Value, model: &str| { + let map = json!([{"from": ["gray 50"], "to": "cmyk 60 0 100 10", "swatch": swatch}]); + let r = run(s, "recolor.apply", json!({"map": map, "method": "scaleTints", "model": model})); + let paint = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + run(s, "edit.undo", json!({})); + select_all(s); + (paint, r.get("note").cloned()) + }; + for model in ["keep", "new", "document"] { + let alone = fills(&mut s, Value::Null, model); + assert_eq!(fills(&mut s, json!({"name": "Leaf"}), model), alone, "{model}: a process swatch is its color"); + } +} + +fn paint_link(s: &Session, id: NodeId) -> Option { + match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { swatch, .. } => swatch, + p => panic!("{p:?}"), + } +} + /// Randomize order moves a row's tint with its new color; changing saturation and brightness /// drops the tint of every color it changes. #[test] @@ -1831,6 +2088,76 @@ fn theme_picker_leaves_out_art_a_curved_clipping_path_hides() { assert_eq!(pick_theme(&mut s, all), ["rgb 255 0 0"], "the corner square is hidden"); } +/// A filled rectangle without a stroke. +fn filled(s: &mut Session, [x, y, w, h]: [f64; 4], fill: &str) -> NodeId { + let id = NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap()); + run(s, "paint.setFill", json!({"ids": [id.0], "color": fill})); + run(s, "paint.setStroke", json!({"ids": [id.0], "none": true})); + id +} + +/// An enabled opacity mask that clips shows the art only where its mask art is lighter than black: white mask art over +/// the red square of three lets red alone through, and black mask art hides all three. Inside a clip group, the masked +/// art shows only where the mask and the clipping path both let it. +#[test] +fn theme_picker_reads_only_what_a_clipping_opacity_mask_shows() { + let all = json!({"picks": [{"rect": [-10, -10, 120, 110]}]}); + // A red, a blue and a green square under one mask. + let masked = |[red, blue, green]: [[f64; 4]; 3], mask_art: [f64; 4], mask_fill: &str| { + let mut s = session(); + let red = filled(&mut s, red, "#ff0000"); + let blue = filled(&mut s, blue, "#0000ff"); + let green = filled(&mut s, green, "#00ff00"); + let mask = filled(&mut s, mask_art, mask_fill); + run(&mut s, "select.set", json!({"ids": [red.0, blue.0, green.0, mask.0]})); + let g = NodeId(run(&mut s, "transparency.makeOpacityMask", json!({"clip": true}))["id"].as_u64().unwrap()); + (s, g) + }; + // Red runs from x 10 to 25, blue from 40 to 55 and green from 70 to 85; the mask art covers red alone. + let in_a_row = [[10.0, 10.0, 15.0, 15.0], [40.0, 10.0, 15.0, 15.0], [70.0, 10.0, 15.0, 15.0]]; + let over_red = [5.0, 5.0, 25.0, 25.0]; + let (mut s, _) = masked(in_a_row, over_red, "#ffffff"); + assert_eq!(pick_theme(&mut s, all.clone()), ["rgb 255 0 0"], "white mask art over the red square"); + let (mut s, _) = masked(in_a_row, over_red, "#000000"); + assert!(pick_theme(&mut s, all.clone()).is_empty(), "black mask art hides every square"); + // Red sits in the top left corner of a 100 × 100 ellipse's box, outside the ellipse; blue and green are inside it. + // The mask art covers red and blue, and the ellipse clips the masked group. + let around_an_ellipse = [[0.0, 0.0, 8.0, 8.0], [40.0, 40.0, 15.0, 15.0], [70.0, 40.0, 15.0, 15.0]]; + let (mut s, g) = masked(around_an_ellipse, [-5.0, -5.0, 65.0, 65.0], "#ffffff"); + let e = NodeId(run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 100, "height": 100}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [g.0, e.0]})); + run(&mut s, "object.clippingMask.make", json!({})); + assert_eq!(pick_theme(&mut s, all), ["rgb 0 0 255"], "only blue shows through both"); +} + +/// A blend a marquee touches is read whole: a marquee over a middle step alone takes the colors of both end objects, +/// also when a clip group around the blend hides the end objects. +#[test] +fn theme_picker_reads_a_blend_whole() { + let mut s = session(); + let circle = |s: &mut Session, x: f64, fill: &str| { + let id = NodeId(run(s, "shape.ellipse", json!({"x": x, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap()); + run(s, "paint.setFill", json!({"ids": [id.0], "color": fill})); + run(s, "paint.setStroke", json!({"ids": [id.0], "none": true})); + id + }; + // The end objects are centered on x 20 and 260; the 3 steps between them on x 80, 140 and 200. + let (red, blue) = (circle(&mut s, 10.0, "#ff0000"), circle(&mut s, 250.0, "#0000ff")); + run(&mut s, "select.set", json!({"ids": [red.0, blue.0]})); + let blend = NodeId(run(&mut s, "object.blend.make", json!({"steps": 3}))["id"].as_u64().unwrap()); + let middle = json!({"picks": [{"rect": [135, 15, 145, 25]}]}); + let mut got = pick_theme(&mut s, middle.clone()); + got.sort(); + assert_eq!(got, ["rgb 0 0 255", "rgb 255 0 0"], "the middle step gives both end colors"); + // A clipping path over the middle step alone. + let clip = filled(&mut s, [120.0, 5.0, 40.0, 30.0], "#00ff00"); + run(&mut s, "select.set", json!({"ids": [blend.0, clip.0]})); + run(&mut s, "object.clippingMask.make", json!({})); + let mut got = pick_theme(&mut s, middle); + got.sort(); + assert_eq!(got, ["rgb 0 0 255", "rgb 255 0 0"], "the clip group around the blend leaves the end objects in"); +} + /// In isolation mode a click and a marquee read only the isolated art. #[test] fn theme_picker_reads_only_the_isolated_art() { diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 1432b8671b..cdb3275607 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -262,6 +262,82 @@ fn steps_act_on_the_artboard_active_as_they_run() { assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it"); } +/// After the script makes another artboard active with `setActiveArtboardIndex`, a step that acts +/// on the active artboard acts on that one. +#[test] +fn steps_act_on_the_artboard_the_script_made_active() { + 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, 0); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]); + log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1); app.doScript('Fit', 'Set');", &actions); + let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(now[0], was[0], "the artboard active as the run started is unchanged"); + assert_ne!(now[1], was[1], "the artboard the script made active is fitted"); + // Choosing the artboard that is already active, after an insert moved it, also counts. + make_active(&mut s, 0); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + log_with( + &mut s, + "var b = app.activeDocument.artboards; b.insert([300, 300, 400, 200], 0); b.setActiveArtboardIndex(1); app.doScript('Fit', 'Set');", + &actions, + ); + let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_ne!(now[1], was[0], "the artboard chosen again is fitted"); +} + +#[test] +fn steps_use_the_chosen_index_when_the_chosen_artboard_is_deleted() { + 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, 2); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]); + let report = run_with( + &mut s, + "var b = app.activeDocument.artboards; b.setActiveArtboardIndex(2); b.remove(2);\ + vc.log(b.getActiveArtboardIndex()); app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;\ + vc.log(app.activeDocument.selection[0].position); app.doScript('Fit', 'Set');", + &actions, + ) + .unwrap(); + assert_eq!(report["log"], json!([0, [10, 10]])); + assert_eq!(report["activeArtboards"], json!([{"document": 0, "artboard": 0}])); + let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(now.len(), 2); + assert_ne!(now[0], was[0], "the fallback artboard is fitted"); + assert_eq!(now[1], was[1], "the other artboard is unchanged"); +} + +#[test] +fn steps_discard_the_chosen_artboard_after_revert() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("script-actions-revert-artboard"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + make_active(&mut s, 2); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]); + log_with( + &mut s, + "app.activeDocument.artboards.setActiveArtboardIndex(0); app.activeDocument.pageItems[0].name = 'changed'; vc.run('file.revert');\ + app.activeDocument.selection = app.activeDocument.pageItems[0]; app.doScript('Fit', 'Set');", + &actions, + ); + let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(now[..2], was[..2]); + assert_ne!(now[2], was[2], "playback uses the run's original index after revert"); +} + /// 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] @@ -382,6 +458,18 @@ fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { 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"); + // Once the script makes an artboard active, the selection from the start of the run no longer holds. + let (mut s, was, _) = setup(); + let before = objects(&s); + log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1); app.doScript('Paste', 'Set');", &actions); + assert_eq!(objects(&s), before + 1, "one copy, on the artboard the script made active"); + let pasted = s.active().unwrap().selection.objects.clone(); + let copy = s.active().unwrap().doc.bounds_of(&pasted, false).unwrap(); + assert!(copy.x0 >= was[1].x0 && copy.x1 <= was[1].x1, "the copy is on artboard 1: {copy:?}"); + let (mut s, was, art) = setup(); + log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(2); app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards, [was[0], was[1], art[2]], "only the artboard the script made active fits its 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(); diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index baa8989208..0ebb346fe7 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -200,6 +200,30 @@ fn prompt_cancel_returns_null() { assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([true])); } +/// A prompt's answer that the engine's nearly full heap cannot hold ends the run, and the report +/// lists the prompt with the answer `"error"`, not the text that did not reach the script. +#[test] +fn a_prompt_answer_that_cannot_reach_the_script_is_listed_as_an_error() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20))); + let mut s = one_doc(); + let filled = headless( + &mut s, + "#targetengine full\nvar head = null, c = 'x';\nwhile (c.length < 4096) c += c;\nfor (var i = 0; ; i++) head = {s: c + i, n: head};", + json!([]), + ); + framed(&mut s, "#targetengine full\nvar a = prompt('Name', '');"); + let waited = pump(&mut s).is_none(); + let answered = s.script_answer(DialogAnswer::Prompt(Some("x".repeat(dialogs::MAX_PROMPT_BYTES)))); + let ended = pump(&mut s); + let report = s.script_report(); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert!(filled.unwrap_err().to_string().contains("Heap")); + assert!(waited && answered); + assert!(ended.unwrap().is_err(), "the answer did not fit in the heap"); + assert_eq!(report.unwrap()["dialogs"][0]["answer"], "error"); +} + #[test] fn dialog_loop_stops_or_exhausts() { let mut s = one_doc(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index f731eef72d..a982c82575 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -134,6 +134,117 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +/// `controlBounds` takes in the direction handles of a curve, which reach past its visible bounds. +#[test] +fn control_bounds_take_in_the_direction_handles() { + let (mut s, _, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.selection[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let top = |v: &Value| v[1].as_f64().unwrap(); + assert!(top(&out[0]) < 180.0, "{out:?}"); + assert_eq!(top(&out[1]), 200.0, "{out:?}"); + assert_eq!(out[1][2].as_f64().unwrap(), out[0][2].as_f64().unwrap(), "{out:?}"); +} + +/// The `controlBounds` of a group leave out the handles of a hidden curve in it. +#[test] +fn control_bounds_leave_out_hidden_paths() { + let (mut s, a, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 -400 200 -400 200 200"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, id]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"id": id, "visible": false})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.selection[0].parent; vc.log(g.visibleBounds); vc.log(g.controlBounds);"); + assert_eq!(out[1], out[0], "{out:?}"); +} + +/// Each anchor `controlBounds` visits counts toward the data a run passes, so reading the bounds of +/// a large path again and again ends the run where reading its geometric bounds does not. +#[test] +fn control_bounds_count_the_anchors_they_visit() { + let (mut s, _, _) = doc(); + let d: String = (0..2000u32).map(|i| format!(" L{} {}", i % 300, (i * 7) % 200)).collect(); + let id = s.execute("path.create", &json!({"d": format!("M0 0{d}")})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + // 100 reads of 2001 anchors are about 200 KB of steps, over a 64 KiB limit. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let read = |s: &mut Session, what: &str| run(s, &format!("var i = app.activeDocument.selection[0]; for (var n = 0; n < 100; n++) i.{what};")); + let geometric = read(&mut s, "geometricBounds"); + let control = read(&mut s, "controlBounds"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + geometric.unwrap(); + let e = control.unwrap_err().to_string(); + assert!(e.contains("passed more data"), "{e}"); +} + +/// The `controlBounds` of a clip group leave out the handles of the clipped art past the clipping +/// path. +#[test] +fn control_bounds_of_a_clip_group_come_from_its_clipping_path() { + let (mut s, _, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 -400 200 -400 200 200"})).unwrap()["id"].as_u64().unwrap(); + let mask = rect(&mut s, 100.0, 150.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.clipped); vc.log(g.visibleBounds); vc.log(g.controlBounds);"); + assert_eq!(out[0], json!(true), "{out:?}"); + assert_eq!(out[2], out[1], "{out:?}"); +} + +/// `controlBounds` takes in the Bézier handles of a path, which can reach past what it draws. +#[test] +fn page_item_control_bounds_take_in_the_handles() { + let (mut s, _, _) = doc(); + let anchors = json!([{"x": 0, "y": 100, "out": [0, 0]}, {"x": 100, "y": 100, "in": [100, 0]}]); + s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let b = |v: &Value| -> Vec { v.as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect() }; + let (visible, control) = (b(&out[0]), b(&out[1])); + assert!(visible[1] < 290.0, "the curve stays well under its handles: {visible:?}"); + assert!((control[1] - 300.0).abs() < 1e-9, "the handles reach the top of the page: {control:?}"); + assert!(control[0] <= visible[0] && control[2] >= visible[2] && control[3] <= visible[3], "{visible:?} {control:?}"); +} + +#[test] +fn control_bounds_include_handles_inside_live_containers() { + for command in ["object.blend.make", "object.envelope.makeWithMesh", "object.repeat.grid", "object.intertwine.make"] { + let (mut s, _, _) = doc(); + let path = s + .execute("path.create", &json!({"anchors": [{"x": 200, "y": 0, "out": [200, -100]}, {"x": 300, "y": 0, "in": [300, -100]}]})) + .unwrap()["id"] + .as_u64() + .unwrap(); + let other = rect(&mut s, 210.0, 10.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [path, other.0]})).unwrap(); + let params = match command { + "object.blend.make" => json!({"steps": 2}), + "object.envelope.makeWithMesh" | "object.repeat.grid" => json!({"rows": 1, "cols": 1}), + _ => json!({}), + }; + s.execute(command, ¶ms).unwrap(); + let out = log( + &mut s, + "app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var p = app.activeDocument.selection[0];\ + vc.log(p.controlBounds[1] < p.visibleBounds[1]);", + ); + assert_eq!(out, [json!(true)], "{command}"); + } +} + +#[test] +fn control_bounds_take_in_the_direction_points() { + let (mut s, _, _) = doc(); + // An arch whose top is at y 40 and whose direction points are at y 20. + let id = s.execute("path.create", &json!({"d": "M100 100C100 20 200 20 200 100"})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.selection[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let top = |v: &Value| v[1].as_f64().unwrap_or(f64::NAN); + assert!(top(&out[0]) < 265.0, "{out:?}"); + assert_eq!(top(&out[1]), 280.0, "{out:?}"); +} + #[test] fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { let (mut s, a, b) = doc(); @@ -186,6 +297,58 @@ fn page_item_size_and_position_setters_measure_type_in_a_back_document_after_the assert_eq!(s.active().unwrap().uid, front, "the front document stays in front"); } +/// The getters measure type in a document in the back as the setters do, so assigning an item's +/// own width, height, left, top or position back to it changes nothing and makes no undo step, +/// and for an object without type the document is not switched to. +#[test] +fn page_item_geometry_read_from_a_back_document_assigns_back_without_a_change() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + rect(&mut s, 200.0, 20.0, 30.0, 40.0); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Wide type here", "size": 40})).unwrap()["id"].as_u64().unwrap()); + let uid = s.active().unwrap().uid; + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let front = s.active().unwrap().uid; + let back = |s: &Session| s.documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.history.undo.len()); + let steps = back(&s); + let sets = ["t.width = t.width;", "t.height = t.height;", "t.left = t.left;", "t.top = t.top;", "t.position = t.position;"]; + for (kind, set) in sets.iter().flat_map(|set| [("TextFrame", set), ("PathItem", set)]) { + let st = s.document_mut(uid).unwrap(); + if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) { + t.cached_bounds = None; + t.cached_baselines.clear(); + } + // A switch to the back document and back again would stamp the front document anew. + let stamp = s.active().unwrap().activated; + let out = log( + &mut s, + &format!( + "var p = app.documents[1].pageItems, t = p[0].typename == '{kind}' ? p[0] : p[1];\ + var w = t.width, x = t.left; {set} vc.log(t.width - w); vc.log(t.left - x);" + ), + ); + assert_eq!(out.len(), 2, "{kind} {set}"); + for d in &out { + assert!(d.as_f64().unwrap().abs() < 1e-6, "{kind} {set} moved or resized the item by {d}"); + } + assert_eq!(back(&s), steps, "{kind} {set} made an undo step"); + if kind == "PathItem" { + assert_eq!(s.active().unwrap().activated, stamp, "{set} switched documents"); + } + } + assert_eq!(s.active().unwrap().uid, front, "the front document stays in front"); + let st = s.document_mut(uid).unwrap(); + if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) { + t.cached_bounds = None; + t.cached_baselines.clear(); + } + let in_back = log(&mut s, "vc.log(app.documents[1].pageItems[0].width);"); + let index = s.documents().iter().position(|d| d.uid == uid).unwrap(); + s.execute("document.activate", &json!({"index": index})).unwrap(); + let in_front = log(&mut s, "vc.log(app.activeDocument.pageItems[0].width);"); + assert_eq!(in_back, in_front, "the width read in the back is the width read in front"); +} + /// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the /// visible bounds. #[test] @@ -439,6 +602,36 @@ fn app_undo_and_redo_step_through_the_runs_edits() { assert!(failure(&mut s, "app.redo();").contains("No active document")); } +/// A layer, page item or artboard read before `app.undo()` took it away is stale, even when an +/// object added afterwards takes its id; one that `app.redo()` brings back, and one that was there +/// before the undone step, still work. +#[test] +fn a_handle_from_before_an_undo_does_not_name_a_later_object() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, kept = d.layers[0], m;\ + var a = d.layers.add(); app.undo(); var b = d.layers.add(); b.name = 'b';\ + m = ''; try { a.name = 'x'; } catch (e) { m = e.message; } vc.log([m, b.name]);\ + m = ''; try { a.groupItems.length; } catch (e) { m = e.message; } vc.log(m);\ + var p = d.groupItems.add(); app.undo(); var q = d.groupItems.add(); q.name = 'q';\ + m = ''; try { p.name = 'y'; } catch (e) { m = e.message; } vc.log([m, q.name]);\ + var r = d.artboards.add([500, 300, 700, 100]); app.undo(); var t = d.artboards.add([800, 300, 1000, 100]); t.name = 't';\ + m = ''; try { r.name = 'z'; } catch (e) { m = e.message; } vc.log([m, t.name]);\ + var c = d.layers.add(); app.undo(); app.redo(); c.name = 'c'; kept.name = 'kept'; vc.log([c.name, kept.name]);", + ); + assert_eq!( + out, + vec![ + json!(["Stale layer", "b"]), + json!("Stale layer"), + json!(["Stale page item", "q"]), + json!(["Stale artboard", "t"]), + json!(["c", "kept"]), + ] + ); +} + /// An opacity a graph mark already has still replaces the opacity another mark of its series left on /// the graph, as `object.setProps` does. #[test] @@ -561,6 +754,23 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(undo_steps(&s), steps + 1); } +/// An item's or a layer's opacity that differs from the reported one, however little, is set as +/// given. +#[test] +fn an_opacity_near_the_reported_one_is_still_set() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 0})).unwrap(); + let out = log( + &mut s, + "var q = app.activeDocument.pageItems, i = q[0].opacity === 0 ? q[0] : q[1]; i.opacity = 0.00009; vc.log(i.opacity);\ + var l = app.activeDocument.layers[0]; l.opacity = 0; l.opacity = 0.00009; vc.log(l.opacity);", + ); + assert_eq!(out, vec![json!(0.0001), json!(0.0001)]); + let d = &s.active().unwrap().doc; + assert!(d.node(a).unwrap().opacity > 0.0); + assert!(d.node(d.layer_containing(a).unwrap()).unwrap().opacity > 0.0); +} + /// `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] @@ -606,6 +816,28 @@ fn blending_mode_reads_and_sets_the_objects_blend_mode() { } } +/// An opacity near the one an item has, but not the one it reports, is set. +#[test] +fn an_opacity_close_to_the_current_one_is_set() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; i.opacity = 50.00009; vc.log(i.opacity);"); + assert_eq!(out, vec![json!(50.0001)]); +} + +/// A layer opacity near the one the layer has, but not the one it reports, is set. +#[test] +fn a_layer_opacity_close_to_the_current_one_is_set() { + let (mut s, _, _) = doc(); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.opacity = 50; l.opacity = 50.00009; vc.log(l.opacity);"); + assert_eq!(out, vec![json!(50.0001)]); + // The same number again stores as the opacity the layer has, and runs no command. + let sets = |s: &Session| s.journal.iter().filter(|(id, _)| id == "object.setProps").count(); + let before = sets(&s); + log(&mut s, "app.activeDocument.layers[0].opacity = 50.00009;"); + assert_eq!(sets(&s), before); +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -613,6 +845,18 @@ fn selection_assignment_is_atomic_across_invalid_items() { let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); assert!(e.contains("Cannot select PathItem"), "{e}"); assert!(s.active().unwrap().selection.objects.is_empty()); + // In either order, the refused assignment leaves nothing selected while the script runs. + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + function pick(list) { var m = ''; try { d.selection = list; } catch (e) { m = e.message; } vc.log([m, d.selection.length === 0]); }\ + pick([p[0], p[1]]); pick([p[1], p[0]]);", + ); + assert_eq!(out.len(), 2); + for o in &out { + assert!(o[0].as_str().is_some_and(|m| m.contains("Cannot select PathItem")), "{o}"); + assert_eq!(o[1], json!(true), "{o}"); + } // With the valid item first and the error caught, the run sees the selection unchanged. let out = log( &mut s, @@ -672,6 +916,24 @@ fn control_bounds_take_in_direction_points_past_the_curve() { assert_eq!(out[2], out[3]); } +#[test] +fn a_failed_selection_assignment_leaves_the_selection_within_the_run() { + let (mut s, _, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + // The run goes on after the failed assignment, so nothing it ends with puts the selection back. + let c = rect(&mut s, 200.0, 20.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, open, shut;\ + for (var i = 0; i < p.length; i++) { if (p[i].locked) shut = p[i]; else if (!p[i].selected) open = p[i]; }\ + try { d.selection = [open, shut]; vc.log('assigned'); } catch (e) { vc.log(String(e.message).indexOf('Cannot select') >= 0); }\ + vc.log([d.selection.length, open.selected, d.selection[0].locked]);", + ); + assert_eq!(out, vec![json!(true), json!([1, false, false])]); + assert_eq!(s.active().unwrap().selection.objects, vec![c]); +} + #[test] fn a_guide_path_is_not_selected_while_guides_are_locked() { let (mut s, a, b) = doc(); @@ -814,6 +1076,45 @@ fn move_and_duplicate_place_by_element_placement() { assert!(e.contains("hidden or locked"), "{e}"); } +/// An object cannot go behind a clip group's clipping path; one put at the end of the group goes +/// directly above the clipping path. +#[test] +fn an_object_cannot_go_behind_a_clipping_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let kids = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::>(); + let before = kids(&s); + s.execute("object.setProps", &json!({"id": before[0].0, "name": "mask"})).unwrap(); + s.execute("object.setProps", &json!({"id": before[1].0, "name": "art"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.getByName('art').move(p.getByName('mask'), ElementPlacement.PLACEAFTER);"); + assert!(e.contains("an object cannot go below a clipping mask"), "{e}"); + assert_eq!(kids(&s), before); + // The clipping path moved directly below the object above it stays where it is. + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art'), ElementPlacement.PLACEAFTER);"); + assert_eq!(kids(&s), before); + assert_eq!(undo_steps(&s), steps); + // The clipping path put at the end of its own clip group stays where it is; put on top of the + // group's contents, it is refused. + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);"); + assert_eq!(kids(&s), before); + assert_eq!(undo_steps(&s), steps); + for place in ["INSIDE", "PLACEATBEGINNING"] { + let e = failure( + &mut s, + &format!("var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art').parent, ElementPlacement.{place});"), + ); + assert!(e.contains("the clipping path stays at the bottom of its clip group"), "{place}: {e}"); + assert_eq!(kids(&s), before, "{place}"); + } + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("object.setProps", &json!({"id": c.0, "name": "c"})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('c').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);"); + assert_eq!(kids(&s), [before[0], c, before[1]]); +} + #[test] fn a_copy_goes_beside_its_source() { let (mut s, a, b) = doc(); @@ -837,6 +1138,34 @@ fn a_copy_goes_beside_its_source() { assert!(e.contains("into itself"), "{e}"); } +/// A clipping group's clipping path stays at the bottom of the group, so an object cannot go +/// below it; above it is the bottom of the clipped art. +#[test] +fn nothing_goes_below_a_clipping_path() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "mask"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "loose"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let children = |s: &Session| -> Vec { s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect() }; + assert_eq!(children(&s)[0], b, "the clipping path is the group's first child"); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + for source in [ + "var p = app.activeDocument.pageItems; p.getByName('loose').move(p.getByName('mask'), ElementPlacement.PLACEAFTER);", + "var p = app.activeDocument.pageItems; p.getByName('loose').duplicate(p.getByName('mask'), ElementPlacement.PLACEAFTER);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("an object cannot go below a clipping mask"), "{source}: {e}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "a refused move changes nothing"); + assert_eq!(undo_steps(&s), steps); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('loose').move(p.getByName('mask'), ElementPlacement.PLACEBEFORE);"); + assert_eq!(children(&s), [b, c, a]); +} + #[test] fn a_copy_that_cannot_be_placed_is_deleted() { let mut s = Session::new(); @@ -1182,6 +1511,24 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { } } +#[test] +fn file_new_replays_legacy_fractional_and_large_rows() { + for (rows, rounded) in [(3.6, 4), (1000.4, 1000), (1000.5, 1000), (5000.0, 1000)] { + let params = json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": {"layout": "gridByColumn", "rows": rows}}); + let mut s = Session::new(); + // A direct call refuses a fraction or a count over 1000; a replay rounds it and keeps it to at most 1000. + let direct = Session::new().execute("file.new", ¶ms); + assert!(direct.is_err(), "{rows}: {direct:?}"); + s.replay("file.new", ¶ms).unwrap(); + let mut expected = Session::new(); + let mut params = params; + params["artboardLayout"]["rows"] = json!(rounded); + expected.execute("file.new", ¶ms).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|b| b.rect).collect::>(); + assert_eq!(boards(&s), boards(&expected)); + } +} + #[test] fn a_listed_preset_keeps_more_rows_than_artboards() { use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; @@ -1232,6 +1579,30 @@ fn an_edit_keeps_direct_selected_anchors() { assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); } +/// A path saved with selected segments and no anchor entry gets its segments back, and only the +/// anchors at their ends, which `select.segments` selects with them. +#[test] +fn an_edit_gives_a_path_with_only_segments_no_other_anchors() { + let (mut s, a, b) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "set"})).unwrap(); + let ends = s.active().unwrap().selection.anchors.get(&a).cloned(); + assert_eq!(ends.as_ref().map(|e| e.len()), Some(2)); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + s.active_mut().unwrap().selection.anchors.remove(&a); + let before = s.active().unwrap().selection.clone(); + assert!(before.segments.contains_key(&a) && !before.anchors.contains_key(&a)); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].duplicate(); p[1].zOrder(ZOrderMethod.SENDTOBACK);"); + assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.anchors.get(&a), ends.as_ref()); + assert_eq!(sel.segments.get(&a), before.segments.get(&a)); + let mut objects = sel.objects.clone(); + objects.sort(); + let mut was = before.objects.clone(); + was.sort(); + assert_eq!(objects, was, "the same objects are selected"); +} + #[test] fn selecting_an_item_keeps_the_direct_selected_anchors_of_others() { let (mut s, a, b) = doc(); @@ -1382,7 +1753,7 @@ fn assigning_the_selection_selects_a_symbol_or_on_path_group_as_a_whole() { } #[test] -fn a_held_image_stays_the_same_object_when_it_is_embedded() { +fn a_held_image_is_stale_when_it_is_embedded() { let dir = super::links::Folder::new("dom-embed"); let photo = dir.file("photo.png"); super::links::write(&photo, &super::links::png(20, 10, [255, 0, 0])); @@ -1392,11 +1763,12 @@ fn a_held_image_stays_the_same_object_when_it_is_embedded() { &mut s, &format!( "var i = app.activeDocument.pageItems[0]; vc.log(i.typename); vc.run('links.embed', {{ids: [{}]}});\ - var j = app.activeDocument.pageItems[0]; vc.log([i === j, i.typename, i instanceof RasterItem, i instanceof PlacedItem]);", + var j = app.activeDocument.pageItems[0], m = ''; try {{ i.typename; }} catch (e) {{ m = e.message; }}\ + vc.log([i === j, m, j.typename, j instanceof RasterItem, i instanceof PlacedItem]);", id.0 ), ); - assert_eq!(out, vec![json!("PlacedItem"), json!([true, "RasterItem", true, false])]); + assert_eq!(out, vec![json!("PlacedItem"), json!([false, "Stale page item", "RasterItem", true, true])]); } #[test] @@ -1436,11 +1808,11 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() { for source in [ "app.activeDocument.pageItems[0].isIsolated;", "app.activeDocument.pageItems[0].uuid = 'x';", - "app.activeDocument.pageItems[0].transform(5);", + "app.activeDocument.pageItems[0].bringInPerspective(0, 0);", ] { 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")); + assert!(failure(&mut s, "app.activeDocument.swatches = 1;").contains("Document.swatches 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.isIsolated;"); assert!(e.contains("Stale page item"), "{e}"); @@ -1692,6 +2064,46 @@ fn document_preset_applies_only_its_given_fields() { assert_eq!(s.documents().len(), 2, "settings the built-in preset refuses make no document"); } +#[test] +fn a_startup_preset_uses_its_own_size_beside_a_saved_preset_of_the_same_name() { + let mut s = Session::new(); + s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 300, "height": 200})).unwrap(); + let first = crate::cmd::newdoc::category(&s, "Print").unwrap().remove(0); + assert_eq!(first.name, "Letter"); + let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height]);"); + assert_eq!((out[0][0].as_f64(), out[0][1].as_f64()), (Some(first.width), Some(first.height)), "{out:?}"); +} + +#[test] +fn document_presets_hold_a_limited_amount_of_data() { + let mut s = Session::new(); + // A 4,096-byte title fits and replacing it does not add up; one byte more is refused. + let out = log( + &mut s, + "var t = 'x'; for (var k = 0; k < 12; k++) t += t; var p = new DocumentPreset();\ + for (var k = 0; k < 20; k++) p.title = t; vc.log(p.title.length);", + ); + assert_eq!(out, vec![json!(4096)]); + let e = failure(&mut s, "var t = 'x'; for (var k = 0; k < 12; k++) t += t; var p = new DocumentPreset(); p.title = t + 'x';"); + assert!(e.contains("the title is too long"), "{e}"); +} + +#[test] +fn moving_art_on_another_layer_keeps_the_current_layer() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.active().unwrap().current_layer().unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let b = s.active().unwrap().current_layer().unwrap(); + assert_ne!(a, b); + rect(&mut s, 10.0, 20.0, 30.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + s.active_mut().unwrap().active_layer = Some(a); + log(&mut s, "var i = app.activeDocument.pageItems[0]; i.left = i.left + 5; i.translate(5, 0);"); + assert_eq!(s.active().unwrap().current_layer(), Some(a)); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + #[test] fn headless_add_document_dialog_fails_without_creating() { let mut s = Session::new(); @@ -1703,6 +2115,69 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +/// A run's `addDocument` with Overprint Preview turns the view on when the run ends; a run that +/// fails leaves it off. +#[test] +fn add_document_with_overprint_preview_turns_it_on_when_the_run_ends() { + if !super::in_own_process("tests::script_dom::add_document_with_overprint_preview_turns_it_on_when_the_run_ends") { + return; + } + let mut s = Session::new(); + let overprint = |s: &mut Session| s.execute("view.proofSetup", &json!({})).unwrap()["overprintPreview"].clone(); + s.execute("view.overprintPreview", &json!({"on": false})).unwrap(); + let add = "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.OverprintPreview; app.documents.addDocument('Print', p);"; + let e = failure(&mut s, &format!("{add} throw new Error('stopped here');")); + assert!(e.contains("stopped here"), "{e}"); + assert_eq!(overprint(&mut s), false); + assert!(s.documents().is_empty()); + assert_eq!(log(&mut s, &format!("{add} vc.log(app.documents.length);")), vec![json!(1)]); + assert_eq!(overprint(&mut s), true); + assert_eq!(s.documents().len(), 1); + s.execute("view.overprintPreview", &json!({"on": false})).unwrap(); +} + +/// A run's `addDocument` reads the images the profile links to beside its file, as the person's +/// File › New does. +#[test] +fn add_document_reads_the_images_the_profile_links_to() { + let dir = std::env::temp_dir().join(format!("vc-script-newdoc-links-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + let img = craft_image_codecs::Image::from_raw( + 600, + 300, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [200u8, 30, 30, 255].repeat(600 * 300), + ) + .unwrap(); + let mut bytes = vec![]; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|b| bytes.extend_from_slice(&b)) + .unwrap(); + let pic = dir.join("logo.png"); + std::fs::write(&pic, &bytes).unwrap(); + s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": true})).unwrap(); + s.execute("symbol.new", &json!({"name": "Logo"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + let read = |s: &Session| { + let images = &s.doc().unwrap().doc.images; + !images.is_empty() && images.values().all(|b| !b.is_proxy()) + }; + s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert!(read(&s), "the person's File › New reads the linked image"); + // No document open when the run begins links to the image, so the run's gate alone does not + // let it be read. + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + log(&mut s, "app.documents.addDocument('Print');"); + assert!(read(&s), "a script's addDocument reads it too"); + let _ = std::fs::remove_dir_all(&dir); +} + /// `addDocumentNoUI(startupPreset)` makes the document `addDocument(startupPreset)` makes, and /// ignores the arguments after the preset's name. #[test] @@ -1757,6 +2232,63 @@ fn add_document_takes_only_a_document_preset() { assert_eq!(out, vec![json!(500)]); } +#[test] +fn document_preset_settings_are_limited_in_bytes() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(2 << 20))); + let mut s = Session::new(); + let out = log( + &mut s, + "#targetengine presets\nvar title = 'a'; while (title.length < 4092) title += 'a';\ + var presets = [];\ + for (var k = 0; k < 1000; k++) { var p = new DocumentPreset(); p.title = 'old'; presets.push(p); }\ + var message = '';\ + try { for (var k = 0; k < presets.length; k++) presets[k].title = title; }\ + catch (e) { message = e.name + ': ' + e.message; }\ + vc.log(message); vc.log(k > 0 && k < presets.length); vc.log(presets[k].title);\ + presets[0].title = 'x'; presets[k].title = title;\ + vc.log(presets[0].title); vc.log(presets[k].title === title);", + ); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert_eq!( + out, + vec![ + json!(format!("RangeError: the DocumentPreset settings would hold more than {} bytes", 2 << 20)), + json!(true), + json!("old"), + json!("x"), + json!(true), + ] + ); +} + +#[test] +fn a_new_document_preset_is_refused_past_the_byte_limit() { + use crate::script::TEST_ENGINE_HEAP; + let preset_bytes = 6 * std::mem::size_of::() + "DocumentArtboardLayout.GridByRow".len(); + TEST_ENGINE_HEAP.with(|h| h.set(Some(2 << 20))); + let mut s = Session::new(); + let out = log( + &mut s, + &format!( + "#targetengine presets\nvar title = 'a'; while (title.length < 4092) title += 'a';\ + var first = new DocumentPreset(); first.title = title;\ + try {{ for (var k = 0; k < 2000; k++) {{ var p = new DocumentPreset(); p.title = title; }} }} catch (e) {{}}\ + var message = '';\ + try {{ for (var k = 0; k < 10000; k++) new DocumentPreset(); }}\ + catch (e) {{ message = e.name + ': ' + e.message; }}\ + vc.log(message); vc.log(k < 10000);\ + first.title = title.substring({preset_bytes});\ + vc.log((new DocumentPreset()).width);\ + var again = ''; try {{ new DocumentPreset(); }} catch (e) {{ again = e.name + ': ' + e.message; }}\ + vc.log(again);" + ), + ); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + let message = json!(format!("RangeError: the DocumentPreset settings would hold more than {} bytes", 2 << 20)); + assert_eq!(out, vec![message.clone(), json!(true), json!(612), message]); +} + #[test] fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { let root = vectorcraft_testkit::TempDir::new("script-add-document-profile"); @@ -1963,6 +2495,66 @@ fn wrappers_go_stale_after_revert() { } } +/// A layer's or group's `pageItems` reads a name, `index` and `toString` as the document's does. +#[test] +fn a_layers_page_items_read_names_as_the_documents_do() { + let (mut s, _, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "Logo"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.layers[0].pageItems;\ + vc.log([p['Logo'].name, 'Logo' in p, 'none' in p, p[-1] === undefined, p.index(0).name, String(p)]);\ + var m = ''; try { p['none']; } catch (e) { m = e.message; } vc.log(m);\ + var n = ''; try { p.index(1.5); } catch (e) { n = e.message; } vc.log(n);", + ); + assert_eq!(out, vec![json!(["Logo", true, false, true, "Logo", "[PageItems]"]), json!("Not found"), json!("Not found")]); +} + +/// A layer's `textFrames.areaText` refuses a path in a locked layer and leaves it as it was. +#[test] +fn area_text_into_a_layer_refuses_a_locked_path() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "var d = app.activeDocument, p = d.pathItems[d.pathItems.length - 1], l = d.layers.add(); l.textFrames.areaText(p);"); + assert!(e.contains("hidden or locked"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert!(s.active().unwrap().doc.node(a).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))); +} + +/// `clipped` on a group on a locked artboard throws `Cannot edit` and keeps the group as it was. +#[test] +fn clipping_a_group_on_a_locked_artboard_is_refused() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.groupItems[0].clipped = true;"); + assert!(e.contains("Cannot edit"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert!(!s.active().unwrap().doc.layers[0].children().unwrap().iter().any(|n| n.clips())); +} + +/// A layer's or group's collection and an artboard read before File › Revert are stale after it, +/// while the document's own collections follow the loaded document. +#[test] +fn scoped_collections_and_artboards_go_stale_after_revert() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-scoped"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let held = "var d = app.activeDocument, p = d.layers[0].pageItems, g = d.layers[0].groupItems, ab = d.artboards[0], all = d.groupItems;\ + d.pageItems[0].name = 'changed'; vc.run('file.revert');"; + for (read, stale) in + [("p.length", "Stale page item"), ("g.length", "Stale page item"), ("ab.name", "Stale artboard"), ("ab.name = 'x'", "Stale artboard")] + { + let source = format!("{held} try {{ {read}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}"); + assert_eq!(log(&mut s, &source), vec![json!(stale)], "{read}"); + } + assert_eq!(log(&mut s, &format!("{held} vc.log(all.length); vc.log(d.artboards[0].name);")), vec![json!(0), json!("Artboard 1")]); +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { let (mut s, a, b) = doc(); @@ -2050,6 +2642,108 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +/// The `removeAll()` of a layer's or group's collections, and of `groupItems` and +/// `compoundPathItems`, refuses art on a locked artboard as the document's `pageItems.removeAll()` +/// does, and deletes nothing. +#[test] +fn scoped_remove_all_refuses_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": g, "name": "locked"})).unwrap(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + // A path and a group on a second, unlocked artboard, made last so each lists first in its + // scope, are not deleted either. + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 300})).unwrap(); + let u = rect(&mut s, 1300.0, 100.0, 20.0, 20.0); + let v = rect(&mut s, 1100.0, 100.0, 20.0, 20.0); + let w = rect(&mut s, 1150.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [v.0, w.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + for scope in [ + "app.activeDocument.layers[0].pageItems", + "app.activeDocument.layers[0].groupItems", + "app.activeDocument.groupItems", + "app.activeDocument.groupItems.getByName('locked').pageItems", + "app.activeDocument.layers[0].compoundPathItems", + "app.activeDocument.compoundPathItems", + ] { + // The error is caught, so the run keeps whatever `removeAll()` did before it threw. + let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);")); + assert!(out[0].as_str().is_some_and(|m| m.contains("cannot delete objects on a locked artboard")), "{scope}: {out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}"); + assert_eq!(undo_steps(&s), steps, "{scope}"); + let doc = &s.active().unwrap().doc; + assert!([u, v, w].iter().all(|i| doc.node(*i).is_some()), "{scope}"); + } + lock(&mut s, false); + let out = log(&mut s, "var d = app.activeDocument; d.layers[0].pageItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, vec![json!(0)]); +} + +/// `removeAll()` on a compound path's `pathItems` deletes its paths and keeps the compound path, +/// empty, as `remove()` on its last path does. +#[test] +fn removing_all_the_paths_of_a_compound_path_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length, app.activeDocument.compoundPathItems.length]);", + ); + assert_eq!(out, vec![json!(["CompoundPathItem", 0, 1])]); + assert!(s.active().unwrap().doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); + assert_eq!(undo_steps(&s), steps + 1); +} + +/// `move` leaves art on a locked artboard where it is, and a move that leaves an object where it +/// is runs no command, also in a layer whose ruler guides are above its art. +#[test] +fn move_refuses_art_on_a_locked_artboard_and_skips_a_move_to_the_same_place() { + let (mut s, a, b) = doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + let steps = undo_steps(&s); + // The topmost art, moved to the top of its layer, stays where it is. + log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, top = p[0];\ + for (var i = 1; i < p.length; i++) { if (p[i].zOrderPosition > top.zOrderPosition) top = p[i]; }\ + top.move(top.parent);", + ); + assert_eq!(undo_steps(&s), steps, "a move to the same place adds no step"); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let order = |s: &Session| format!("{:?}", (s.active().unwrap().doc.position(a), s.active().unwrap().doc.position(b))); + let before = order(&s); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].parent, ElementPlacement.PLACEATBEGINNING);"); + assert!(e.contains("Cannot move PathItem"), "{e}"); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1].parent, ElementPlacement.PLACEATEND);"); + assert!(e.contains("Cannot move PathItem"), "{e}"); + assert_eq!(order(&s), before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { let mut s = Session::new(); @@ -2353,7 +3047,1831 @@ fn select_tool_makes_the_named_tool_current_when_the_run_ends() { #[test] fn unsupported_members_say_so() { let (mut s, _, _) = doc(); - assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet")); + assert!(failure(&mut s, "app.activeDocument.swatches;").contains("Document.swatches is not available yet")); +} + +fn layer_names(s: &Session) -> Vec { + s.active().unwrap().doc.layers.iter().rev().map(|n| n.name.clone().unwrap_or_default()).collect() +} + +#[test] +fn layers_list_top_first_and_add_makes_the_new_layer_current() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers; vc.log(L.length); vc.log(L.typename); vc.log(L.parent.typename);\ + var n = L.add(); n.name = 'Top'; vc.log(L.length); vc.log(L[0].name); vc.log(d.activeLayer.name);\ + vc.log(L.getByName('Top').zOrderPosition); vc.log(L[1].zOrderPosition); vc.log(n.parent.typename);\ + var sub = L[1].layers.add(); sub.name = 'Sub'; vc.log(L[1].layers.length); vc.log(sub.parent.name);\ + vc.log(L.length); vc.log(L[5] === undefined); vc.log(L[1].pageItems.length); vc.log(L[1].pageItems[0].typename);\ + vc.log(sub.zOrderPosition);", + ); + let expected = [json!(1), json!("Layers"), json!("Document"), json!(2), json!("Top"), json!("Top"), json!(2), json!(1), json!("Document")]; + assert_eq!(out[..9], expected); + // A layer's pageItems hold its art, not its sublayers, and a sublayer's zOrderPosition counts + // only the layers beside it. + assert_eq!(out[9..], [json!(1), json!("Layer 1"), json!(2), json!(true), json!(2), json!("PathItem"), json!(1)]); + assert_eq!(layer_names(&s), ["Top", "Layer 1"]); + // One run is one undo step. + assert_eq!(undo_steps(&s), steps + 1); + let lid = s.active().unwrap().doc.layer_containing(a).unwrap(); + assert!(failure(&mut s, "app.activeDocument.layers.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.layers.getByName(5);").contains("give a name")); + assert_eq!(s.active().unwrap().doc.layer_containing(a), Some(lid)); +} + +#[test] +fn a_new_or_assigned_layer_stays_the_current_layer() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, base = d.layers[0];\ + var n = d.layers.add(); n.name = 'New'; vc.log(d.activeLayer.name);\ + d.activeLayer = base; vc.log(d.activeLayer.name);\ + d.activeLayer = n; vc.log(d.activeLayer.name);\ + var sub = base.layers.add(); sub.name = 'Sub'; vc.log(d.activeLayer.name);\ + vc.log(d.selection.length); vc.log(d.selection[0].layer.name);", + ); + assert_eq!(out, [json!("New"), json!("Layer 1"), json!("New"), json!("Sub"), json!(1), json!("Layer 1")]); + // The layer the script made current is still current after the run. + let st = s.active().unwrap(); + let current = st.current_layer().and_then(|l| st.doc.node(l)).and_then(|n| n.name.clone()); + assert_eq!(current.as_deref(), Some("Sub")); +} + +#[test] +fn a_new_layer_or_group_with_a_large_id_is_the_new_one() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The new ids, 2^53 + 1 and 2^53 + 3, are not exact as numbers. + for (id, source) in + [(1, "var l = app.activeDocument.layers.add(); l.name = 'made';"), (3, "var g = app.activeDocument.groupItems.add(); g.name = 'made';")] + { + let big = (1u64 << 53) + id; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + run(&mut s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + let d = &s.active().unwrap().doc; + assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("made"), "{source}"); + } +} + +#[test] +fn layer_properties_round_trip_and_reject_bad_values() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0];\ + l.name = 'Art'; l.printable = false; l.preview = false; l.opacity = 40; l.dimPlacedImages = true;\ + l.color = {red: 10, green: 20, blue: 30};\ + vc.log(l.name); vc.log(l.printable); vc.log(l.preview); vc.log(l.opacity); vc.log(l.dimPlacedImages);\ + var c = l.color; vc.log([c.red, c.green, c.blue]); vc.log(l.visible); vc.log(l.locked); vc.log(l.typename);\ + l.visible = false; vc.log(l.visible); l.visible = true; l.locked = true; vc.log(l.locked); l.locked = false;", + ); + let expected = [json!("Art"), json!(false), json!(false), json!(40), json!(true), json!([10, 20, 30]), json!(true), json!(false)]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("Layer"), json!(false), json!(true)]); + // Setting the values a layer has adds no undo step. + let steps = undo_steps(&s); + let same = "var l = app.activeDocument.layers[0]; l.name = 'Art'; l.opacity = 40; l.printable = false; l.color = {red: 10, green: 20, blue: 30};"; + run(&mut s, same).unwrap(); + assert_eq!(undo_steps(&s), steps); + let before = format!("{:?}", s.active().unwrap().doc.layers); + for (src, msg) in [ + ("app.activeDocument.layers[0].name = null;", "name must be a string"), + ("app.activeDocument.layers[0].name = {};", "name must be a string"), + ("app.activeDocument.layers[0].name = ' ';", "cannot be empty"), + ("app.activeDocument.layers[0].name = new Array(600).join('x');", "at most 512"), + ("app.activeDocument.layers[0].opacity = 200;", "from 0 to 100"), + ("app.activeDocument.layers[0].opacity = NaN;", "finite number"), + ("app.activeDocument.layers[0].visible = 1;", "true or false"), + ("app.activeDocument.layers[0].color = {red: 300, green: 0, blue: 0};", "color.red"), + ("app.activeDocument.layers[0].color = {red: 1.5, green: 0, blue: 0};", "color.red"), + ("app.activeDocument.layers[0].color = 'red';", "red, green and blue"), + ("app.activeDocument.layers[0].zOrder('up');", "ZOrderMethod"), + ("app.activeDocument.activeLayer = 3;", "not a Layer"), + ] { + assert!(failure(&mut s, src).contains(msg), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn layer_move_and_z_order_keep_ids() { + let (mut s, _, _) = doc(); + run(&mut s, "var L = app.activeDocument.layers; L.add().name = 'B'; L.add().name = 'C';").unwrap(); + assert_eq!(layer_names(&s), ["C", "B", "Layer 1"]); + let out = log( + &mut s, + "var L = app.activeDocument.layers, c = L[0]; c.zOrder(ZOrderMethod.SENDTOBACK); vc.log(L[2].name); vc.log(c.zOrderPosition);\ + c.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(L[1].name);\ + c.move(L.getByName('B'), ElementPlacement.PLACEBEFORE); vc.log(L[0].name);\ + c.move(L.getByName('B')); vc.log(L.length); vc.log(c.parent.name); vc.log(c.name);\ + c.move(app.activeDocument); vc.log(L.length); vc.log(L[0].name);", + ); + assert_eq!(out, [json!("C"), json!(1), json!("C"), json!("C"), json!(2), json!("B"), json!("C"), json!(3), json!("C")]); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move(L[0]);").contains("into itself")); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move(L[1].pageItems);").contains("a layer or a document")); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move();").contains("relative object")); +} + +#[test] +fn sublayer_z_order_steps_past_the_next_layer_and_the_art_between() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var P = app.activeDocument.layers[0], x = P.layers.add(); x.name = 'X'; x.zOrder(ZOrderMethod.SENDTOBACK);\ + var y = P.layers.add(); y.name = 'Y'; vc.log([x.zOrderPosition, y.zOrderPosition]);\ + y.zOrder(ZOrderMethod.SENDBACKWARD); vc.log([x.zOrderPosition, y.zOrderPosition, P.layers[0].name]);\ + y.zOrder(ZOrderMethod.BRINGFORWARD); vc.log([x.zOrderPosition, y.zOrderPosition, P.layers[0].name]);\ + y.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(P.pageItems.length);", + ); + assert_eq!(out, [json!([1, 2]), json!([2, 1, "X"]), json!([1, 2, "Y"]), json!(2)]); + // The last step had no layer to pass, so Y stayed under the art. + let d = &s.active().unwrap().doc; + let p = d.layers.last().unwrap(); + let kids = d.children(Some(p.id)).unwrap(); + assert!(kids[1].is_layer() && !kids[2].is_layer() && !kids[3].is_layer()); +} + +#[test] +fn removed_layers_throw_and_the_last_layer_stays() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var L = app.activeDocument.layers, n = L.add(); n.layers.add(); n.layers.add(); vc.log(n.layers.length);\ + n.layers.removeAll(); vc.log(n.layers.length); n.remove(); vc.log(L.length);\ + try { n.name; } catch (e) { vc.log(String(e)); }", + ); + assert_eq!(out[..3], [json!(2), json!(0), json!(1)]); + assert!(out[3].as_str().unwrap().contains("Stale layer"), "{out:?}"); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert!(failure(&mut s, "app.activeDocument.layers[0].remove();").contains("at least one layer")); + assert!(failure(&mut s, "app.activeDocument.layers.removeAll();").contains("at least one layer")); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert!(failure(&mut s, "Object.getOwnPropertyDescriptor(Layer.prototype, 'name').get.call({});").contains("not a Layer")); +} + +#[test] +fn group_items_list_every_depth_and_clipped_toggles_the_mask() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.groupItems[0]; vc.log(d.groupItems.length); vc.log(g.pageItems.length);\ + var inner = g.groupItems.add(); vc.log(inner.typename); vc.log(inner.pageItems.length);\ + vc.log(d.groupItems.length); vc.log(g.groupItems.length); vc.log(d.layers[0].groupItems.length);\ + vc.log(g.layer.name); vc.log(g.clipped); vc.log(d.compoundPathItems.length);\ + d.layers[0].groupItems.add(); vc.log(d.layers[0].groupItems.length); vc.log(g.pageItems.parent.typename);", + ); + let expected = [json!(1), json!(2), json!("GroupItem"), json!(0), json!(2), json!(1), json!(1), json!("Layer 1"), json!(false), json!(0)]; + assert_eq!(out[..10], expected); + assert_eq!(out[10..], [json!(2), json!("GroupItem")]); + // `clipped` on a group with a path on top makes the topmost path its clipping path. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 0.0, 0.0, 5.0, 5.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + run(&mut s, "var g = app.activeDocument.layers[0].groupItems[0]; g.clipped = false;").unwrap(); + assert_eq!(undo_steps(&s), steps); + assert_eq!(log(&mut s, "var g = app.activeDocument.layers[0].groupItems[0]; g.clipped = true; vc.log(g.clipped);"), [json!(true)]); + let st = s.active().unwrap(); + let g = st.doc.node(gid).unwrap(); + assert!(g.clips()); + assert_eq!(g.children().unwrap()[0].id, b); + assert_eq!(undo_steps(&s), steps + 1); + assert!(failure(&mut s, "app.activeDocument.groupItems[0].clipped = 'yes';").contains("true or false")); + assert!(failure(&mut s, "app.activeDocument.groupItems.getByName('none');").contains("Not found")); +} + +#[test] +fn a_layers_and_a_groups_lists_give_the_topmost_object_first() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 70.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The layer holds, bottom to top, the compound path of `a` and the group of `b` (50 pt wide) + // and `c` (70 pt wide). + let out = log( + &mut s, + "var L = app.activeDocument.layers[0], P = L.pageItems, g = L.groupItems[0];\ + vc.log(P[0].typename); vc.log(P[1].typename); vc.log(g.pageItems[0].width); vc.log(g.pageItems[1].width);\ + var e = L.groupItems.add(); e.name = 'E'; vc.log(L.groupItems[0].name); vc.log(L.pageItems[0].name);\ + vc.log(L.compoundPathItems[0].pathItems[0].width);", + ); + assert_eq!(out, [json!("GroupItem"), json!("CompoundPathItem"), json!(70), json!(50), json!("E"), json!("E"), json!(30)]); +} + +#[test] +fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let red = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.compoundPathItems.add(); c.name = 'C'; vc.log(c.typename); vc.log(c.pathItems.length);\ + vc.log(d.compoundPathItems.length); vc.log(c.layer.name);", + ); + assert_eq!(out, [json!("CompoundPathItem"), json!(0), json!(1), json!("Layer 1")]); + assert_eq!(undo_steps(&s), steps + 1); + let cid = { + let d = &s.active().unwrap().doc; + let lid = d.layer_containing(a).unwrap(); + d.node(lid).unwrap().children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap().id + }; + // Paths moved into it become its members, and it takes the paint of the first one. The layer + // lists the new compound path first, then `b`, then `a`. + let source = "var d = app.activeDocument, c = d.compoundPathItems.getByName('C'), L = d.layers[0].pageItems, a = L[2], b = L[1];\ + vc.log(L[0].name); a.move(c, ElementPlacement.PLACEATBEGINNING); b.move(c, ElementPlacement.PLACEATEND);\ + vc.log(c.pathItems.length); vc.log(a.parent.typename); vc.log(b.parent.typename);"; + assert_eq!(log(&mut s, source), [json!("C"), json!(2), json!("CompoundPathItem"), json!("CompoundPathItem")]); + let c = s.active().unwrap().doc.node(cid).unwrap(); + let members: Vec = c.children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(members.len(), 2); + assert!(members.contains(&a) && members.contains(&b)); + assert_eq!(c.appearance, red); + // A group goes neither into a compound path nor beside a path inside one. + let before = format!("{:?}", s.active().unwrap().doc.layers); + for src in [ + "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C'));", + "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C').pathItems[0], ElementPlacement.PLACEBEFORE);", + "app.activeDocument.compoundPathItems.add().move(app.activeDocument.compoundPathItems.getByName('C'));", + ] { + assert!(failure(&mut s, src).contains("only paths"), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false")); +} + +/// The paint of a compound path's only path is the compound path's: moved into an empty compound +/// path, the path gives it that paint, not its own default one. +#[test] +fn a_path_moved_out_of_a_compound_path_gives_an_empty_one_the_paint_it_was_drawn_with() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let red = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, old = d.compoundPathItems[0], c = d.compoundPathItems.add(); c.name = 'C';\ + old.pathItems[0].move(c); vc.log(d.compoundPathItems.getByName('C').pathItems.length);", + ); + assert_eq!(out, [json!(1)]); + let d = &s.active().unwrap().doc; + let c = d.parent_of(a).and_then(|p| d.node(p)).unwrap(); + assert_eq!(c.name.as_deref(), Some("C")); + assert_eq!(c.appearance, red); + assert_ne!(d.node(a).unwrap().appearance, red); +} + +/// `node.move` into a compound path leaves the path without paint or pixel alignment of its own, +/// as Make Compound Path leaves its paths, and the compound path takes the alignment. +#[test] +fn node_move_into_a_compound_path_clears_the_paths_own_paint() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let painted = s.active().unwrap().doc.node(b).unwrap().appearance.clone(); + let member = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let steps = undo_steps(&s); + s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(b), Some(cid)); + let n = d.node(b).unwrap(); + assert_ne!(n.appearance, painted); + assert_eq!(n.appearance, member); + assert!(!n.extras().pixel_aligned); + assert!(d.node(cid).unwrap().extras().pixel_aligned); +} + +#[test] +fn node_move_refuses_a_guide_and_a_locked_or_hidden_compound_path() { + let (mut s, a, b) = doc(); + let cid = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + assert!(matches!(s.active().unwrap().doc.node(cid).unwrap().kind, NodeKind::Compound { .. })); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let err = s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("only paths"), "{err}"); + for hide in ["object.lock", "object.hide"] { + s.execute("select.set", &json!({"ids": [cid.0]})).unwrap(); + s.execute(hide, &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let err = s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("hidden or locked"), "{hide}: {err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + +/// `node.move` refuses a clip group's clipping path for a compound path and leaves the group +/// clipped as it was; the art the group clips still goes in. +#[test] +fn node_move_refuses_a_clipping_path_for_a_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let cid = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0))); + let (before, steps) = (format!("{:?}", d.layers), undo_steps(&s)); + let err = s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("clipping path"), "{err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(cid)); + assert!(d.node(g).unwrap().clips()); + assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0))); +} + +/// `duplicate(compoundPath)` puts the copy into the compound path; an empty one takes its paint. +#[test] +fn a_path_duplicated_into_an_empty_compound_path_becomes_its_path() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let blue = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.compoundPathItems.add(), p = d.layers[0].pageItems[2]; var q = p.duplicate(c);\ + vc.log(c.pathItems.length); vc.log(q.parent.typename); vc.log(p.parent.typename);", + ); + assert_eq!(out, [json!(1), json!("CompoundPathItem"), json!("Layer")]); + let d = &s.active().unwrap().doc; + let lid = d.layer_containing(a).unwrap(); + let c = d.node(lid).unwrap().children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap(); + assert_eq!(c.appearance, blue); + assert_eq!(d.node(a).unwrap().appearance, blue); + // The copy keeps no paint, live shape or pixel alignment of its own. + let q = &c.children().unwrap()[0]; + assert_ne!(q.appearance, blue); + assert!(matches!(q.kind, NodeKind::Path { live: None, .. })); + assert!(!q.extras().pixel_aligned); +} + +/// A compound path's `pathItems` list its topmost path first. +#[test] +fn a_compound_paths_path_items_list_the_topmost_path_first() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + let source = "var P = app.activeDocument.compoundPathItems[0].pathItems; vc.log(P[0].width); vc.log(P[1].width);"; + // `b` (50 pt wide) on top, then `a` (30 pt wide) on top. + s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(log(&mut s, source), [json!(50), json!(30)]); + s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(log(&mut s, source), [json!(30), json!(50)]); +} + +/// `index(i)` on a layer's `pageItems` and a compound path's `pathItems` gives the object `[i]` +/// gives, and `Not found` past the end. +#[test] +fn scoped_collections_index_by_number() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers[0].pageItems, P = d.compoundPathItems[0].pathItems;\ + vc.log(L.index(0).typename); vc.log(P.index(1).width === P[1].width);", + ); + assert_eq!(out, vec![json!("CompoundPathItem"), json!(true)]); + let e = failure(&mut s, "app.activeDocument.compoundPathItems[0].pathItems.index(5);"); + assert!(e.contains("Not found"), "{e}"); +} + +#[test] +fn scoped_collection_methods_reject_the_other_collection_class() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + rect(&mut s, 200.0, 20.0, 30.0, 40.0); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for (class, receiver) in + [("PathItems", "app.activeDocument.layers[0].pageItems"), ("PageItems", "app.activeDocument.compoundPathItems[0].pathItems")] + { + for call in ["removeAll.call(r)", "getByName.call(r, '')", "index.call(r, 0)"] { + let source = format!("var r = {receiver}; {class}.prototype.{call};"); + let error = failure(&mut s, &source); + assert!(error.contains(&format!("not a {class}")), "{source}: {error}"); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); + } + for property in ["typename", "length", "parent"] { + let source = format!("Object.getOwnPropertyDescriptor({class}.prototype, '{property}').get.call({receiver});"); + let error = failure(&mut s, &source); + assert!(error.contains(&format!("not a {class}")), "{source}: {error}"); + } + } + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn clear_releases_a_group_after_removing_its_last_compound_mask_member() { + for mode in ["whole", "anchors", "mixed"] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("edit.clear", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let other = rect(&mut s, 200.0, 20.0, 30.0, 40.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + if mode == "anchors" { + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1], [0, 2]]})).unwrap(); + } else if mode == "mixed" { + s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + } + let before = s.active().unwrap().doc.clone(); + let selection = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + s.execute("edit.clear", &json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(compound).is_none(), "{mode}"); + assert!(d.node(other).is_some(), "{mode}"); + assert!(d.node(group).unwrap().children().unwrap().is_empty(), "{mode}"); + assert!(!d.node(group).unwrap().clips(), "{mode}"); + assert_eq!(undo_steps(&s), steps + 1, "{mode}"); + let after = d.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before, "{mode}"); + assert_eq!(s.active().unwrap().selection, selection, "{mode}"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, after, "{mode}"); + } +} + +/// Ruler guides left in a clipped layer do not count as other objects: `removeAll()` deletes the +/// layer's clipping compound path. +#[test] +fn scoped_remove_all_deletes_a_clipping_path_beside_ruler_guides() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + let layer = s.active().unwrap().doc.parent_of(cid).unwrap(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + run(&mut s, "app.activeDocument.layers[0].compoundPathItems.removeAll();").unwrap(); + assert!(s.active().unwrap().doc.node(cid).is_none()); + assert!(!s.active().unwrap().doc.node(layer).unwrap().clips()); + let added = rect(&mut s, 200.0, 20.0, 30.0, 40.0); + assert_eq!(s.active().unwrap().doc.parent_of(added), Some(layer)); + assert!(!s.active().unwrap().doc.node(layer).unwrap().clips()); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.active().unwrap().doc.node(cid).is_some()); + assert!(s.active().unwrap().doc.node(layer).unwrap().clips()); + s.execute("edit.redo", &json!({})).unwrap(); + rect(&mut s, 200.0, 20.0, 30.0, 40.0); + assert!(!s.active().unwrap().doc.node(layer).unwrap().clips()); +} + +#[test] +fn scoped_remove_all_releases_an_empty_clipping_group_in_one_step() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let steps = undo_steps(&s); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.removeAll(); vc.log(g.clipped); vc.log(g.pageItems.length);"); + assert_eq!(out, [json!(false), json!(0)]); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.clipped); vc.log(g.pageItems.length);"); + assert_eq!(out, [json!(true), json!(2)]); +} + +#[test] +fn clipped_setter_refuses_locked_artboards_layers_and_groups() { + for target in ["artboard", "layer", "group"] { + for clipped in [false, true] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + if clipped { + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + } + let layer = s.active().unwrap().doc.layer_containing(NodeId(g)).unwrap(); + s.edit("Lock", |d, _| { + match target { + "artboard" => d.artboards[0].locked = true, + "layer" => d.node_mut(layer).unwrap().locked = true, + _ => d.node_mut(NodeId(g)).unwrap().locked = true, + } + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let src = format!( + "var g = app.activeDocument.groupItems[0]; try {{ g.clipped = {}; vc.log('changed'); }} catch (e) {{ vc.log(e.message); }} vc.log(g.clipped);", + !clipped + ); + let out = log(&mut s, &src); + assert!(out[0].as_str().unwrap().contains("locked"), "{target}: {out:?}"); + assert_eq!(out[1], json!(clipped)); + assert_eq!(undo_steps(&s), steps); + } + } +} + +#[test] +fn clipped_setter_refuses_a_hidden_or_locked_topmost_object() { + for hidden in [false, true] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.edit("Protect", |d, _| { + let n = d.node_mut(b).unwrap(); + if hidden { + n.visible = false; + } else { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.node(b).unwrap().appearance); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; try { g.clipped = true; vc.log('changed'); } catch (e) { vc.log(e.message); } vc.log(g.clipped);", + ); + assert!(out[0].as_str().unwrap().contains("hidden or locked"), "hidden {hidden}: {out:?}"); + assert_eq!(out[1], json!(false)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b).unwrap().appearance), before); + assert_eq!(undo_steps(&s), steps); + } +} + +#[test] +fn scoped_collections_convert_to_strings() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0], g = l.groupItems.add(), c = g.compoundPathItems.add();\ + var lists = [l.pageItems, g.pageItems, l.layers, l.groupItems, g.groupItems, l.compoundPathItems, g.compoundPathItems, c.pathItems];\ + for (var i = 0; i < lists.length; i++) { vc.log(String(lists[i])); vc.log(lists[i].toString()); }", + ); + let expected: Vec<_> = ["PageItems", "PageItems", "Layers", "GroupItems", "GroupItems", "CompoundPathItems", "CompoundPathItems", "PathItems"] + .into_iter() + .flat_map(|name| [json!(format!("[{name}]")), json!(format!("[{name}]"))]) + .collect(); + assert_eq!(out, expected); +} + +#[test] +fn layer_color_can_be_assigned_to_path_paint() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0]; l.color = {red: 10, green: 20, blue: 30};\ + var c = l.color; vc.log(c.typename); var p = l.pageItems[0]; p.fillColor = c;\ + vc.log([p.fillColor.red, p.fillColor.green, p.fillColor.blue]);", + ); + assert_eq!(out, [json!("RGBColor"), json!([10, 20, 30])]); +} + +/// `removeAll()` refuses to delete the compound path that clips a group while the group keeps +/// other art, and deletes nothing. +#[test] +fn scoped_remove_all_refuses_a_clipping_compound_path() { + let (mut s, a, b) = doc(); + let e = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [cid.0, e.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + let err = failure(&mut s, "app.activeDocument.groupItems[0].compoundPathItems.removeAll();"); + assert!(err.contains("clipping"), "{err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); +} + +/// Runs the document's `pathItems.removeAll()`, then logs its error message and the number of paths. +const CAUGHT_PATHS_REMOVE_ALL: &str = "var p = app.activeDocument.pathItems, m = '';\ + try { p.removeAll(); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.length);"; + +/// The document's `pathItems.removeAll()` refuses to delete the path that clips a group while the +/// group keeps other art, and deletes nothing, as the scoped collections do. +#[test] +fn document_path_items_remove_all_refuses_a_clipping_path() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(a)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + // The script catches the error and counts the paths before the run ends, so the run's own + // rollback cannot hide a deletion. + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&a.0.to_string()), "{out:?}"); + assert!(!e.contains(&b.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// The document's `pathItems.removeAll()` would empty a compound path that clips a group keeping +/// other art, so it throws and deletes nothing. +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_compound_path() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [compound.0, t.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(compound).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(compound)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&compound.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// A clipping mask made of a group of paths, as an imported SVG mask with several shapes is, would +/// be left empty by the document's `pathItems.removeAll()`, so it throws and deletes nothing. +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_of_paths() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// Type clips by its glyph outlines, so a clipping group that keeps type after its paths go still +/// clips, and the document's `pathItems.removeAll()` deletes every path. +#[test] +fn document_path_items_remove_all_keeps_a_clipping_group_that_holds_type() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!(out[0], json!(""), "{out:?}"); + assert_eq!(out[1], json!(0)); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none()); + assert!(d.node(t).is_some() && d.node(u).is_some()); + assert_eq!(undo_steps(&s), steps + 1); +} + +/// Type with no characters to draw gives no clip outline, so a clipping group whose paths would +/// leave only such type makes the document's `pathItems.removeAll()` throw and delete nothing. +#[test] +fn document_path_items_remove_all_refuses_when_only_blank_type_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) { + tx.runs.iter_mut().for_each(|r| r.text = " ".into()); + } + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// A clipping group nested in a clipping mask clips by its first member only, so type it clips does +/// not keep the outer mask's outline, and the document's `pathItems.removeAll()` names the outer +/// mask too. +#[test] +fn document_path_items_remove_all_ignores_type_clipped_inside_a_nested_mask() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [b.0, t.0]})).unwrap(); + let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, nested.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + for (g, first) in [(nested, b), (outer, mask)] { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(g).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != first); + *clip = true; + } + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.split(": ").last().unwrap_or_default().split(", ").any(|id| id == mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); +} + +/// A numbered paragraph whose text is a single space still draws its number, which clips, so the +/// document's `pathItems.removeAll()` deletes the paths of a clipping group that keeps it. +#[test] +fn document_path_items_remove_all_keeps_a_clipping_group_whose_type_draws_only_a_list_number() { + use vectorcraft_doc::text::{NumberStyle, ParaList}; + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) { + tx.runs.iter_mut().for_each(|r| r.text = " ".into()); + let mut styles = tx.paragraph_styles(); + styles.iter_mut().for_each(|p| p.list = Some(ParaList::numbered(NumberStyle::Arabic))); + tx.set_paragraph_styles(styles); + } + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) { + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty()); + } + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!(out[0], json!(""), "{out:?}"); + assert_eq!(out[1], json!(0)); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none()); + assert!(d.node(t).is_some() && d.node(u).is_some()); + assert_eq!(undo_steps(&s), steps + 1); +} + +/// Area type too short for its first line lays out no glyphs and gives no clip outline, so a +/// clipping group whose paths would leave only such type makes the document's +/// `pathItems.removeAll()` throw and delete nothing. +#[test] +fn document_path_items_remove_all_refuses_when_only_overset_type_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 250, "size": 12, "area": {"width": 100, "height": 1}, "text": "hi"})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) { + assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty()); + } + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); +} + +/// Hidden type does not clip, so a clipping group whose paths would leave only hidden type makes +/// the document's `pathItems.removeAll()` throw and delete nothing. +#[test] +fn document_path_items_remove_all_refuses_when_only_hidden_type_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(n) = d.node_mut(t) { + n.visible = false; + } + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empty_subgroup() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let empty = NodeId(s.execute("object.newGroup", &json!({"parent": mask.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + assert!(d.node(empty).unwrap().children().unwrap().is_empty()); + let before = d.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!( + out[0], + json!(format!("cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", mask.0)) + ); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn document_path_items_remove_all_keeps_empty_groups_but_removes_empty_compounds() { + for compound in [false, true] { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute(if compound { "object.compoundPath.make" } else { "object.group" }, &json!({})).unwrap(); + let sibling = s.active().unwrap().doc.parent_of(b).unwrap(); + let layer = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(layer).unwrap().clips()); + assert_eq!(d.node(layer).and_then(|n| n.children()).map(|k| k[0].id), Some(a)); + let before = d.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + if compound { + assert_eq!(out, [json!(""), json!(0)]); + let d = &s.active().unwrap().doc; + assert!(d.node(sibling).is_none()); + assert!(!d.node(layer).unwrap().clips()); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + } else { + assert_eq!( + out[0], + json!(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", + a.0 + )) + ); + assert_eq!(out[1], json!(3)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); + } + } +} + +/// A path that leaves a compound path for a layer is drawn as it was: it takes the compound +/// path's paint and pixel alignment, as Release Compound Path gives them. +#[test] +fn a_path_moved_out_of_a_compound_path_keeps_the_paint_it_was_drawn_with() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let (cid, red, lid) = { + let d = &s.active().unwrap().doc; + let cid = d.parent_of(a).unwrap(); + (cid, d.node(cid).unwrap().appearance.clone(), d.layer_containing(a).unwrap()) + }; + assert_ne!(s.active().unwrap().doc.node(a).unwrap().appearance, red); + s.execute("node.move", &json!({"id": a.0, "parent": lid.0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(lid)); + let n = d.node(a).unwrap(); + assert_eq!(n.appearance, red); + assert!(n.extras().pixel_aligned); + // The path left behind keeps none of its own. + assert_eq!(d.parent_of(b), Some(cid)); + assert_ne!(d.node(b).unwrap().appearance, red); +} + +/// A path that leaves a pixel-aligned compound path for another compound path makes that one +/// pixel-aligned, as it gives it the paint it was drawn with. +#[test] +fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.active().unwrap().doc.node(a).unwrap().extras().pixel_aligned); + let to = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + assert!(!s.active().unwrap().doc.node(to).unwrap().extras().pixel_aligned); + s.execute("node.move", &json!({"id": a.0, "parent": to.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(to)); + assert!(d.node(to).unwrap().extras().pixel_aligned); + assert!(!d.node(a).unwrap().extras().pixel_aligned); +} + +/// A path off the pixel grid that moves into a pixel-aligned compound path is snapped to the grid +/// with the compound path's other paths. +#[test] +fn a_path_moved_into_a_pixel_aligned_compound_path_is_snapped() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let to = s.active().unwrap().doc.parent_of(a).unwrap(); + let r = rect(&mut s, 200.3, 100.3, 20.4, 20.4); + s.execute("object.setPixelAligned", &json!({"ids": [r.0], "on": false})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.active().unwrap().doc.node(r).unwrap().extras().pixel_aligned); + let before = s.active().unwrap().doc.bounds_of(&[r], false).unwrap(); + assert!(before.x0.fract().abs() > 0.01, "{before:?}"); + s.execute("node.move", &json!({"id": r.0, "parent": to.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(to).unwrap().extras().pixel_aligned); + let after = d.bounds_of(&[r], false).unwrap(); + assert_ne!(after, before); + assert!(!d.node(r).unwrap().extras().pixel_aligned); + assert!([after.x0, after.y0, after.x1, after.y1].iter().all(|v| (v * 2.0).fract().abs() < 1e-9), "not snapped: {after:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.bounds_of(&[r], false).unwrap(), before); +} + +#[test] +fn a_compound_paths_path_items_are_page_items() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.compoundPathItems[0].pathItems; vc.log(p.typename); vc.log(p.length);\ + vc.log(p[0].typename); vc.log(d.layers[0].pageItems.typename); vc.log(p instanceof PathItems);\ + vc.log(p instanceof PageItems); vc.log(p.parent === d.compoundPathItems[0]);\ + p[0].name = 'member'; vc.log(p.getByName('member') === p[0]); vc.log(p.index(0) === p[0]);", + ); + assert_eq!( + out, + [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems"), json!(true), json!(false), json!(true), json!(true), json!(true)] + ); + for call in ["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"] { + let source = format!( + "var p = app.activeDocument.compoundPathItems[0].pathItems; try {{ p.{call}; vc.log('made'); }} catch (e) {{ vc.log(e.message); }} vc.log(p.length);" + ); + let out = log(&mut s, &source); + assert!(out[0].as_str().unwrap().contains("not available yet"), "{call}: {out:?}"); + assert_eq!(out[1], json!(2)); + } + run(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log(c.pathItems.length);").unwrap(); + assert!(s.active().unwrap().doc.node(a).is_none() && s.active().unwrap().doc.node(b).is_none()); +} + +#[test] +fn art_collections_follow_edits_between_reads() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.layers[0].pageItems, g = d.groupItems; vc.log(p.length); vc.log(g.length);\ + d.layers[0].groupItems.add(); vc.log(p.length); vc.log(p[0].typename); vc.log(g.length);\ + p[0].remove(); vc.log(p.length); vc.log(p[0].typename);", + ); + assert_eq!(out, [json!(2), json!(0), json!(3), json!("GroupItem"), json!(1), json!(2), json!("PathItem")]); +} + +#[test] +fn a_loop_over_groups_and_their_items_lists_each_collection_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..5 { + let x = f64::from(i) * 20.0; + let (a, b) = (rect(&mut s, x, 0.0, 10.0, 10.0), rect(&mut s, x, 20.0, 10.0, 10.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + } + // Both scripts make the same calls. The first reads the groups and each group's items in + // turn; the second reads every group before any group's items, so it builds each list once. + let nested = "var gs = app.activeDocument.groupItems, n = 0;\ + for (var i = 0; i < gs.length; i++) { var p = gs[i].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\ + vc.log(n);"; + let in_order = "var gs = app.activeDocument.groupItems, all = [], n = 0;\ + for (var i = 0; i < gs.length; i++) { all.push(gs[i]); }\ + for (var k = 0; k < all.length; k++) { var p = all[k].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\ + vc.log(n);"; + crate::script::dom::ART_SCANS.with(|c| c.set(0)); + let a = run(&mut s, nested).unwrap(); + // The groups' list and each group's list are built once: 1 + 5 lists. + let scans = crate::script::dom::ART_SCANS.with(std::cell::Cell::get); + assert!(scans <= 6, "{scans} lists built for 5 groups"); + let b = run(&mut s, in_order).unwrap(); + assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10]))); + assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); + // A list built again for each lookup would add a host call to both. Building the document's + // page items for `groupItems` counts one call. + assert_eq!(a["hostCalls"], json!(51), "{a}"); +} + +/// A loop over `layers.length` and `layers[i]` lists the layers once while the document is +/// unchanged, so it looks at each layer a bounded number of times. +#[test] +fn a_loop_over_layers_lists_them_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for _ in 0..39 { + s.execute("layer.new", &json!({})).unwrap(); + } + let n = s.active().unwrap().doc.layers.len() as u64; + crate::script::dom::LAYER_SCANS.with(|c| c.set(0)); + let out = log(&mut s, "var L = app.activeDocument.layers, n = 0; for (var i = 0; i < L.length; i++) { L[i]; n++; } vc.log(n);"); + assert_eq!(out, vec![json!(n)]); + let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get); + assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); +} + +/// Reading `zOrderPosition` for every layer lists the layers once while the document is unchanged. +#[test] +fn z_order_position_of_each_layer_lists_them_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for _ in 0..39 { + s.execute("layer.new", &json!({})).unwrap(); + } + let n = s.active().unwrap().doc.layers.len() as u64; + crate::script::dom::LAYER_SCANS.with(|c| c.set(0)); + let out = log( + &mut s, + "var L = app.activeDocument.layers, k = L.length, z = []; for (var i = 0; i < k; i++) { z.push(L[i].zOrderPosition); } vc.log(z[0]); vc.log(z[k - 1]);", + ); + assert_eq!(out, vec![json!(n), json!(1)]); + let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get); + assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); +} + +/// `groupItems.createFromFile` on a collection whose group is gone reports the stale object before +/// the member that is not available yet. +#[test] +fn create_from_file_on_a_stale_group_collection_reports_it_stale() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let e = failure(&mut s, "var g = app.activeDocument.groupItems[0], c = g.groupItems; g.remove(); c.createFromFile(new File('x.svg'));"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "app.activeDocument.groupItems[0].groupItems.createFromFile(new File('x.svg'));"); + assert!(e.contains("GroupItems.createFromFile is not available yet"), "{e}"); +} + +/// Each `getByName` on a layer's `pageItems` is charged to the host budget like one on the +/// document's `pageItems`, also when the list was already built. +#[test] +fn scoped_name_searches_are_charged_each_time() { + let (mut s, ..) = doc(); + let calls = |s: &mut Session, list: &str, k: usize| { + let source = format!("var p = {list}; p.length; for (var i = 0; i < {k}; i++) {{ try {{ p.getByName('none'); }} catch (e) {{}} }}"); + run(s, &source).unwrap()["hostCalls"].as_u64().unwrap() + }; + let doc_cost = calls(&mut s, "app.activeDocument.pageItems", 6) - calls(&mut s, "app.activeDocument.pageItems", 1); + let layer_cost = calls(&mut s, "app.activeDocument.layers[0].pageItems", 6) - calls(&mut s, "app.activeDocument.layers[0].pageItems", 1); + assert_eq!(layer_cost, doc_cost); +} + +#[test] +fn layer_z_order_scans_are_charged_each_time() { + let (mut s, ..) = doc(); + let repeated = "var l = app.activeDocument.layers[0]; for (var i = 0; i < 512; i++) l.zOrderPosition;"; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let small = run(&mut s, repeated); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + small.unwrap(); + for _ in 0..100 { + s.execute("layer.new", &json!({})).unwrap(); + } + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let once = run(&mut s, "var l = app.activeDocument.layers[0]; l.zOrderPosition;"); + let large = run(&mut s, repeated); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + once.unwrap(); + let error = large.unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{error}"); +} + +#[test] +fn has_selected_artwork_keeps_selected_objects_in_other_layers() { + let (mut s, a, b) = doc(); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 220.0, 30.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0, other.0]})).unwrap(); + for (operation, a_selected, b_selected) in + [("vc.log(l.hasSelectedArtwork)", true, false), ("l.hasSelectedArtwork = false", false, false), ("l.hasSelectedArtwork = true", true, true)] + { + let source = format!("var l = app.activeDocument.layers.getByName('Layer 1'); {operation};"); + run(&mut s, &source).unwrap(); + assert!(s.active().unwrap().selection.objects.contains(&other), "{operation}"); + let selected = &s.active().unwrap().selection.objects; + assert_eq!((selected.contains(&a), selected.contains(&b)), (a_selected, b_selected), "{operation}"); + } +} + +#[test] +fn group_items_remove_all_refuses_locked_groups() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + assert!(failure(&mut s, "app.activeDocument.groupItems.removeAll();").contains("hidden or locked")); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + s.execute("object.setProps", &json!({"ids": [g], "locked": false})).unwrap(); + run(&mut s, "app.activeDocument.groupItems.removeAll();").unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(NodeId(g)).is_none() && d.node(a).is_none() && d.node(b).is_some()); +} + +#[test] +fn new_group_command_checks_its_parent() { + let (mut s, a, _) = doc(); + let layer = s.active().unwrap().doc.layer_containing(a).unwrap(); + let g = s.execute("object.newGroup", &json!({"parent": layer.0, "index": 0})).unwrap()["id"].as_u64().unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.position(NodeId(g)).map(|(p, i, _)| (p, i)), Some((Some(layer), 0))); + assert!(s.execute("object.newGroup", &json!({"parent": a.0})).unwrap_err().to_string().contains("not a layer or group")); + assert!(s.execute("object.newGroup", &json!({"parent": 999_999})).unwrap_err().to_string().contains("no layer or group")); + assert!(s.execute("object.newGroup", &json!({"parent": "x"})).unwrap_err().to_string().contains("parent must be")); + assert!(s.execute("object.newGroup", &json!({"index": -1})).unwrap_err().to_string().contains("index must be")); + let before = format!("{:?}", s.active().unwrap().doc.layers); + assert!(s.execute("object.newGroup", &json!({"parent": null})).unwrap_err().to_string().contains("parent must be")); + assert!(s.execute("object.newGroup", &json!({"index": null})).unwrap_err().to_string().contains("index must be")); + assert!(s.execute("object.newGroup", &json!({"compound": null})).unwrap_err().to_string().contains("compound must be")); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + assert!(s.execute("object.newGroup", &json!({"parent": layer.0})).unwrap_err().to_string().contains("hidden or locked")); +} + +#[test] +fn artboards_add_insert_rename_and_remove() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; vc.log(A.length); vc.log(A[0].artboardRect); vc.log(A.typename);\ + var b = A.add([500, 300, 700, 100]); b.name = 'Two'; vc.log(A.length); vc.log(A[1].name); vc.log(b.artboardRect);\ + A.insert([0, -100, 100, -200], 1); vc.log(A[1].artboardRect); vc.log(b.name); vc.log(A.getByName('Two').artboardRect[0]);\ + b.artboardRect = [500, 300, 650, 150]; vc.log(b.artboardRect); b.rulerPAR = 2; vc.log(b.rulerPAR);\ + b.showCenter = true; b.showCrossHairs = true; b.showSafeAreas = true; vc.log([b.showCenter, b.showCrossHairs, b.showSafeAreas]);\ + b.rulerOrigin = [10, 20]; vc.log(b.rulerOrigin); vc.log(b.parent.typename);\ + A.remove(0); vc.log(A.length); b.remove(); vc.log(A.length); try { b.name; } catch (e) { vc.log(String(e)); }", + ); + assert_eq!(out[..4], [json!(1), json!([0, 300, 400, 0]), json!("Artboards"), json!(2)]); + assert_eq!(out[4..7], [json!("Two"), json!([500, 300, 700, 100]), json!([0, -100, 100, -200])]); + assert_eq!(out[7..11], [json!("Two"), json!(500), json!([500, 300, 650, 150]), json!(2)]); + assert_eq!(out[11..16], [json!([true, true, true]), json!([10, 20]), json!("Document"), json!(2), json!(1)]); + assert!(out[16].as_str().unwrap().contains("Stale artboard"), "{out:?}"); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1); +} + +#[test] +fn new_artboards_get_a_name_no_other_artboard_has() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A[0].name = 'Artboard 2';\ + vc.log(A.add([500, 300, 700, 100]).name); A.insert([0, -100, 100, -200], 0); vc.log(A[0].name);\ + vc.log(A.add([800, 300, 900, 100]).name);", + ); + assert_eq!(out, [json!("Artboard 3"), json!("Artboard 4"), json!("Artboard 5")]); +} + +#[test] +fn names_take_numbers_and_booleans() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers[0];\ + L.name = 5; vc.log(L.name); vc.log(typeof L.name); L.name = 1.5; vc.log(L.name); L.name = true; vc.log(L.name);\ + d.artboards[0].name = 7; vc.log(d.artboards[0].name); vc.log(typeof d.artboards[0].name);", + ); + assert_eq!(out, [json!("5"), json!("string"), json!("1.5"), json!("true"), json!("7"), json!("string")]); +} + +#[test] +fn an_empty_artboard_name_gives_the_default_name() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]);\ + A[0].name = 'Front'; A[1].name = 'Back'; A[0].name = ''; A[1].name = ' ';\ + vc.log([A[0].name, A[1].name]);", + ); + assert_eq!(out, [json!(["Artboard 1", "Artboard 2"])]); +} + +#[test] +fn two_artboards_may_share_a_name() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]);\ + A[1].name = 'Same'; A[0].name = 'Same'; vc.log([A[0].name, A[1].name]); vc.log(A.getByName('Same').artboardRect[0]);", + ); + assert_eq!(out, [json!(["Same", "Same"]), json!(0)]); + let names: Vec = s.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect(); + assert_eq!(names, ["Same", "Same"]); +} + +#[test] +fn artboards_reject_bad_arguments_before_any_change() { + let (mut s, _, _) = doc(); + run(&mut s, "app.activeDocument.artboards.add([500, 300, 700, 100]).name = 'Two';").unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.artboards); + let steps = undo_steps(&s); + for (src, msg) in [ + ("app.activeDocument.artboards.add([0, 0, 10]);", "four numbers"), + ("app.activeDocument.artboards.add('x');", "four numbers"), + ("app.activeDocument.artboards.add([10, 0, 0, 10]);", "right side"), + ("app.activeDocument.artboards.add([0, 0, NaN, -10]);", "finite number"), + ("app.activeDocument.artboards.add([0, 0, 1e300, -10]);", "outside the canvas"), + ("app.activeDocument.artboards.add([0, 0, 0.5, -10]);", "at least 1 point"), + ("app.activeDocument.artboards[0].artboardRect = [0, 0, 10, -0.25];", "at least 1 point"), + ("app.activeDocument.artboards.insert([0, 0, 10, -10], 5);", "index must be"), + ("app.activeDocument.artboards.insert([0, 0, 10, -10]);", "needs an index"), + ("app.activeDocument.artboards.remove(2);", "index must be"), + ("app.activeDocument.artboards.remove(-1);", "index must be"), + ("app.activeDocument.artboards[0].name = null;", "must be a string"), + ("app.activeDocument.artboards[0].name = new Array(5000).join('x');", "too long"), + ("app.activeDocument.artboards[0].rulerPAR = 20;", "from 0.1 to 10"), + ("app.activeDocument.artboards[0].showCenter = 'on';", "true or false"), + ("app.activeDocument.artboards.setActiveArtboardIndex(9);", "index must be"), + ("app.activeDocument.artboards.getByName('none');", "Not found"), + ] { + assert!(failure(&mut s, src).contains(msg), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.artboards), before); + assert_eq!(undo_steps(&s), steps); + run(&mut s, "app.activeDocument.artboards.remove(1);").unwrap(); + assert!(failure(&mut s, "app.activeDocument.artboards[0].remove();").to_lowercase().contains("artboard")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1); +} + +#[test] +fn set_active_artboard_index_is_reported_without_an_undo_step() { + let (mut s, _, _) = doc(); + run(&mut s, "app.activeDocument.artboards.add([500, 300, 700, 100]);").unwrap(); + let steps = undo_steps(&s); + let r = run(&mut s, "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(1); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + assert_eq!(undo_steps(&s), steps); + let st = s.active().unwrap(); + assert_eq!(st.active_artboard, Some(st.doc.artboards[1].id)); + // Artboard coordinates follow the active artboard. + let out = log(&mut s, "app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; vc.log(app.activeDocument.artboards[1].artboardRect);"); + assert_eq!(out, [json!([0, 0, 200, 200])]); + let r = run(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1);").unwrap(); + assert!(r.get("activeArtboards").is_none()); +} + +/// A stale container's `pageItems.index(n)` and `groupItems.index(n)` throw the stale error for +/// every number, a negative one included. +#[test] +fn a_stale_containers_list_throws_its_stale_error_for_any_index() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-stale-index"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for list in ["pageItems", "groupItems"] { + let source = + format!("var d = app.activeDocument, p = d.layers[0].{list}; d.pageItems[0].name = 'changed'; vc.run('file.revert'); p.index(-1);"); + let e = failure(&mut s, &source); + assert!(e.contains("Stale page item"), "{list}: {e}"); + } +} + +/// `removeAll()` on a clip group releases its mask, so an object added to the group afterwards is +/// not its clipping path; the run's one undo step puts everything back. +#[test] +fn remove_all_on_a_clip_group_releases_its_mask() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let out = + log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.removeAll(); vc.log(g.clipped); g.groupItems.add(); vc.log(g.clipped);"); + assert_eq!(out, [json!(false), json!(false)]); + assert!(!s.active().unwrap().doc.node(g).unwrap().clips()); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps); + let st = s.active().unwrap(); + assert!(st.doc.node(g).unwrap().clips()); + assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2); + // `groupItems.removeAll()` leaves the clipping path, and the group keeps its mask. + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; g.groupItems.add(); g.groupItems.removeAll(); vc.log(g.clipped); vc.log(g.pageItems.length);", + ); + assert_eq!(out, [json!(true), json!(2)]); +} + +/// `remove()` on a clip group's clipping path while other art stays in the group releases the +/// mask, so the art above it is not made the clipping path, and so does emptying a clipping layer +/// with the document's `pageItems.removeAll()`. +#[test] +fn deleting_a_clipping_path_releases_its_mask() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let kids = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::>(); + let mask = kids(&s)[0]; + assert!(matches!(s.active().unwrap().doc.node(mask).unwrap().kind, NodeKind::Compound { .. })); + s.execute("object.setProps", &json!({"id": mask.0, "name": "mask"})).unwrap(); + let clips = |s: &Session| s.active().unwrap().doc.node(g).unwrap().clips(); + assert!(clips(&s)); + let out = + log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.getByName('mask').remove(); vc.log([g.clipped, g.pageItems.length]);"); + assert_eq!(out, [json!([false, 2])]); + assert!(!clips(&s)); + assert_eq!(kids(&s), [a, b]); + // A clipping layer emptied by `pageItems.removeAll()` releases its mask too. + let (mut s, _, _) = doc(); + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert!(s.active().unwrap().doc.layers[0].clips()); + log(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(!s.active().unwrap().doc.layers[0].clips()); +} + +/// Choosing the artboard that is active only by default keeps that artboard: one inserted before it +/// moves it to the next index, and the report gives that index. +#[test] +fn choosing_the_default_active_artboard_keeps_it_when_one_is_inserted_before() { + let (mut s, _, _) = doc(); + assert_eq!(s.active().unwrap().active_artboard, None); + let first = s.active().unwrap().doc.artboards[0].id; + let r = run( + &mut s, + "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0);\ + vc.log(A.getActiveArtboardIndex());", + ) + .unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + assert_eq!(s.active().unwrap().active_artboard, Some(first)); +} + +/// In a document the run makes, choosing artboard 0 and then inserting one before it still puts +/// the document in the report. +#[test] +fn a_new_documents_chosen_artboard_is_reported_after_an_insert_before_it() { + let (mut s, _, _) = doc(); + let r = run( + &mut s, + "var d = app.documents.add(); var A = d.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0);\ + vc.log(A.getActiveArtboardIndex());", + ) + .unwrap(); + assert_eq!(r["log"], json!([1])); + let list = r["activeArtboards"].as_array().cloned().unwrap_or_default(); + assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}"); +} + +/// `artboards.insert` gives nothing back; `artboards.add` gives the new artboard. +#[test] +fn artboards_insert_returns_nothing() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; vc.log(typeof A.insert([0, -100, 100, -200], 0)); vc.log(A.add([500, 300, 700, 100]).typename);", + ); + assert_eq!(out, [json!("undefined"), json!("Artboard")]); +} + +/// The collections' `index` is described as giving an element, and `toString` of a collection +/// whose container is gone fails as `typename` does. +#[test] +fn collection_index_reflection_and_stale_to_string() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log([d.layers.reflect.find('index').dataType, d.groupItems.reflect.find('index').dataType,\ + d.compoundPathItems.reflect.find('index').dataType, d.artboards.reflect.find('index').dataType]);", + ); + assert_eq!(out, [json!(["Layer", "GroupItem", "CompoundPathItem", "Artboard"])]); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let live = log(&mut s, "vc.log(app.activeDocument.groupItems[0].groupItems.toString()); vc.log(app.activeDocument.layers[0].layers.toString());"); + assert_eq!(live, [json!("[GroupItems]"), json!("[Layers]")]); + let source = "var g = app.activeDocument.groupItems[0]; var c = g.groupItems; g.remove(); c.toString();"; + let error = failure(&mut s, source); + assert!(error.contains("Stale page item"), "{error}"); + let source = "var l = app.activeDocument.layers.add(); var c = l.layers; l.remove(); c.toString();"; + let error = failure(&mut s, source); + assert!(error.contains("Stale layer"), "{error}"); +} + +/// Setting `hasSelectedArtwork = true` on a layer whose art is all selected runs no command but +/// is still charged for the art it looks at. +#[test] +fn has_selected_artwork_charges_the_walk_when_nothing_is_added() { + // `locked`: the art is locked, so nothing is selectable; otherwise it is all selected. + let repeated = |n: usize, locked: bool| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect(); + if locked { + s.execute("object.setProps", &json!({"ids": ids, "locked": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + } else { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + } + let steps = undo_steps(&s); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13))); + let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork = true;"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(undo_steps(&s), steps); + r + }; + for locked in [false, true] { + repeated(1, locked).unwrap(); + let error = repeated(200, locked).unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{locked}: {error}"); + } + // `false` on an empty layer is charged for the selection held in another layer, which stays. + let deselect = |n: usize| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect(); + s.execute("layer.new", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13))); + let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork = false;"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(s.active().unwrap().selection.objects.len(), n); + r + }; + deselect(1).unwrap(); + let error = deselect(200).unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{error}"); +} + +/// Reading `hasSelectedArtwork` is charged for every selected object it looks at. +#[test] +fn has_selected_artwork_charges_the_selection_it_reads() { + let repeated = |n: usize| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect(); + s.execute("layer.new", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13))); + let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork;"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + r + }; + repeated(1).unwrap(); + let error = repeated(200).unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{error}"); +} + +/// While a group is isolated, `hasSelectedArtwork = true` selects the art inside the group, as +/// Select All does. +#[test] +fn has_selected_artwork_selects_inside_an_isolated_group() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": g})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.hasSelectedArtwork = true; vc.log(l.hasSelectedArtwork);"); + assert_eq!(out, [json!(true)]); + let sel = &s.active().unwrap().selection.objects; + assert!(sel.contains(&a) && sel.contains(&b), "{sel:?}"); +} + +/// While Lock Guides is on, a path made into a guide is not counted as art to add, so a selection +/// at the limit does not refuse a layer that holds only such a path. +#[test] +fn has_selected_artwork_skips_locked_guide_paths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 220.0, 30.0, 10.0, 10.0); + s.active_mut().unwrap().selection.objects = vec![other; 10_000]; + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap_or_else(|e| panic!("{e}")); + assert_eq!(s.active().unwrap().selection.objects.len(), 10_000); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap(); + assert_eq!(undo_steps(&s), steps); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + +#[test] +fn the_report_gives_the_active_artboard_the_run_leaves() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]); A.add([800, 300, 900, 100]);").unwrap(); + // The chosen artboard is deleted later in the run: the report gives the one active at the end. + let r = + run(&mut s, "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(2); A.remove(2); vc.log(A.getActiveArtboardIndex());").unwrap(); + let active = r["log"][0].clone(); + assert!(active.as_u64().is_some_and(|i| i < 2), "{r}"); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": active}])); +} + +#[test] +fn the_report_gives_the_active_artboards_new_index_after_an_insert_or_remove() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]); A.setActiveArtboardIndex(1);").unwrap(); + // An artboard inserted or removed before the active one moves it to another index. + let r = run(&mut s, "var A = app.activeDocument.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([2])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 2}])); + let r = run(&mut s, "var A = app.activeDocument.artboards; A.remove(0); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + // One added after it leaves its index as it was. + let r = run(&mut s, "app.activeDocument.artboards.add([1000, 300, 1100, 100]);").unwrap(); + assert!(r.get("activeArtboards").is_none(), "{r}"); +} + +#[test] +fn an_artboard_rectangle_stays_inside_the_canvas() { + let (mut s, _, _) = doc(); + let before = format!("{:?}", s.active().unwrap().doc.artboards); + let steps = undo_steps(&s); + // Each number is within the coordinate range, but the right edge is past the canvas. + for src in [ + "app.activeDocument.artboards[0].artboardRect = [3999950, 0, 4000100, -100];", + "app.activeDocument.artboards.add([-4000100, 0, -3999950, -100]);", + "app.activeDocument.artboards.insert([0, 4000600, 100, 4000500], 0);", + ] { + assert!(failure(&mut s, src).contains("outside the canvas"), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.artboards), before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn has_selected_artwork_selects_and_deselects_a_layers_art() { + let (mut s, a, b) = doc(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0]; vc.log(l.hasSelectedArtwork); l.hasSelectedArtwork = true;\ + vc.log(app.activeDocument.selection.length); vc.log(l.hasSelectedArtwork); vc.log(l.isIsolated);", + ); + assert_eq!(out, [json!(false), json!(2), json!(true), json!(false)]); + let sel = &s.active().unwrap().selection.objects; + assert!(sel.contains(&a) && sel.contains(&b)); + run(&mut s, "app.activeDocument.layers[0].hasSelectedArtwork = false;").unwrap(); + assert!(s.active().unwrap().selection.objects.is_empty()); + assert!(failure(&mut s, "app.activeDocument.layers[0].hasSelectedArtwork = 0;").contains("true or false")); +} + +#[test] +fn has_selected_artwork_keeps_the_rest_of_the_selection() { + let (mut s, a, b) = doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + // An empty layer has nothing to deselect or add: the selected guide stays. + let steps = undo_steps(&s); + run(&mut s, "var l = app.activeDocument.layers.add(); l.hasSelectedArtwork = false; l.hasSelectedArtwork = true;").unwrap(); + assert_eq!(s.active().unwrap().selection.guides.len(), 1); + assert_eq!(undo_steps(&s), steps + 1); + // Deselecting a layer's art leaves the guide selected, and so does adding it. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = false;").unwrap(); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.len(), sel.guides.len()), (0, 1)); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap(); + let sel = &s.active().unwrap().selection; + assert!(sel.objects.contains(&a) && sel.objects.contains(&b)); + assert_eq!(sel.guides.len(), 1); +} + +/// The selection limit counts only the art an assignment would add: a layer with nothing to add +/// changes nothing beside a selection already at the limit, and one with art to add throws. +#[test] +fn has_selected_artwork_checks_the_limit_only_for_art_it_adds() { + let (mut s, a, _) = doc(); + run(&mut s, "app.activeDocument.layers.add();").unwrap(); + // A selection of 10,001 entries, as the limit counts them. + s.active_mut().unwrap().selection.objects = vec![a; 10_001]; + run(&mut s, "var l = app.activeDocument.layers[0]; l.hasSelectedArtwork = true;").unwrap_or_else(|e| panic!("{e}")); + assert_eq!(s.active().unwrap().selection.objects.len(), 10_001); + s.active_mut().unwrap().selection.objects = vec![a; 10_000]; + let e = failure(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;"); + assert!(e.contains("at most 10000"), "{e}"); +} + +#[test] +fn has_selected_artwork_on_an_empty_layer_passes_a_full_selection() { + let (mut s, a, _) = doc(); + let n = crate::script::dom::MAX_LISTED; + // Each Duplicate of everything doubles the objects. + s.execute("select.all", &json!({})).unwrap(); + for _ in 0..n.ilog2() { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + assert!(s.active().unwrap().selection.objects.len() > n); + // The empty layer adds nothing, so the selection's size does not matter. + run(&mut s, "app.activeDocument.layers.add().hasSelectedArtwork = true;").unwrap(); + // A layer with an unselected object would take the selection past the limit. + s.execute("select.toggle", &json!({"ids": [a.0]})).unwrap(); + assert!(s.active().unwrap().selection.objects.len() > n); + let steps = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").contains("at most")); + assert!(!s.active().unwrap().selection.objects.contains(&a)); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn artboards_insert_gives_undefined_and_index_reflects_an_artboard() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; vc.log(typeof A.insert([500, 300, 700, 100], 0));\ + function info(o, n) { var m = o.reflect.methods; for (var i = 0; i < m.length; i++) if (m[i].name == n) return m[i].dataType + ':' + m[i].arguments[0].dataType; }\ + function prop(o, n) { var m = o.reflect.properties; for (var i = 0; i < m.length; i++) if (m[i].name == n) return m[i].dataType; }\ + vc.log(info(A, 'index')); vc.log(prop(app.activeDocument.pageItems, 'parent'));", + ); + assert_eq!(out, [json!("undefined"), json!("Artboard:*"), json!("*")]); +} + +#[test] +fn artboards_stop_at_one_hundred() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; for (var i = 1; i < 100; i++) A.add([i * 10, -400, i * 10 + 5, -405]);").unwrap(); + assert_eq!(s.active().unwrap().doc.artboards.len(), 100); + let steps = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.artboards.add([0, -500, 10, -510]);").contains("at most 100 artboards")); + assert!(failure(&mut s, "app.activeDocument.artboards.insert([0, -500, 10, -510], 0);").contains("at most 100 artboards")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 100); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn every_page_item_has_its_layer_and_members_check_this() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems[0], n = d.layers.add(); n.name = 'Up'; p.move(n);\ + vc.log(p.layer.name); vc.log(d.pageItems[d.pageItems.length - 1].layer.name); vc.log(p.layer.layers.typename);\ + vc.log(n.pageItems.typename); vc.log(n.groupItems.typename);", + ); + assert_eq!(out, [json!("Up"), json!("Layer 1"), json!("Layers"), json!("PageItems"), json!("GroupItems")]); + for src in [ + "Object.getOwnPropertyDescriptor(Layers.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(GroupItems.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Artboard.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Artboards.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Layer.prototype, 'pathItems').get.call({});", + ] { + assert!(failure(&mut s, src).contains("this is not a"), "{src}"); + } + let stale = "var L = app.activeDocument.layers, n = L.add(), c = n.layers, g = n.groupItems; n.remove();"; + for read in ["c.typename", "g.typename", "n.pathItems"] { + assert!(failure(&mut s, &format!("{stale} {read};")).contains("Stale"), "{read}"); + } } /// A script that names each visible selected object after its place in `app.selection`, testing @@ -2445,7 +4963,7 @@ 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('isIsolated'), p.hasOwnProperty('transform'), d.hasOwnProperty('layers'),\ + vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('swatches'),\ p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);", ); diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs new file mode 100644 index 0000000000..8fc2876981 --- /dev/null +++ b/crates/engine/src/tests/script_dom_images.rs @@ -0,0 +1,822 @@ +//! Placed and raster items in the script object model: placing a file with `PlacedItems.add()`, +//! relinking, embedding, the encoded image's header, and the file checks. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +/// A fresh folder for test `name`, with a `main` folder for the script and an `outside` folder the +/// script may not read, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-dom-images-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + PathBuf::from(plain_path(&std::fs::canonicalize(&base).unwrap().to_string_lossy())) +} + +/// A `w`×`h` 8-bit gray PNG. +fn gray_png(w: u32, h: u32) -> Vec { + let raw = vec![128u8; (w * h) as usize]; + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, raw).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// The path as the inside of a single-quoted script string: JSON escapes backslashes, quotes, +/// line breaks and control characters, and the apostrophe is escaped as well. +fn js_path(p: &Path) -> String { + let quoted = Value::String(plain_path(&p.to_string_lossy())).to_string(); + quoted[1..quoted.len() - 1].replace('\'', "\\'") +} + +fn plain_path(path: &str) -> String { + if let Some(tail) = path.strip_prefix(r"\\?\UNC\") { format!(r"\\{tail}") } else { path.strip_prefix(r"\\?\").unwrap_or(path).to_string() } +} + +#[test] +fn fixture_paths_strip_verbatim_prefixes_on_every_platform() { + let drive = format!("{}{}", r"\\?\", r"C:\x\a.png"); + let unc = format!("{}{}", r"\\?\UNC\", r"server\share\a.png"); + assert_eq!(plain_path(&drive), r"C:\x\a.png"); + assert_eq!(plain_path(&unc), r"\\server\share\a.png"); + assert_eq!(js_path(Path::new(&drive)), r"C:\\x\\a.png"); + assert_eq!(js_path(Path::new("a\nb'c\"d")), r#"a\nb\'c\"d"#); + assert_eq!(plain_path("/tmp/a.png"), "/tmp/a.png"); +} + +/// A session with one 400 × 300 pt document. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +/// Runs `text` as `main/main.jsx` in `base`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn log(s: &mut Session, base: &Path, text: &str) -> Vec { + let r = run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +fn failure(s: &mut Session, base: &Path, text: &str) -> String { + run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The images of the active document: (id, linked path). +fn images(s: &Session) -> Vec<(NodeId, Option)> { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + out.push((n.id, im.link.as_ref().map(|l| l.path.clone()))); + } + }); + out +} + +/// Places `path` linked (`link`) with the engine's own command, outside any script. +fn place(s: &mut Session, path: &Path, link: bool) -> NodeId { + let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": link})).unwrap(); + NodeId(r["ids"][0].as_u64().unwrap()) +} + +#[test] +fn placed_add_file_keeps_wrapper_identity_in_collections() { + let base = folder("bound-identity"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 4)).unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.placedItems.add(); p.file = new File('{}'); p.name = 'placed'; d.selection = [p];\ + vc.log(p === d.placedItems[0]); vc.log(p === d.placedItems.getByName('placed'));\ + vc.log(p === d.pageItems[0]); vc.log(p === d.selection[0]);", + js_path(&png) + ), + ); + assert_eq!(out, vec![json!(true); 4]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn placed_add_file_links_one_image() { + let base = folder("add"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(40, 20)).unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.placedItems.add(); vc.log(p.file); vc.log(d.placedItems.length);\ + var m = ''; try {{ p.width; }} catch (e) {{ m = e.message; }} vc.log(m);\ + p.file = new File('{}'); vc.log(d.placedItems.length); vc.log(p.typename); vc.log(p.file.name);\ + vc.log(p.width); vc.log(d.placedItems[0].file.name); vc.log(d.rasterItems.length);\ + try {{ p.file = new File('{}'); }} catch (e) {{ m = e.message; }} vc.log(m);", + js_path(&png), + js_path(&png) + ), + ); + assert_eq!(out[..3], [json!(null), json!(0), json!("PlacedItem.file is required")]); + assert_eq!(out[3..9], [json!(1), json!("PlacedItem"), json!("a.png"), json!(40), json!("a.png"), json!(0)]); + assert_eq!(out[9], json!("PlacedItem.file is read-only: use relink")); + let imgs = images(&s); + assert_eq!(imgs.len(), 1); + assert_eq!(imgs[0].1.as_deref().map(Path::new), Some(png.as_path())); + assert_eq!(undo_steps(&s), 1); + let _ = std::fs::remove_dir_all(base); +} + +/// A `placedItems.add()` result made before File › Revert is stale, as the document's other objects +/// are, and places nothing. +#[test] +fn a_placed_items_add_result_is_stale_after_a_revert() { + let base = folder("add-revert"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 2)).unwrap(); + let mut s = session(); + s.execute("document.save", &json!({"path": base.join("main/saved.vectorcraft").to_string_lossy()})).unwrap(); + let assign = format!("p.file = new File('{}')", js_path(&png)); + for read in ["p.file", assign.as_str()] { + let e = failure( + &mut s, + &base, + &format!("var d = app.activeDocument; d.pathItems.rectangle(0, 0, 10, 10); var p = d.placedItems.add(); vc.run('file.revert'); {read};"), + ); + assert!(e.contains("Stale page item"), "{read}: {e}"); + } + assert!(images(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn placed_file_refuses_bad_values_without_changing_the_document() { + let base = folder("bad"); + std::fs::write(base.join("main/notes.txt"), "hello").unwrap(); + std::fs::write(base.join("outside/b.png"), gray_png(4, 4)).unwrap(); + let big = std::fs::File::create(base.join("main/big.png")).unwrap(); + big.set_len((256 << 20) + 1).unwrap(); + drop(big); + let mut s = session(); + let cases = [ + ("'a.png'", "must be a File"), + ("{}", "must be a File"), + (&format!("new File('{}')", js_path(&base.join("main/notes.txt"))), "not an image"), + (&format!("new File('{}')", js_path(&base.join("outside/b.png"))), "Script file access denied"), + (&format!("new File('{}')", js_path(&base.join("main/big.png"))), "larger than 256 MiB"), + (&format!("new File('{}')", js_path(&base.join("main/none.png"))), "does not exist"), + (&format!("new Folder('{}')", js_path(&base.join("main"))), "must be a File"), + ]; + for (value, message) in cases { + let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems.add().file = {value};")); + assert!(e.contains(message), "{value}: {e}"); + assert!(!e.contains("outside"), "{value}: {e}"); + assert!(images(&s).is_empty(), "{value}"); + assert_eq!(undo_steps(&s), 0, "{value}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_plain_object_shaped_like_a_file_is_not_one() { + let base = folder("forged"); + std::fs::write(base.join("outside/b.png"), gray_png(4, 4)).unwrap(); + let mut s = session(); + let forged = js_path(&base.join("outside/b.png")); + let e = failure(&mut s, &base, &format!("var f = {{}}; f['\\u0000fileRef'] = '{forged}'; app.activeDocument.placedItems.add().file = f;")); + assert!(e.contains("not plain data"), "{e}"); + assert!(images(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_forged_or_altered_file_does_not_change_the_path() { + let base = folder("forged-proto"); + let (a, b, c) = (base.join("main/a.png"), base.join("main/b.png"), base.join("outside/c.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + std::fs::write(&c, gray_png(30, 10)).unwrap(); + let mut s = session(); + let forged = js_path(&c); + let make = format!( + "var f = Object.create(File.prototype); f.__vcPath = '{forged}';\ + Object.defineProperty(f, 'fsName', {{value: '{forged}', enumerable: true}});\ + Object.defineProperty(f, 'path', {{value: '{forged}', enumerable: true}});" + ); + for target in ["app.activeDocument.placedItems.add().file = f;", "app.activeDocument.placedItems[0].relink(f);"] { + if target.contains("relink") { + place(&mut s, &a, true); + } + let e = failure(&mut s, &base, &format!("{make} {target}")); + assert!(e.contains("must be a File") && !e.contains("c.png"), "{target}: {e}"); + } + let id = images(&s)[0].0; + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + let alter = format!( + "f.__vcPath = '{forged}'; Object.defineProperty(f, '__vcPath', {{value: '{forged}'}});\ + Object.defineProperty(f, 'fsName', {{value: '{forged}', enumerable: true}});" + ); + let out = log( + &mut s, + &base, + &format!( + "var f = new File('{}'); {alter} var p = app.activeDocument.placedItems.add(); p.file = f; vc.log(p.file.name);\ + f = new File('{}'); {alter} p.relink(f); vc.log(p.file.name);", + js_path(&b), + js_path(&a) + ), + ); + assert_eq!(out, vec![json!("b.png"), json!("a.png")]); + let paths: Vec<_> = images(&s).into_iter().map(|(_, p)| p).collect(); + assert_eq!(paths.len(), 2); + assert!(paths.iter().all(|p| p.as_deref().map(Path::new) == Some(a.as_path())), "{paths:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_placed_items_add_result_is_a_relative_object() { + let base = folder("relative"); + let (a, b) = (base.join("main/a.png"), base.join("main/b.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + let mut s = session(); + let first = place(&mut s, &a, true); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, q = d.placedItems[0], p = d.placedItems.add(), m = '';\ + try {{ q.move(p, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m = e.message; }} vc.log(m);\ + p.file = new File('{}'); q.move(p, ElementPlacement.PLACEBEFORE);", + js_path(&b) + ), + ); + assert_eq!(out, vec![json!("PlacedItem.file is required")]); + let order: Vec = images(&s).into_iter().map(|(id, _)| id).collect(); + assert_eq!(order.len(), 2); + assert_eq!(order[1], first, "{order:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_file_that_is_not_an_image_is_refused_before_placing() { + let base = folder("text"); + let notes = base.join("main/notes.txt"); + std::fs::write(¬es, "hello").unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!("try {{ app.activeDocument.placedItems.add().file = new File('{}'); }} catch (e) {{ vc.log(e.message); }}", js_path(¬es)), + ); + assert_eq!(out, vec![json!("The file is not an image")]); + assert_eq!(s.active().unwrap().doc.layers[0].children().map_or(0, |c| c.len()), 0); + assert_eq!(undo_steps(&s), 0); + let _ = std::fs::remove_dir_all(base); +} + +/// How many times the engine read the file at `path` on this thread since the last call. +#[cfg(not(target_arch = "wasm32"))] +fn reads_of(path: &Path) -> usize { + let path = path.to_string_lossy(); + crate::cmd::fileio::FILES_READ.with(|r| r.take().iter().filter(|p| plain_path(p) == path).count()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn placing_or_relinking_from_a_script_reads_the_file_once() { + let base = folder("read-once"); + let (a, b) = (base.join("main/a.png"), base.join("main/b.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + let mut s = session(); + reads_of(&a); + log(&mut s, &base, &format!("app.activeDocument.placedItems.add().file = new File('{}');", js_path(&a))); + assert_eq!(reads_of(&a), 1, "placing reads the file once"); + log(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&b))); + assert_eq!(reads_of(&b), 1, "relinking reads the file once"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn relinking_to_a_file_that_is_not_an_image_keeps_the_link() { + let base = folder("relink-text"); + let (a, notes) = (base.join("main/a.png"), base.join("main/notes.txt")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(¬es, "hello").unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let before = undo_steps(&s); + let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(¬es))); + assert!(e.contains("The file is not an image") && !e.contains("notes.txt"), "{e}"); + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + assert_eq!(undo_steps(&s), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn placed_items_add_is_bounded() { + let base = folder("pending"); + let mut s = session(); + let e = failure(&mut s, &base, "var p = app.activeDocument.placedItems; for (var i = 0; i < 1025; i++) p.add();"); + assert!(e.contains("at most 1024"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn relink_denied_path_preserves_old_link() { + let base = folder("relink"); + let (a, b, c) = (base.join("main/a.png"), base.join("main/b.png"), base.join("outside/c.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + std::fs::write(&c, gray_png(30, 10)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&c))); + assert!(e.contains("Script file access denied") && !e.contains("c.png"), "{e}"); + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + let before = undo_steps(&s); + let out = log(&mut s, &base, &format!("var p = app.activeDocument.placedItems[0]; p.relink(new File('{}')); vc.log(p.file.name);", js_path(&b))); + assert_eq!(out, vec![json!("b.png")]); + assert_eq!(images(&s), vec![(id, Some(b.to_string_lossy().into_owned()))]); + assert_eq!(undo_steps(&s), before + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn embed_reclassifies_and_stales_wrapper() { + let base = folder("embed"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0]; p.embed(); var m = '';\ + try { p.name; } catch (e) { m = e.message; } vc.log(m);\ + vc.log(d.placedItems.length); var r = d.rasterItems[0]; vc.log(r.typename);\ + vc.log(r.embedded); vc.log(r.file); vc.log(r.status === RasterLinkState.NODATA); r.embedded = true;\ + try { r.embedded = false; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out[..6], [json!("Stale page item"), json!(0), json!("RasterItem"), json!(true), json!(null), json!(true)]); + assert!(out[6].as_str().unwrap().contains("cannot be linked"), "{out:?}"); + assert_eq!(images(&s), vec![(id, None)]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn embed_gives_raster_item_a_new_object() { + let base = folder("embed-new"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], q = d.pageItems[0]; vc.log(p === q); p.embed();\ + var r = d.rasterItems[0]; vc.log(p === r); vc.log(r.typename); vc.log(d.pageItems[0] === r); var m = '';\ + try { p.name; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, vec![json!(true), json!(false), json!("RasterItem"), json!(true), json!("Stale page item")]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn missing_link_embed_reports_error() { + let base = folder("missing"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + std::fs::remove_file(&a).unwrap(); + let before = undo_steps(&s); + let e = failure(&mut s, &base, "app.activeDocument.placedItems[0].embed();"); + assert!(e.contains("Linked image is missing"), "{e}"); + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + assert_eq!(undo_steps(&s), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn embed_keeps_an_exact_image_id_above_javascript_integer_precision() { + let base = folder("embed-big-id"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 4)).unwrap(); + let mut s = session(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let id = place(&mut s, &png, true); + assert_eq!(id, NodeId(big)); + let out = + log(&mut s, &base, "var d = app.activeDocument; d.placedItems[0].embed(); vc.log(d.placedItems.length); vc.log(d.rasterItems[0].embedded);"); + assert_eq!(out, [json!(0), json!(true)]); + assert_eq!(images(&s), vec![(id, None)]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn raster_metadata_uses_encoded_header_not_rgb_fallback() { + let base = folder("meta"); + let (g, c) = (base.join("main/g.png"), base.join("main/c.png")); + std::fs::write(&g, gray_png(6, 4)).unwrap(); + std::fs::write(&c, super::links::png(3, 2, [10, 20, 30])).unwrap(); + let mut s = session(); + place(&mut s, &g, false); + place(&mut s, &c, false); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems, t = [];\ + for (var i = 0; i < r.length; i++) t.push([r[i].imageColorSpace, r[i].channels, r[i].bitsPerChannel, r[i].transparent, r[i].colorizedGrayscale]);\ + vc.log(t); vc.log(r[1].boundingBox); vc.log(r[0].imageColorSpace === ImageColorSpace.RGB); var m = r[0].matrix; vc.log([m.typename, m.mValueA, m.mValueD]);", + ); + // The collection lists the images topmost first, as `pageItems` does: the color image placed last comes first. + assert_eq!(out[0], json!([["ImageColorSpace.RGB", 4, 8, true, false], ["ImageColorSpace.Grayscale", 1, 8, false, false]])); + assert_eq!(out[1], json!([0, 4, 6, 0])); + assert_eq!(out[2], json!(true)); + let m = out[3].as_array().unwrap(); + assert_eq!(m[0], json!("Matrix")); + assert!(m[1].as_f64().unwrap() > 0.0 && m[2].as_f64().unwrap() < 0.0, "{m:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_matrix_assignment_transforms_the_image() { + let base = folder("matrix"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, false); + let before = undo_steps(&s); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0], m = r.matrix;\ + m.mValueA = 0; m.mValueB = 2; m.mValueC = -3; m.mValueD = 0; m.mValueTX = 50; m.mValueTY = 60; r.matrix = m;\ + var n = r.matrix; vc.log([n.mValueA, n.mValueB, n.mValueC, n.mValueD, n.mValueTX, n.mValueTY]); r.matrix = n;", + ); + let got: Vec = out[0].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + for (g, w) in got.iter().zip([0.0, 2.0, -3.0, 0.0, 50.0, 60.0]) { + assert!((g - w).abs() < 1e-6, "{got:?}"); + } + let xf = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Image(im) => im.xf.as_coeffs(), + _ => panic!("not an image"), + }; + assert!((xf[1] + 2.0).abs() < 1e-6 && (xf[2] + 3.0).abs() < 1e-6, "{xf:?}"); + assert_eq!(undo_steps(&s), before + 1); + log(&mut s, &base, "var r = app.activeDocument.rasterItems[0]; r.matrix = r.matrix;"); + assert_eq!(undo_steps(&s), before + 1); + // A change smaller than 1e-9 to the linear part still counts. + log(&mut s, &base, "var r = app.activeDocument.rasterItems[0], m = r.matrix; m.mValueB = m.mValueB * (1 + 1e-10); r.matrix = m;"); + assert_eq!(undo_steps(&s), before + 2); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_tiny_matrix_change_still_transforms_the_image() { + let base = folder("matrix-tiny"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, false); + let before = undo_steps(&s); + let tx = |s: &Session| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Image(im) => im.xf.as_coeffs()[4], + _ => panic!("not an image"), + }; + let old = tx(&s); + log(&mut s, &base, "var r = app.activeDocument.rasterItems[0], m = r.matrix; m.mValueTX = m.mValueTX + 5e-10; r.matrix = m;"); + assert_eq!(undo_steps(&s), before + 1); + assert!(tx(&s) != old, "the image did not move"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_stale_placed_item_is_not_a_relative_object() { + let base = folder("stale-relative"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + place(&mut s, &a, true); + place(&mut s, &a, true); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.placedItems[0], q = d.placedItems[1], r = d.placedItems[2], m = [];\ + r.move(q, ElementPlacement.PLACEBEFORE); m.push('live');\ + var n = d.placedItems.add(); n.file = new File('{}'); r.move(n, ElementPlacement.PLACEAFTER); m.push('added');\ + p.embed();\ + try {{ r.move(p, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\ + try {{ r.duplicate(p, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\ + n.embed();\ + try {{ r.move(n, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\ + try {{ r.duplicate(n, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\ + vc.log(m);", + js_path(&a) + ), + ); + assert_eq!(out, vec![json!(["live", "added", "Stale page item", "Stale page item", "Stale page item", "Stale page item"])]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_matrix_refuses_locked_hidden_and_locked_artboard_images() { + let base = folder("matrix-locks"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, true); + // A moved matrix and the matrix the image already has are refused alike. + let sets = [ + "var p = app.activeDocument.placedItems[0], m = p.matrix; m.mValueTX = m.mValueTX + 5; p.matrix = m;", + "var p = app.activeDocument.placedItems[0]; p.matrix = p.matrix;", + ]; + let refused = |s: &mut Session, message: &str| { + for set in sets { + let (was, before) = (s.active().unwrap().doc.clone(), undo_steps(s)); + let e = failure(s, &base, set); + assert!(e.contains(message), "{set}: {e}"); + assert_eq!(*s.active().unwrap().doc, *was, "{set}"); + assert_eq!(undo_steps(s), before, "{set}"); + } + }; + for (field, set_to, message) in [("locked", true, "cannot transform locked objects"), ("visible", false, "cannot transform hidden objects")] { + s.execute("object.setProps", &json!({"ids": [id.0], field: set_to})).unwrap(); + refused(&mut s, message); + s.execute("object.setProps", &json!({"ids": [id.0], field: !set_to})).unwrap(); + } + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + refused(&mut s, "cannot transform objects on a locked artboard"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_matrix_refuses_bad_values_without_changing_the_image() { + let base = folder("matrix-bad"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, true); + let xf = |s: &Session| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Image(im) => im.xf, + _ => panic!("not an image"), + }; + let (was, before) = (xf(&s), undo_steps(&s)); + let cases = [ + ("m.mValueA = NaN;", "mValueA is not a finite number"), + ("m.mValueTY = -Infinity;", "mValueTY is not a finite number"), + ("m.mValueB = '1';", "finite mValueB"), + ("delete m.mValueTX;", "finite mValueTX"), + ("m = 5;", "finite mValueA"), + ("m.mValueA = 0; m.mValueD = 0;", "no area"), + ("m.mValueA = 1e300;", "outside the canvas"), + ("m.mValueTX = 9e6;", "outside the canvas"), + ("m.mValueA = 1e6;", "outside the canvas"), + ]; + for (change, message) in cases { + let e = failure(&mut s, &base, &format!("var p = app.activeDocument.placedItems[0], m = p.matrix; {change} p.matrix = m;")); + assert!(e.contains(message), "{change}: {e}"); + assert_eq!(xf(&s), was, "{change}"); + assert_eq!(undo_steps(&s), before, "{change}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_file_getter_hides_out_of_scope_link() { + let base = folder("hide"); + let b = base.join("outside/secret.png"); + std::fs::write(&b, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &b, true); + let e = failure(&mut s, &base, "vc.log(app.activeDocument.placedItems[0].file.fsName);"); + assert!(e.contains("Script file access denied") && !e.contains("secret"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_file_getter_resolves_document_relative_and_fallback_paths() { + let base = folder("resolved-file"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 4)).unwrap(); + for (stored, relative) in [ + ("a.png".to_string(), None), + (base.join("missing/a.png").to_string_lossy().into_owned(), None), + (base.join("missing/old.png").to_string_lossy().into_owned(), Some("a.png".to_string())), + ] { + let mut s = session(); + let image = place(&mut s, &png, true); + s.doc_mut().unwrap().path = Some(base.join("main/page.vectorcraft").to_string_lossy().into_owned()); + if relative.is_some() { + s.doc_mut().unwrap().path = Some(base.join("main/saved/page.vectorcraft").to_string_lossy().into_owned()); + s.doc_mut().unwrap().links_from = Some(base.join("main/original.vectorcraft").to_string_lossy().into_owned()); + } + s.edit("Set linked path", |d, _| { + let NodeKind::Image(im) = &mut d.node_mut(image).unwrap().kind else { panic!("not an image") }; + im.link.as_mut().unwrap().path = stored.clone(); + im.link.as_mut().unwrap().relative = relative.clone(); + Ok(()) + }) + .unwrap(); + let out = log(&mut s, &base, &format!("vc.log(app.activeDocument.placedItems[0].file.fsName === new File('{}').fsName);", js_path(&png))); + assert_eq!(out, [json!(true)], "{stored}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_file_getter_hides_a_link_to_an_open_document_out_of_scope() { + let base = folder("hidedoc"); + let b = base.join("outside/secret.png"); + std::fs::write(&b, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &b, true); + // The linked file is also the file of an open document, which the script's commands may read. + s.doc_mut().unwrap().path = Some(b.to_string_lossy().into_owned()); + let e = failure(&mut s, &base, "vc.log(app.activeDocument.placedItems[0].file.fsName);"); + assert!(e.contains("Script file access denied") && !e.contains("secret"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +/// Assigning `file` or `matrix` checks the item before the value: an `add()` result with no file +/// throws `PlacedItem.file is required`, and one that was embedded throws `Stale page item`. +#[test] +fn assignments_check_the_item_before_the_value() { + let base = folder("receiver"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, n = d.placedItems.add(), p = d.placedItems.add(), m = [];\ + try {{ n.matrix = null; }} catch (e) {{ m.push(e.message); }}\ + p.file = new File('{0}'); p.embed();\ + try {{ p.file = new File('{0}'); }} catch (e) {{ m.push(e.message); }}\ + try {{ p.matrix = null; }} catch (e) {{ m.push(e.message); }}\ + try {{ d.rasterItems[0].matrix = null; }} catch (e) {{ m.push(e.name); }}\ + vc.log(m);", + js_path(&a) + ), + ); + assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "Stale page item", "TypeError"])]); + let _ = std::fs::remove_dir_all(base); +} + +/// `removeAll()` deletes no image when one is on a locked artboard, in both collections. +#[test] +fn remove_all_keeps_images_on_a_locked_artboard() { + let base = folder("locked-board"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + let linked = place(&mut s, &a, true); + let embedded = place(&mut s, &a, false); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let steps = undo_steps(&s); + let e = failure(&mut s, &base, "app.activeDocument.placedItems.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", linked.0)), "{e}"); + let e = failure(&mut s, &base, "app.activeDocument.rasterItems.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", embedded.0)), "{e}"); + assert_eq!(images(&s).len(), 2); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + let out = log(&mut s, &base, "var d = app.activeDocument; d.placedItems.removeAll(); d.rasterItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, vec![json!(0)]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn stale_and_foreign_placed_items_are_refused() { + let base = folder("stale"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + place(&mut s, &a, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.placedItems[0], m = []; p.remove();\ + try { p.relink(null); } catch (e) { m.push(e.message); }\ + var g = Object.getOwnPropertyDescriptor(RasterItem.prototype, 'embedded').get;\ + try { g.call(1); } catch (e) { m.push(e.name); }\ + m.push(g.call(app.activeDocument.rasterItems[0]));\ + try { PlacedItem.prototype.embed.call(app.activeDocument); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!(["Stale page item", "TypeError", true, "this is not a PlacedItem"])]); + assert!(s.active().unwrap().doc.node(id).is_none()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn members_not_available_yet_check_the_image_first() { + let base = folder("later"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], n = d.placedItems.add(), m = [];\ + try { n.contentVariable; } catch (e) { m.push(e.message); }\ + p.embed(); try { p.contentVariable; } catch (e) { m.push(e.message); }\ + var r = d.rasterItems[0]; try { r.colorize; } catch (e) { m.push(e.message); }\ + r.remove(); try { r.overprint; } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "RasterItem.colorize is not available yet", "Stale page item"])]); + let _ = std::fs::remove_dir_all(base); +} + +/// The `file` of a `PlacedItems.add()` result with no file is null while its document is open, and +/// the item is stale once that document is closed. +#[test] +fn a_pending_placed_items_file_is_stale_once_its_document_closes() { + let base = folder("pending-closed"); + let mut s = session(); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.placedItems.add(); vc.log(p.file); vc.run('file.close', {});\ + var m = ''; try { vc.log(p.file); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, vec![json!(null), json!("Stale page item")]); + let _ = std::fs::remove_dir_all(base); +} + +/// Assigning `file` binds the placed item to the image `file.place` made, by its exact id, also +/// for an id above 2^53, which a script number does not hold exactly. +#[test] +fn a_placed_items_file_binds_the_exact_id_of_the_image_placed() { + let base = folder("big-id"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 4)).unwrap(); + let mut s = session(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log( + &mut s, + &base, + &format!("var p = app.activeDocument.placedItems.add(); p.file = new File('{}'); vc.log(p.file.name); vc.log(p.width);", js_path(&png)), + ); + assert_eq!(out, vec![json!("a.png"), json!(4)]); + let imgs = images(&s); + assert_eq!(imgs.len(), 1, "{imgs:?}"); + assert_eq!(imgs[0].0, NodeId(big)); + let _ = std::fs::remove_dir_all(base); +} + +/// A `PlacedItem` that was embedded is stale as the relative object of `move`: the raster item +/// it became is named by a fresh wrapper. +#[test] +fn a_stale_placed_item_is_refused_as_the_relative_object_of_move() { + let base = folder("stale-relative"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], x = null, m = '';\ + for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') x = d.pageItems[i]; }\ + p.embed(); try { x.move(p, ElementPlacement.PLACEAFTER); } catch (e) { m = e.message; } vc.log(m);\ + x.move(d.rasterItems[0], ElementPlacement.PLACEAFTER); vc.log([d.pageItems[0].typename, d.pageItems[1].typename]);", + ); + assert_eq!(out, vec![json!("Stale page item"), json!(["RasterItem", "PathItem"])]); + assert!(s.active().unwrap().doc.node(NodeId(rect)).is_some()); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 8988c042eb..1078f7078e 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -50,6 +50,114 @@ fn node(s: &Session, id: NodeId) -> crate::doc::Node { s.active().unwrap().doc.node(id).unwrap().clone() } +#[test] +fn path_creation_replays_on_top_of_the_active_layer() { + for mode in ["behind", "inside", "isolation"] { + for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { + let setup = || { + let (mut s, a, b) = doc(); + if mode == "isolation" { + let group = s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].clone(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + } else { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + } + s + }; + let mut s = setup(); + let start = s.journal.len(); + log(&mut s, &format!("app.activeDocument.pathItems.{create};")); + let mut replay = setup(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s), "{mode}: {create}"); + assert_eq!(replay.draw_mode, s.draw_mode); + assert_eq!(replay.active().unwrap().isolation, s.active().unwrap().isolation); + } + } +} + +#[test] +fn path_paint_edits_replay_without_changing_new_art() { + let (mut s, a, _) = doc(); + let start = s.journal.len(); + log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\ + p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7;\ + app.activeDocument.pathItems.rectangle(100, 200, 20, 30);", + ); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(node(&replay, a).appearance, node(&s, a).appearance); + assert_eq!(art(&replay), art(&s)); + assert_eq!(replay.paint, s.paint); + assert_eq!(replay.fill_active, s.fill_active); + assert_eq!(replay.recent_colors, s.recent_colors); +} + +#[test] +fn mixed_anchor_and_segment_picks_keep_independent_anchors() { + for selected in ["ANCHORPOINT", "NOSELECTION"] { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 3]]})).unwrap(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints[0].selected);\ + vc.log(p.pathPoints[1].selected); vc.log(p.selectedPathPoints.length);\ + p.pathPoints[{}].selected = PathPointSelection.{selected}; vc.log(p.selectedPathPoints.length);", + if selected == "ANCHORPOINT" { 1 } else { 3 } + ), + ); + assert_eq!(out[..3], [json!("PathPointSelection.ANCHORPOINT"), json!("PathPointSelection.NOSELECTION"), json!(2)]); + assert_eq!(out[3], json!(if selected == "ANCHORPOINT" { 3 } else { 1 })); + assert!(!s.active().unwrap().selection.segments.contains_key(&a)); + assert_eq!(selected_anchors(&s, a), Some(if selected == "ANCHORPOINT" { vec![(0, 0), (0, 1), (0, 3)] } else { vec![(0, 0)] })); + } +} + +#[test] +fn an_empty_path_keeps_closed_before_points_are_added() { + for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);", "p.setEntirePath([]);"] { + let (mut s, _, _) = doc(); + let start = s.journal.len(); + let out = log( + &mut s, + &format!("var p = app.activeDocument.pathItems.add(); p.closed = true; vc.log(p.closed); vc.run('select.none'); {add} vc.log(p.closed);"), + ); + assert_eq!(out, [json!(true), json!(true)]); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s)); + } +} + +#[test] +fn enabling_path_paint_preserves_the_new_art_color_model() { + for fill in [true, false] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; + s.execute(cmd, &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute(cmd, &json!({"color": "#12ab34", "keepModel": true})).unwrap(); + let new_art = s.new_art(); + let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() }; + log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }); + let n = node(&s, a); + assert_eq!(if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }, want); + } +} + /// Each number of `v` rounded to 3 decimals, in place. fn rounded(v: &Value) -> Value { match v { @@ -98,6 +206,81 @@ fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() { assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); } +/// `pathItems` read with a name gives what `getByName` gives, and throws as it does for no match, +/// as `pageItems` does. +#[test] +fn path_items_read_with_a_name_give_the_named_path() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "n"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems, m = [];\ + vc.log([p['n'] === p.getByName('n'), p['n'].name, 'n' in p, 'nosuch' in p, p['length'] === p.length]);\ + try { p['nosuch']; } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]); +} + +#[test] +fn path_items_read_non_index_numbers_as_names() { + for name in ["-1", "1.5", "4294967295"] { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": name})).unwrap(); + let out = log( + &mut s, + &format!( + "var d = app.activeDocument; vc.log(d.pathItems['{name}'].name);\ + vc.log(d.pathItems[{name}].name == d.pageItems[{name}].name);\ + vc.log(d.pathItems[-2] === undefined); vc.log(d.pathItems[1].name == '{name}');" + ), + ); + assert_eq!(out, vec![json!(name), json!(true), json!(true), json!(false)]); + } +} + +/// `pathItems` read with a name that is the text of a number but not an array index, such as `-1` +/// or `1.5`, gives the path of that name, and `undefined` when no path has it; `index` still takes +/// a number as a position, as in `pageItems`. +#[test] +fn path_items_read_with_a_number_name_that_is_not_an_index_give_the_named_path() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems, m = [];\ + vc.log([p['-1'] === p.getByName('-1'), '-1' in p, p[-1] === p.getByName('-1'), p['1.5'] === undefined, '1.5' in p]);\ + try { p.index(-1); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!([true, true, true, true, false]), json!(["Not found"])]); +} + +/// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes +/// nothing, as `pageItems.removeAll()` and `remove()` do. +#[test] +fn path_items_remove_all_refuses_paths_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("object.group", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let (before, steps) = (art(&s), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()) && e.contains(&b.0.to_string()), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + log(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); +} + #[test] fn shape_creators_use_documented_defaults_and_y_up() { let mut s = Session::new(); @@ -274,6 +457,354 @@ fn path_point_wrapper_goes_stale_after_remove() { ); } +#[test] +fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.pathPoints[1].selected = PathPointSelection.ANCHORPOINT;\ + var anchor = p.pathPoints[1].anchor; p.pathPoints[0].remove();\ + vc.log(p.selectedPathPoints.length); vc.log(p.selectedPathPoints[0].anchor.join() == anchor.join());\ + vc.log(p.pathPoints[0].selected);", + ); + assert_eq!(out, vec![json!(1), json!(true), json!("PathPointSelection.ANCHORPOINT")]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)])); + assert!(s.active().unwrap().selection.contains(b)); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert!(!s.active().unwrap().selection.contains(a)); + assert!(s.active().unwrap().selection.contains(b)); + + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert!(!s.active().unwrap().selection.contains(a)); + assert!(!s.active().unwrap().selection.segments.contains_key(&a)); + + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert_eq!(s.active().unwrap().selection.segments.get(&a).unwrap().iter().copied().collect::>(), vec![(0, 1)]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); +} + +#[test] +fn removing_a_point_replays_selection_before_moving_anchors() { + for segments in [false, true] { + let setup = || { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1], [0, 3]]})).unwrap(); + if segments { + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "add"})).unwrap(); + } else { + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); + } + s + }; + let mut s = setup(); + let start = s.journal.len(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + let a = s.active().unwrap().selection.objects[0]; + // The removed anchor's segments take their other ends with them unless a selected segment + // still ends there, so with segments the anchor after the removed one leaves the selection. + assert_eq!(selected_anchors(&s, a), Some(if segments { vec![(0, 1), (0, 2)] } else { vec![(0, 0), (0, 2)] })); + s.execute("path.moveAnchors", &json!({"dx": 7, "dy": 3})).unwrap(); + let mut replay = setup(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s), "segments: {segments}"); + assert_eq!(replay.active().unwrap().selection, s.active().unwrap().selection, "segments: {segments}"); + } +} + +#[test] +fn removing_the_last_selected_point_of_a_path_keeps_the_current_layer() { + let (mut s, _, b) = doc(); + s.execute("layer.new", &json!({"name": "Top"})).unwrap(); + let c = rect(&mut s, 200.0, 50.0, 40.0, 40.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": c.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + let (layer, rows) = { + let st = s.active().unwrap(); + (st.active_layer, st.highlighted_rows()) + }; + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[1].remove();"); + let st = s.active().unwrap(); + assert!(!st.selection.contains(c) && st.selection.contains(b)); + assert_eq!(st.active_layer, layer); + assert_eq!(st.highlighted_rows(), rows); +} + +#[test] +fn emptying_an_unselected_path_keeps_the_targeted_layer() { + let (mut s, a, _) = doc(); + let layer = NodeId(s.execute("layer.new", &json!({"name": "Empty"})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert!(!s.active().unwrap().selection.contains(a)); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints.removeAll();"); + assert_eq!(s.active().unwrap().selection.target, Some(layer)); +} + +#[test] +fn point_selection_reads_flush_removed_closing_segments() { + for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], first = p.pathPoints[0], last = p.pathPoints[3];\ + p.closed = false; vc.log(first.selected); vc.log(last.selected); p.name;\ + vc.log(first.selected); vc.log(last.selected); vc.log(p.pathPoints[1].selected);", + ); + assert_eq!(out[..4], vec![json!("PathPointSelection.ANCHORPOINT"); 4]); + assert_eq!(out[4], json!("PathPointSelection.NOSELECTION")); + } +} + +#[test] +fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() { + for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] { + for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { + let (mut s, a, b) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let anchors = selected_anchors(&s, a); + let steps = undo_steps(&s); + let out = log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.closed = false; {flush}")); + assert_eq!(out, if flush.is_empty() { vec![] } else { vec![json!("flushed")] }); + assert!(!node(&s, a).path_data().unwrap().subpaths[0].closed); + let selection = &s.active().unwrap().selection; + assert!(selection.contains(b)); + assert_eq!(selected_anchors(&s, a), anchors); + let kept: Vec<_> = selection.segments.get(&a).into_iter().flatten().copied().collect(); + assert_eq!(kept, if segments.as_array().unwrap().len() == 1 { vec![] } else { vec![(0, 1)] }); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, a).path_data().unwrap().subpaths[0].closed); + } + } +} + +#[test] +fn path_point_handles_are_stale_after_revert_even_when_geometry_is_unchanged() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-path-points-revert"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for operation in ["pp.length", "pp.parent", "pp[0].anchor = [1, 2]", "pp.add()", "q.anchor", "q.anchor = [1, 2]", "picked.anchor = [1, 2]"] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let before = node(&s, a); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints, q = pp[0], picked = p.selectedPathPoints[0];\ + p.name = 'changed'; vc.run('file.revert');\ + try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}\ + var fresh = app.activeDocument.pathItems[0]; vc.log(fresh.pathPoints.length);\ + fresh.pathPoints[0].anchor = [11, 279]; vc.log(fresh.pathPoints[0].anchor);" + ), + ); + assert_eq!(out, vec![json!("Stale page item"), json!(4), json!([11, 279])], "{operation}"); + assert_ne!(node(&s, a).path_data(), before.path_data()); + s.execute("file.revert", &json!({})).unwrap(); + } +} + +#[test] +fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() { + let (mut s, a, _) = doc(); + s.execute( + "path.setAnchors", + &json!({"id": a.0, "subpaths": [ + {"anchors": [{"x": 0, "y": 0}]}, + {"anchors": [{"x": 10, "y": 10}, {"x": 20, "y": 20}, {"x": 30, "y": 30}]} + ]}), + ) + .unwrap(); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [1, 1], [1, 2]]}], "mode": "set"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [1, 2]})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); + assert_eq!(s.active().unwrap().selection.key_anchor, Some((a, (0, 2)))); +} + +#[test] +fn locked_guides_refuse_path_edits_and_bulk_removal() { + let (mut s, a, _) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + s.set_guides_locked(true); + let (before, steps) = (art(&s), undo_steps(&s)); + for edit in [ + "p.pathPoints[0].anchor = [0, 0]", + "p.pathPoints[0].remove()", + "p.pathPoints.removeAll()", + "p.setEntirePath([[0, 0], [1, 1]])", + "p.closed = false", + "p.translate(1, 0)", + "p.filled = false", + "p.strokeWidth = 12", + "app.activeDocument.pathItems.removeAll()", + ] { + let out = + log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); + assert_eq!(out.first(), Some(&json!("Error")), "{edit}: {out:?}"); + assert!(out[1].as_str().unwrap().contains("guides are locked"), "{edit}: {out:?}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{edit}"); + } + assert!(is_guide(&s, a)); + s.set_guides_locked(false); + log(&mut s, "app.activeDocument.pathItems[0].translate(1, 0);"); + assert_ne!(art(&s), before); +} + +#[test] +fn document_path_creators_use_the_active_layer_during_isolation() { + for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { + let (mut s, a, b) = doc(); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": group.0})).unwrap(); + let layer = s.active().unwrap().active_layer.unwrap(); + let before = node(&s, group); + let selection = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + log(&mut s, &format!("app.activeDocument.pathItems.{create};")); + let st = s.active().unwrap(); + let made = st.doc.node(layer).unwrap().children().unwrap().last().unwrap(); + assert!(matches!(made.kind, NodeKind::Path { .. }), "{create}"); + assert_eq!(st.doc.parent_of(made.id), Some(layer), "{create}"); + assert_eq!(node(&s, group), before, "{create}"); + assert_eq!(st.isolation, Some(group), "{create}"); + assert_eq!(st.selection, selection, "{create}"); + assert_eq!(undo_steps(&s), steps + 1, "{create}"); + } +} + +#[test] +fn paint_writes_refuse_generated_graph_design_paths() { + for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + for unpainted in [false, true] { + let (mut s, a, _) = doc(); + if unpainted { + s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap(); + } + s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); + let graph = NodeId( + s.execute( + "graph.create", + &json!({ + "type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4" + }), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); + let graph_node = node(&s, graph); + let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); + let mut paths = Vec::new(); + design.walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) { + paths.push(n.id); + } + }); + let path = paths[0]; + s.execute("object.setProps", &json!({"ids": [path.0], "name": "generated"})).unwrap(); + let (before, steps) = (art(&s), undo_steps(&s)); + for edit in [ + "p.fillColor = c", + "p.strokeColor = c", + "p.filled = !p.filled", + "p.stroked = !p.stroked", + "p.strokeWidth = 12", + "p.strokeCap = StrokeCap.ROUNDENDCAP", + "p.strokeJoin = StrokeJoin.BEVELENDJOIN", + "p.strokeMiterLimit = 22", + "p.strokeDashes = [3, 4]", + ] { + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems.getByName('generated'), c = new RGBColor(); c.red = 123;\ + try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}" + ), + ); + assert_eq!(out.first(), Some(&json!("Error")), "{kind} {unpainted} {edit}: {out:?}"); + assert!(out[1].as_str().unwrap().contains("did not change the path"), "{kind} {edit}: {out:?}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{kind} {edit}"); + } + } + } +} + +#[test] +fn overprint_writes_refuse_generated_graph_design_paths() { + for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + let (mut s, a, _) = doc(); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#000000"})).unwrap(); + s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); + let graph = NodeId( + s.execute("graph.create", &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4"})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); + let graph_node = node(&s, graph); + let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); + let mut paths = Vec::new(); + design.walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) { + paths.push(n.id); + } + }); + s.execute("object.setProps", &json!({"ids": [paths[0].0], "name": "generated"})).unwrap(); + let before = (art(&s), undo_steps(&s)); + for property in ["fillOverprint", "strokeOverprint"] { + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems.getByName('generated'), before = p.{property};\ + try {{ p.{property} = !before; }} catch (e) {{ vc.log(e.message); }} vc.log(p.{property} == before);" + ), + ); + assert!(out[0].as_str().unwrap().contains("object.setOverprint did not change the path"), "{kind} {property}: {out:?}"); + assert_eq!(out.get(1), Some(&json!(true)), "{kind} {property}"); + assert_eq!((art(&s), undo_steps(&s)), before, "{kind} {property}"); + } + } +} + +#[test] +fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() { + let (mut s, a, b) = doc(); + for i in 0..100 { + rect(&mut s, f64::from(i), 10.0, 2.0, 2.0); + } + let out = log( + &mut s, + &format!( + "var ps = app.activeDocument.pathItems, paths = [], points = [], expected = [];\ + for (var i = 0; i < ps.length; i++) {{ paths.push(ps[i]); points.push(ps[i].pathPoints[0]); }}\ + for (var i = 0; i < paths.length; i++) {{ paths[i].translate(2, 0); expected.push(points[i].anchor.join()); }}\ + var valid = true; for (var i = 0; i < points.length; i++) valid = valid && points[i].anchor.join() == expected[i]; vc.log(valid);\ + vc.run('object.move', {{ids: [{a}], dx: 1, dy: 0}});\ + try {{ points[100].anchor; }} catch (e) {{ vc.log(e.message); }}\ + paths[0].translate(1, 0); vc.log(points[101].anchor.join() == expected[101]);\ + vc.run('object.move', {{ids: [{b}], dx: 1, dy: 0}}); vc.run('edit.undo');\ + try {{ points[101].anchor; }} catch (e) {{ vc.log(e.message); }}", + a = a.0, + b = b.0 + ), + ); + assert_eq!(out, vec![json!(true), json!("Stale path point"), json!(true), json!("Stale path point")]); +} + #[test] fn points_read_before_a_removal_or_replacement_go_stale() { let (mut s, _, _) = doc(); @@ -558,6 +1089,42 @@ fn editing_one_point_on_each_of_many_paths_looks_at_each_path_a_few_times() { assert!(looks < 3000, "{looks} looks at paths for 300 one-point edits"); } +/// After a run reads a path's points, each command makes the run look through the document's +/// changed layers for paths whose points it read, and that look is charged by the objects it +/// looks at: a loop of commands on a large layer ends at the limit on data passed to commands. +#[test] +fn looking_for_changed_points_after_each_command_is_charged() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let mut last = NodeId(0); + for i in 0..2000 { + last = rect(&mut s, f64::from(i % 40) * 10.0, f64::from(i / 40) * 5.0, 4.0, 4.0); + } + s.execute("select.none", &json!({})).unwrap(); + let source = format!( + "vc.log(app.activeDocument.pathItems[0].pathPoints[0].anchor.length);\ + for (var i = 0; i < 100; i++) vc.run('object.move', {{ids: [{}], dx: 1, dy: 0}});", + last.0 + ); + let r = run(&mut s, &source).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["log"], json!([2])); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let e = run(&mut s, &source).map(|r| r.to_string()); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = e.map(|r| panic!("100 commands, each followed by a look at 2,000 objects, ran: {r}")).unwrap_err(); + assert!(e.to_string().ends_with("(limit)"), "{e}"); + // Once the path whose points the run read is gone, later commands look for nothing. + let source = format!( + "var p = app.activeDocument.pathItems[1]; vc.log(p.pathPoints[0].anchor.length); p.remove();\ + for (var i = 0; i < 100; i++) vc.run('object.move', {{ids: [{}], dx: 1, dy: 0}});", + last.0 + ); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let r = run(&mut s, &source); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(r.unwrap_or_else(|e| panic!("{e}"))["log"], json!([2])); +} + #[test] fn point_edits_are_written_before_the_next_other_member_reads() { let (mut s, a, _) = doc(); @@ -676,6 +1243,39 @@ fn filled_true_on_a_compound_member_places_the_gradient_on_the_compound() { } } +#[test] +fn resizing_a_compound_member_with_its_own_line_width_scales_the_compound_stroke() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.strokeWidth = 4; p.resize(50, 50, true, true, true, true, 50);\ + vc.log(p.strokeWidth); vc.log(app.activeDocument.pathItems[1].strokeWidth);", + ); + assert_eq!(out, vec![json!(2), json!(2)], "the compound's stroke halves with the member"); +} + +#[test] +fn transforming_a_compound_member_with_its_own_line_width_scales_the_compound_stroke() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.strokeWidth = 4; p.transform(app.getScaleMatrix(50), true, true, true, true, 50);\ + vc.log(p.strokeWidth); vc.log(app.activeDocument.pathItems[1].strokeWidth);", + ); + assert_eq!(out, vec![json!(2), json!(2)], "transform scales the compound's stroke as resize does"); + // 100 keeps the weight even when the scale is within the tolerance of 100%. + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.transform(app.getScaleMatrix(100.00000005), true, true, true, true, 100);\ + vc.log(p.strokeWidth);", + ); + assert_eq!(out, vec![json!(2)]); +} + #[test] fn set_anchors_reads_smooth_false_as_a_corner() { let (mut s, a, _) = doc(); @@ -1024,6 +1624,71 @@ fn a_point_outside_an_inner_objects_on_path_group_is_stale_after_its_path_change assert_eq!(art(&s), before); } +/// Global Edit gives an edit of one member to the others, so a point read of another member before +/// the edit is stale afterwards, even when an undo puts the member back. +#[test] +fn a_point_of_another_global_edit_member_is_stale_after_an_edit_and_undo() { + let (mut s, a, _) = doc(); + let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "edit"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = s.execute("select.globalEdit", &json!({})).unwrap(); + assert_eq!(r["count"], json!(2), "{r}"); + let before = art(&s); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ + vc.log(m.pathPoints[0].anchor);\ + var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]];\ + vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();", + ); + assert_ne!(out[0], out[1], "the other member took the edit"); + assert_eq!(art(&s), before); + let e = failure( + &mut s, + "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ + var mp = m.pathPoints[0]; mp.anchor;\ + var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]]; app.undo();\ + mp.anchor;", + ); + assert!(e.contains("Stale path point"), "{e}"); + assert_eq!(art(&s), before); +} + +/// Moving a group that holds the selected Global Edit member moves the other members too, so a +/// point read of another member before the move is stale afterwards. +#[test] +fn a_point_of_another_global_edit_member_is_stale_after_its_group_moves_and_undoes() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = s.execute("select.globalEdit", &json!({})).unwrap(); + assert_eq!(r["count"], json!(2), "{r}"); + let before = art(&s); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, m = P.getByName('m');\ + vc.log(m.pathPoints[0].anchor);\ + app.activeDocument.groupItems[0].translate(10, 0);\ + vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();", + ); + assert_ne!(out[0], out[1], "the other member took the move"); + assert_eq!(art(&s), before); + let e = failure( + &mut s, + "var P = app.activeDocument.pathItems, m = P.getByName('m');\ + var mp = m.pathPoints[0]; mp.anchor;\ + app.activeDocument.groupItems[0].translate(10, 0); app.undo();\ + mp.anchor;", + ); + assert!(e.contains("Stale path point"), "{e}"); + assert_eq!(art(&s), before); +} + /// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke. fn doc_with_paints() -> (Session, NodeId) { let (mut s, a, _) = doc(); @@ -1145,7 +1810,7 @@ fn locked_paths_and_wrong_objects_are_refused() { ("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", "Cannot edit PathItem"), ("app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", "Cannot edit PathItem"), ("app.activeDocument.pathItems[0].strokeWidth = 3;", "Cannot edit PathItem"), - ("app.activeDocument.pathItems[0].translate(5, 5);", "Cannot edit PathItem"), + ("app.activeDocument.pathItems[0].translate(5, 5);", "cannot transform locked objects"), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); @@ -1159,6 +1824,78 @@ fn locked_paths_and_wrong_objects_are_refused() { assert!(e.contains("not a PathPoint"), "{e}"); } +/// A point edit of a path on a locked artboard throws `Cannot edit` and changes nothing. +#[test] +fn point_edits_of_a_path_on_a_locked_artboard_are_refused() { + let (mut s, _, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let before = art(&s); + let steps = undo_steps(&s); + for source in [ + "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", + "app.activeDocument.pathItems[0].pathPoints[0].leftDirection = [1, 1];", + "app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("Cannot edit PathItem") && e.contains("locked artboard"), "{source}: {e}"); + } + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); +} + +/// A point placed beyond the canvas throws when it is assigned, and the path keeps its points, so a +/// later member call does not lose an assignment that returned. +#[test] +fn a_point_beyond_the_canvas_throws_when_it_is_assigned() { + let (mut s, a, _) = doc(); + let before = node(&s, a).path_data().unwrap().subpaths.clone(); + let far = crate::MAX_COORD * 1.5; + for source in [ + format!("app.activeDocument.pathItems[0].pathPoints[0].anchor = [{far}, 0];"), + format!("app.activeDocument.pathItems[0].pathPoints[0].rightDirection = [0, {far}];"), + format!("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [{far}, 1]]);"), + ] { + let e = failure(&mut s, &source); + assert!(e.contains("outside the canvas"), "{source}: {e}"); + } + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0], q = p.pathPoints[1];\ + q.anchor = [45, 285];\ + try {{ p.pathPoints[0].anchor = [{far}, 0]; }} catch (e) {{ vc.log('threw'); }}\ + vc.log(q.anchor); vc.log(p.closed);" + ), + ); + assert_eq!(out, vec![json!("threw"), json!([45, 285]), json!(true)]); + let after = node(&s, a).path_data().unwrap().subpaths.clone(); + assert_eq!(after[0].anchors[0], before[0].anchors[0], "the point assigned beyond the canvas stays"); + assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written"); +} + +#[test] +fn transforms_refuse_moving_gradients_without_the_path() { + for transform in + ["translate(5, 10, false, false, true, false)", "rotate(30, false, false, true, false)", "resize(150, 125, false, false, true, false)"] + { + let (mut s, a, b) = doc(); + s.execute( + "paint.setFill", + &json!({"ids": [a.0], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ) + .unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let before = (art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)); + let out = log(&mut s, &format!("try {{ app.activeDocument.pathItems[0].{transform}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); + assert_eq!(out.first(), Some(&json!("Error")), "{transform}: {out:?}"); + assert!( + out[1].as_str().unwrap().contains("Gradients different from") && out[1].as_str().unwrap().contains("not available yet"), + "{transform}: {out:?}" + ); + assert_eq!((art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)), before, "{transform}"); + } +} + #[test] fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { let mut s = Session::new(); @@ -1178,10 +1915,10 @@ fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { assert_eq!(out[3], json!(6)); assert!(failure(&mut s, "app.activeDocument.pathItems[0].rotate(10, true, true, true, true, 'CENTER');").contains("Transformation")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].resize(0, 100);").contains("scaleX")); - assert!(failure(&mut s, "app.activeDocument.pathItems[0].translate(1, 2, 'no');").contains("changePositions")); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].translate(1, 2, 'no');").contains("transformObjects")); let before = art(&s); for (source, part) in [ - ("app.activeDocument.pathItems[0].translate(1, 2, true, true, false);", "changeFillGradients false"), + ("app.activeDocument.pathItems[0].translate(1, 2, true, false, false);", "transformFillGradients different from transformObjects"), ("app.activeDocument.pathItems[0].rotate(10, true, true, true, false);", "must be the same"), ("app.activeDocument.pathItems.ellipse(10, 10, 5, 5, false, true);", "inscribed"), ( @@ -1485,18 +2222,16 @@ fn path_changes_refuse_paths_on_a_locked_artboard() { let (mut s, a, _) = doc(); s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); let (before, steps) = (art(&s), undo_steps(&s)); - // Points (waiting and written at once), paint, stroke and a transform. - for change in [ - "p.closed = false;", - "p.pathPoints[0].anchor = [1, 2];", - "p.setEntirePath([[0, 0], [10, 10]]);", - "p.filled = false;", - "p.strokeWidth = 7;", - "p.translate(5, 5);", - ] { + // Points (waiting and written at once), paint and stroke. + for change in + ["p.closed = false;", "p.pathPoints[0].anchor = [1, 2];", "p.setEntirePath([[0, 0], [10, 10]]);", "p.filled = false;", "p.strokeWidth = 7;"] + { let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}")); assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}"); } + // A transform is PageItem's, which refuses any object on a locked artboard. + let e = failure(&mut s, "app.activeDocument.pathItems[0].translate(5, 5);"); + assert!(e.contains(&format!("cannot transform objects on a locked artboard: {}", a.0)), "{e}"); let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); assert!(e.contains("cannot delete objects on a locked artboard"), "{e}"); assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps)); @@ -1587,3 +2322,25 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() { log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;"); assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command"); } + +/// A point change made before a call that fails and is put back, here a new document whose +/// profile cannot be read, is kept. +#[test] +fn a_point_change_before_a_failed_new_document_is_kept() { + let dir = std::env::temp_dir().join(format!("vc-script-points-new-doc-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + let (mut s, a, _) = doc(); + s.attach_new_doc_profiles(dir.clone()); + let before = node(&s, a).path_data().unwrap().subpaths.clone(); + let out = log( + &mut s, + "app.activeDocument.pathItems[0].pathPoints[0].anchor = [5, 7];\ + try { app.documents.addDocument('Print'); } catch (e) { vc.log('refused'); }", + ); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(out, vec![json!("refused")]); + assert_eq!(s.documents().len(), 1); + assert_ne!(node(&s, a).path_data().unwrap().subpaths, before, "the point change is kept"); +} diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs new file mode 100644 index 0000000000..e8826c13b9 --- /dev/null +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -0,0 +1,729 @@ +//! The script object model: `app.preferences`, the matrix functions of `app` and `app.copy`, +//! `app.cut` and `app.paste`. + +use serde_json::{Value, json}; + +use crate::script::dom::preferences::{MAX_KEYS, MAX_STRING_BYTES, MAX_TOTAL_BYTES, WARNING_OFF_NEEDS_A_PERSON, WARNING_OFF_QUESTION}; +use crate::script::{DialogAnswer, DialogKind, ScriptDialog}; +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 stored(s: &Session, key: &str) -> Option { + s.prefs.script_preferences.get(key).cloned() +} + +#[test] +fn show_external_jsx_warning_is_the_external_script_warning() { + let mut s = Session::new(); + assert!(s.prefs.show_external_script_warning); + let journal = s.journal.len(); + let out = log( + &mut s, + "var p = app.preferences; vc.log(p.typename); vc.log(p.getBooleanPreference('ShowExternalJSXWarning'));\ + vc.log(p.getIntegerPreference('ShowExternalJSXWarning')); p.setBooleanPreference('ShowExternalJSXWarning', true);", + ); + assert_eq!(out, vec![json!("Preferences"), json!(true), json!(1)]); + // A preference is not a command, so the journal has no entry for the run. + assert_eq!(s.journal.len(), journal); + assert!(s.prefs.script_preferences.is_empty()); + assert!(failure(&mut s, "app.preferences.setIntegerPreference('ShowExternalJSXWarning', 1);").contains("setBooleanPreference")); + // Turned off by the person, a script reads it as off and can turn it back on, or remove it. + s.prefs.show_external_script_warning = false; + let out = log( + &mut s, + "var p = app.preferences; p.setBooleanPreference('ShowExternalJSXWarning', false);\ + vc.log(p.getBooleanPreference('ShowExternalJSXWarning')); p.setBooleanPreference('ShowExternalJSXWarning', true);", + ); + assert_eq!(out, vec![json!(false)]); + assert!(s.prefs.show_external_script_warning); + s.prefs.show_external_script_warning = false; + log(&mut s, "app.preferences.removePreference('ShowExternalJSXWarning');"); + assert!(s.prefs.show_external_script_warning); +} + +/// A run with nobody to ask cannot turn the warning off, even with a Yes in `answers`. +#[test] +fn a_run_without_a_person_cannot_turn_the_warning_off() { + let mut s = Session::new(); + let off = "app.preferences.setBooleanPreference('ShowExternalJSXWarning', false);"; + assert!(failure(&mut s, off).contains(WARNING_OFF_NEEDS_A_PERSON)); + assert!(s.prefs.show_external_script_warning); + let r = s.execute("script.run", &json!({"source": off, "name": "t.js", "answers": [{"kind": "confirm", "value": true}]})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains(WARNING_OFF_NEEDS_A_PERSON)), "{r:?}"); + assert!(s.prefs.show_external_script_warning); + let caught = log(&mut s, &format!("try {{ {off} }} catch (e) {{ vc.log(e.message); }}")); + assert_eq!(caught, vec![json!(WARNING_OFF_NEEDS_A_PERSON)]); + assert!(s.prefs.show_external_script_warning); +} + +/// A run in the app, one slice in. +fn framed(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(run(s, source).unwrap()["running"], true); + assert!(s.script_pump().is_none()); +} + +/// Pumps the run in the app until it ends or waits at a dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_dialog().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +const ASK_OFF: &str = "var p = app.preferences; var r = p.setBooleanPreference('ShowExternalJSXWarning', false);\ + vc.log([r === undefined, p.getBooleanPreference('ShowExternalJSXWarning')]);"; + +#[test] +fn yes_to_the_confirm_turns_the_warning_off() { + let mut s = Session::new(); + framed(&mut s, ASK_OFF); + let want = ScriptDialog { + kind: DialogKind::Confirm, + message: WARNING_OFF_QUESTION.into(), + title: None, + error_icon: false, + no_as_default: true, + preset: String::new(), + }; + assert_eq!(s.script_dialog(), Some(want)); + assert!(s.script_dialog_turns_warning_off()); + assert!(s.prefs.show_external_script_warning, "nothing changes while the confirm waits"); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[true, false]])); + assert_eq!(r["dialogs"][0]["answer"], true); + assert!(!s.prefs.show_external_script_warning); +} + +#[test] +fn a_script_confirm_with_the_same_text_is_not_the_warning_question() { + let mut s = Session::new(); + framed(&mut s, &format!("vc.log(confirm({}));", json!(WARNING_OFF_QUESTION))); + assert_eq!(s.script_dialog().map(|d| d.message), Some(WARNING_OFF_QUESTION.to_string())); + assert!(!s.script_dialog_turns_warning_off()); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([true])); +} + +#[test] +fn turning_the_warning_on_after_yes_keeps_it_on() { + let mut s = Session::new(); + framed( + &mut s, + &format!("{ASK_OFF} p.setBooleanPreference('ShowExternalJSXWarning', true); vc.log(p.getBooleanPreference('ShowExternalJSXWarning'));"), + ); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[true, false], true]), "the script sees the answer at once"); + assert!(s.prefs.show_external_script_warning, "the script's last write is what the run keeps"); +} + +#[test] +fn no_to_the_confirm_or_stop_leaves_the_warning_on() { + let mut s = Session::new(); + framed(&mut s, ASK_OFF); + assert!(s.script_answer(DialogAnswer::Confirm(false))); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([[true, true]])); + assert!(s.prefs.show_external_script_warning); + framed(&mut s, ASK_OFF); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert!(!s.script_answer(DialogAnswer::Confirm(true))); + assert!(s.script_pump().unwrap().is_err()); + assert!(s.prefs.show_external_script_warning); + // Yes in a run that then fails is put back with the rest of the run. + framed(&mut s, &format!("{ASK_OFF} throw new Error('stop');")); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + assert!(pump(&mut s).unwrap().is_err()); + assert!(s.prefs.show_external_script_warning); +} + +/// Asking to show no dialogs does not skip the confirm, and a call from a callback, where no dialog +/// can open, throws. +#[test] +fn the_confirm_cannot_be_skipped() { + let mut s = Session::new(); + framed(&mut s, &format!("app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; {ASK_OFF}")); + assert_eq!(s.script_dialog().map(|d| d.message), Some(WARNING_OFF_QUESTION.to_string())); + assert!(s.script_answer(DialogAnswer::Confirm(false))); + assert!(pump(&mut s).unwrap().is_ok()); + assert!(s.prefs.show_external_script_warning); + let callback = "[1].forEach(function () { app.preferences.setBooleanPreference('ShowExternalJSXWarning', false); });"; + assert_eq!(run(&mut s, callback).unwrap()["running"], true); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains(WARNING_OFF_NEEDS_A_PERSON), "{e}"); + assert!(s.prefs.show_external_script_warning); +} + +#[test] +fn other_keys_keep_their_type_across_runs_and_a_restart() { + let mut s = Session::new(); + log( + &mut s, + "var p = app.preferences; p.setBooleanPreference('my/flag', true); p.setIntegerPreference('count', -7);\ + p.setRealPreference('ratio', 0.25); p.setStringPreference('name', 'Ünïcode \\u2713');", + ); + assert_eq!(stored(&s, "my/flag"), Some(ScriptPreference::Boolean(true))); + assert_eq!(stored(&s, "count"), Some(ScriptPreference::Integer(-7))); + assert_eq!(stored(&s, "ratio"), Some(ScriptPreference::Real(0.25))); + assert_eq!(stored(&s, "name"), Some(ScriptPreference::String("Ünïcode \u{2713}".into()))); + // The preferences as the app saves them, read into a new session. + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut t = Session::new(); + t.prefs = serde_json::from_str(&saved).unwrap(); + let out = log( + &mut t, + "var p = app.preferences; vc.log(p.getBooleanPreference('my/flag')); vc.log(p.getIntegerPreference('count'));\ + vc.log(p.getRealPreference('ratio')); vc.log(p.getStringPreference('name'));", + ); + assert_eq!(out, vec![json!(true), json!(-7), json!(0.25), json!("Ünïcode \u{2713}")]); +} + +#[test] +fn missing_keys_read_as_empty_values_and_getters_convert() { + let mut s = Session::new(); + let mut out = log( + &mut s, + "var p = app.preferences; vc.log([p.getBooleanPreference('none'), p.getIntegerPreference('none'),\ + p.getRealPreference('none'), p.getStringPreference('none')]);\ + p.setRealPreference('r', -2.75); p.setStringPreference('t', ' 12.5 '); p.setStringPreference('x', 'abc');\ + p.setBooleanPreference('b', true); p.setIntegerPreference('i', 0);\ + vc.log([p.getIntegerPreference('r'), p.getStringPreference('r'), p.getBooleanPreference('r')]);\ + vc.log([p.getRealPreference('t'), p.getIntegerPreference('t'), p.getBooleanPreference('t')]);\ + vc.log([isNaN(p.getRealPreference('x')), p.getIntegerPreference('x')]);\ + vc.log([p.getStringPreference('b'), p.getRealPreference('b'), p.getBooleanPreference('i'), p.getStringPreference('i')]);\ + var n = []; ['0x10', '0B101', '0o17', '-0x10', '0x', ' -Infinity ', '1e3', '.5', 'inf', '1_0'].forEach(function (t) {\ + p.setStringPreference('n', t); n.push(String(p.getRealPreference('n'))); }); vc.log(n.join(' '));\ + p.setStringPreference('n', '0x200000000000018'); var r = [p.getRealPreference('n') === Math.pow(2, 57) + 32];\ + p.setStringPreference('n', '0x' + new Array(301).join('f')); r.push(String(p.getRealPreference('n')));\ + p.setStringPreference('n', '0b' + new Array(60).join('0') + '1' + new Array(53).join('0') + '1'); r.push(p.getRealPreference('n') === Math.pow(2, 53));\ + vc.log(r);", + ); + // Each whole number in base 16, 8 or 2 is rounded once: 2^57 + 24 to 2^57 + 32, 1,200 bits to + // Infinity, and 2^53 + 1 after leading zeros to 2^53 (ties to even). + assert_eq!(out.pop(), Some(json!([true, "Infinity", true]))); + assert_eq!(out.pop(), Some(json!("16 5 15 NaN NaN -Infinity 1000 0.5 NaN NaN"))); + assert_eq!( + out, + vec![json!([false, 0, 0, ""]), json!([-2, "-2.75", true]), json!([12.5, 12, true]), json!([true, 0]), json!(["true", 1, false, "0"])] + ); +} + +#[test] +fn text_reads_trim_javascript_whitespace_only() { + let mut s = Session::new(); + let out = log( + &mut s, + "var p = app.preferences; var r = [];\ + ['\\u0085' + '42', '\\ufeff 42\\u00a0', '\\u2028' + '42\\u3000'].forEach(function (t) {\ + p.setStringPreference('n', t); r.push(String(p.getRealPreference('n'))); }); vc.log(r.join(' '));", + ); + assert_eq!(out, vec![json!("NaN 42 42")]); +} + +#[test] +fn a_real_preference_changes_between_zero_and_negative_zero() { + let mut s = Session::new(); + log(&mut s, "app.preferences.setRealPreference('z', -0);"); + let out = log( + &mut s, + "var p = app.preferences; vc.log(String(1 / p.getRealPreference('z'))); p.setRealPreference('z', 0); vc.log(String(1 / p.getRealPreference('z')));", + ); + assert_eq!(out, vec![json!("-Infinity"), json!("Infinity")]); + // The change is kept when the run's keys are merged with the app's. + assert_eq!(stored(&s, "z").map(|v| matches!(v, ScriptPreference::Real(r) if r.to_bits() == 0)), Some(true)); +} + +#[test] +fn bad_arguments_throw_and_store_nothing() { + let mut s = Session::new(); + let mut wrong = Vec::new(); + for (source, message) in [ + ("app.preferences.setIntegerPreference('k', 1.5);", "whole number"), + ("app.preferences.setIntegerPreference('k', 1e300);", "whole number"), + ("app.preferences.setIntegerPreference('k', '3');", "whole number"), + ("app.preferences.setRealPreference('k', Infinity);", "finite number"), + ("app.preferences.setRealPreference('k', NaN);", "finite number"), + ("app.preferences.setBooleanPreference('k', 1);", "true or false"), + ("app.preferences.setStringPreference('k', 5);", "a string"), + ("app.preferences.setStringPreference(5, 'v');", "key must be a string"), + ("app.preferences.getBooleanPreference();", "key must be a string"), + ("app.preferences.setStringPreference('', 'v');", "1 to 256"), + ("app.preferences.setStringPreference(new Array(258).join('k'), 'v');", "1 to 256"), + // 129 characters outside the Basic Multilingual Plane are 258 UTF-16 code units. + ("app.preferences.setStringPreference(new Array(130).join('\\uD83D\\uDE00'), 'v');", "1 to 256"), + ("app.preferences.setStringPreference('a\\u0000b', 'v');", "control characters"), + ("app.preferences.setStringPreference('k', new Array(65538).join('v'));", "at most 65536 bytes"), + ("var f = app.preferences.getBooleanPreference; f.call({}, 'k');", "not a Preferences"), + ("Preferences.prototype.setBooleanPreference('k', true);", "not a Preferences"), + ] { + match run(&mut s, source) { + Err(e) if e.to_string().contains(message) => {} + r => wrong.push(format!("{source}: {r:?}")), + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + assert!(s.prefs.script_preferences.is_empty()); + // A key of exactly 256 code units and a value of exactly the limit are taken. + log(&mut s, "app.preferences.setStringPreference(new Array(257).join('k'), new Array(65537).join('v'));"); + assert_eq!(stored(&s, &"k".repeat(256)), Some(ScriptPreference::String("v".repeat(MAX_STRING_BYTES)))); + log(&mut s, "app.preferences.setStringPreference(new Array(129).join('\\uD83D\\uDE00'), 'v');"); + assert_eq!(stored(&s, &"\u{1F600}".repeat(128)), Some(ScriptPreference::String("v".into()))); +} + +#[test] +fn the_store_limits_its_keys() { + let mut s = Session::new(); + for i in 0..MAX_KEYS { + s.prefs.script_preferences.insert(format!("k{i}"), ScriptPreference::Integer(1)); + } + assert!(failure(&mut s, "app.preferences.setIntegerPreference('one more', 1);").contains("at most 4096 keys")); + assert_eq!(s.prefs.script_preferences.len(), MAX_KEYS); + // A key already stored can still change. + log(&mut s, "app.preferences.setIntegerPreference('k0', 2);"); + assert_eq!(stored(&s, "k0"), Some(ScriptPreference::Integer(2))); +} + +#[test] +fn the_store_limits_its_bytes() { + let mut s = Session::new(); + let big = "v".repeat(MAX_STRING_BYTES); + for i in 0..MAX_TOTAL_BYTES / MAX_STRING_BYTES - 1 { + s.prefs.script_preferences.insert(format!("{i:02}"), ScriptPreference::String(big.clone())); + } + let e = failure(&mut s, "app.preferences.setStringPreference('last', new Array(65537).join('v'));"); + assert!(e.contains("at most 1048576 bytes"), "{e}"); + assert_eq!(stored(&s, "last"), None); + // Replacing a stored value counts the new value instead of the old one. + log(&mut s, "app.preferences.setStringPreference('00', new Array(65537).join('w'));"); + assert_eq!(stored(&s, "00"), Some(ScriptPreference::String("w".repeat(MAX_STRING_BYTES)))); +} + +#[test] +fn a_failed_run_puts_the_store_back_and_removing_the_last_key_empties_it() { + let mut s = Session::new(); + log(&mut s, "app.preferences.setIntegerPreference('keep', 1);"); + let e = failure(&mut s, "app.preferences.setIntegerPreference('keep', 2); app.preferences.setRealPreference('new', 1); throw new Error('stop');"); + assert!(e.contains("stop")); + assert_eq!(stored(&s, "keep"), Some(ScriptPreference::Integer(1))); + assert_eq!(stored(&s, "new"), None); + let out = log( + &mut s, + "var p = app.preferences; p.removePreference('missing'); p.removePreference('keep');\ + vc.log(p.getIntegerPreference('keep'));", + ); + assert_eq!(out, vec![json!(0)]); + assert!(s.prefs.script_preferences.is_empty()); +} + +#[test] +fn a_run_merges_its_keys_with_keys_the_app_changed_meanwhile() { + let mut s = Session::new(); + s.prefs.script_preferences.insert("gone".into(), ScriptPreference::Integer(1)); + s.prefs.script_preferences.insert("kept".into(), ScriptPreference::Integer(1)); + s.script_frames = true; + let source = "var p = app.preferences; p.removePreference('gone'); p.setIntegerPreference('mine', 2);\ + for (var i = 0; i < 2000000; i++) {}"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert!(s.script_running()); + s.prefs.script_preferences.insert("theirs".into(), ScriptPreference::Boolean(true)); + s.prefs.script_preferences.insert("kept".into(), ScriptPreference::Integer(3)); + pump(&mut s).unwrap().unwrap(); + let keys: Vec<(&str, &ScriptPreference)> = s.prefs.script_preferences.iter().map(|(k, v)| (k.as_str(), v)).collect(); + assert_eq!( + keys, + vec![("kept", &ScriptPreference::Integer(3)), ("mine", &ScriptPreference::Integer(2)), ("theirs", &ScriptPreference::Boolean(true))] + ); +} + +#[test] +fn matrix_functions_give_new_records() { + let mut s = Session::new(); + let out = log( + &mut s, + "function v(m) { return [m.typename, m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\ + vc.log(v(app.getIdentityMatrix())); vc.log(v(app.getTranslationMatrix(100, 200))); vc.log(v(app.getTranslationMatrix()));\ + vc.log(v(app.getScaleMatrix(60))); vc.log(v(app.getScaleMatrix(50, 200))); vc.log(v(app.getScaleMatrix()));\ + vc.log(v(app.getRotationMatrix(90))); vc.log(v(app.getRotationMatrix(-270))); vc.log(v(app.getRotationMatrix()));", + ); + assert_eq!( + out, + vec![ + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + json!(["Matrix", 1, 0, 0, 1, 100, 200]), + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + json!(["Matrix", 0.6, 0, 0, 0.6, 0, 0]), + json!(["Matrix", 0.5, 0, 0, 2, 0, 0]), + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + json!(["Matrix", 0, 1, -1, 0, 0, 0]), + json!(["Matrix", 0, 1, -1, 0, 0, 0]), + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + ] + ); + let r = log(&mut s, "var m = app.getRotationMatrix(30); vc.log([m.mValueA, m.mValueB, m.mValueC, m.mValueD]);"); + let (c, sn) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + assert_eq!(r, vec![json!([c, sn, -sn, c])]); +} + +#[test] +fn reflect_reports_the_matrix_argument_defaults() { + let mut s = Session::new(); + let out = log( + &mut s, + "function d(f, a) { return String(app.reflect.find(f).arguments[a].defaultValue); }\ + vc.log([d('getScaleMatrix', 'scaleX'), d('concatenateScaleMatrix', 'scaleX'), d('getTranslationMatrix', 'deltaX'),\ + d('concatenateTranslationMatrix', 'deltaY'), d('getRotationMatrix', 'angle'), d('concatenateRotationMatrix', 'angle'),\ + d('getScaleMatrix', 'scaleY'), d('concatenateMatrix', 'matrix')]);\ + vc.log(app.reflect.find('getScaleMatrix').arguments.scaleY.description);", + ); + assert_eq!( + out, + vec![ + json!(["100", "100", "0", "0", "0", "0", "undefined", "undefined"]), + json!("The vertical scale; when it is left out, the horizontal scale."), + ] + ); +} + +#[test] +fn concatenation_applies_the_first_matrix_first() { + let mut s = Session::new(); + // As PDF `cm` operators compose (ISO 32000-1, 8.3.4): [x y 1] × M × N. + // M = [2 0 0 3 5 7] then N = [0 1 -1 0 10 20]: (x, y) → (2x + 5, 3y + 7) → (-(3y + 7) + 10, 2x + 5 + 20). + let out = log( + &mut s, + "function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\ + var m = {mValueA: 2, mValueB: 0, mValueC: 0, mValueD: 3, mValueTX: 5, mValueTY: 7};\ + var n = {mValueA: 0, mValueB: 1, mValueC: -1, mValueD: 0, mValueTX: 10, mValueTY: 20};\ + var c = app.concatenateMatrix(m, n); vc.log(v(c)); vc.log(v(m)); vc.log(c === m);\ + vc.log(v(app.concatenateTranslationMatrix(m, 1, 2))); vc.log(v(app.concatenateScaleMatrix(m, 50)));\ + vc.log(v(app.concatenateRotationMatrix(m, 90)));\ + vc.log(app.isEqualMatrix(app.concatenateRotationMatrix(m, 90), app.concatenateMatrix(m, app.getRotationMatrix(90))));", + ); + assert_eq!( + out, + vec![ + json!([0, 2, -3, 0, 3, 25]), + json!([2, 0, 0, 3, 5, 7]), + json!(false), + json!([2, 0, 0, 3, 6, 9]), + json!([1, 0, 0, 1.5, 2.5, 3.5]), + json!([0, 2, -3, 0, -7, 5]), + json!(true), + ] + ); +} + +#[test] +fn concatenation_rounds_once_at_the_smallest_normal_number_and_the_largest_number() { + let mut s = Session::new(); + // N·(1 - 2^-53) is N - S/2, which rounds up to N; the exact A is -1.5·S, which rounds to -2·S. + // MAX - 2^969 + 2^970 rounds to MAX, while adding the rounded MAX - 2^969 and 2^970 overflows. + // MAX·(1 - 2^-53) + 2^971 + 2^970 - 2^917 is past the overflow midpoint by 2^917, which rounding + // the first product drops. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var n = Math.pow(2, -1022), s = Number.MIN_VALUE;\ + vc.log(app.concatenateMatrix(mat([n, n + s, 0, 1, 0, 0]), mat([1 - Math.pow(2, -53), 0, -1, 1, 0, 0])).mValueA === -2 * s);\ + vc.log(app.concatenateMatrix(mat([n, 0, 0, 1, 0, 0]), mat([1, 0, 0, 1, 0, 0])).mValueA === n);\ + var shift = mat([1, 0, -1, 1, Math.pow(2, 970), 0]);\ + vc.log(app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, Math.pow(2, 969)]), shift).mValueTX === Number.MAX_VALUE);\ + try { app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, 0]), shift); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }\ + var near = mat([1 - Math.pow(2, -53), 0, 1, 1, Math.pow(2, 970) - Math.pow(2, 917), 0]);\ + try { app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, Math.pow(2, 971)]), near); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }", + ); + assert_eq!(out, vec![json!(true), json!(true), json!(true), json!("RangeError"), json!("RangeError")]); +} + +#[test] +fn concatenation_keeps_a_small_translation_that_a_large_one_cancels() { + let mut s = Session::new(); + // 2^53 + 1 rounds to 2^53, so adding the rounded products and then -2^53 gives 0; the exact X is 1. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var big = Math.pow(2, 53);\ + vc.log(app.concatenateMatrix(mat([1, 0, 0, 1, big, 1]), mat([1, 0, 1, 1, -big, 0])).mValueTX);", + ); + assert_eq!(out, vec![json!(1)]); +} + +#[test] +fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_number() { + let mut s = Session::new(); + let out = log( + &mut s, + "function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\ + function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var x = Math.pow(2, 600), y = Math.pow(2, -500), z = Math.pow(2, -575);\ + var c = app.concatenateMatrix(mat([x, x, 0, 1, x, x]), mat([x, 0, -x, 1, 0, 0]));\ + vc.log([c.mValueA, c.mValueB === x, c.mValueC === -x, c.mValueD, c.mValueTX, c.mValueTY === x]);\ + vc.log(app.concatenateMatrix(mat([y, y, 0, 1, 0, 0]), mat([z, 0, z, 1, 0, 0])).mValueA === Number.MIN_VALUE);\ + var p = 2.0543170765449965e-57, q = 6.201533916984909e-252;\ + vc.log(app.concatenateMatrix(mat([p, 0, 0, 1, 0, 0]), mat([q, 0, 0, 1, 0, 0])).mValueA === p * q);\ + vc.log(v(app.concatenateMatrix(mat([-2, 0, 0, -3, 0, 0]), mat([0, 1, -1, 0, 0, 0]))));\ + var big = mat([1, 0, 0, 1, Number.MAX_VALUE, 0]), up = 1 + Math.pow(2, -52);\ + try { app.concatenateMatrix(big, mat([up, 0, 0, 1, -Math.pow(2, 971), 0])); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }\ + vc.log(app.concatenateMatrix(big, mat([up, 0, 0, 1, -Math.pow(2, 972), 0])).mValueTX === Number.MAX_VALUE);\ + var h = Math.pow(2, 500), far = mat([1, 0, 0, 1, Math.pow(2, 600), -Math.pow(2, 600)]);\ + vc.log(app.concatenateMatrix(far, mat([h, 0, h, 1, 1, 0])).mValueTX);\ + var g = Math.pow(2, 100), farther = mat([1, 0, 0, 1, Math.pow(2, 1000), -Math.pow(2, 1000)]);\ + vc.log(app.concatenateMatrix(farther, mat([g, 0, g, 1, Math.pow(2, -100), 0])).mValueTX === Math.pow(2, -100));\ + var tiny = mat([1, 0, 0, 1, y, 0]);\ + vc.log(app.concatenateMatrix(tiny, mat([z, 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === 2 * Number.MIN_VALUE);\ + var least = mat([1, 0, 0, 1, Number.MIN_VALUE, 0]);\ + vc.log(app.concatenateMatrix(least, mat([0.5 - Math.pow(2, -54), 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === Number.MIN_VALUE);\ + vc.log(app.concatenateMatrix(least, mat([0.5 + Math.pow(2, -53), 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === 2 * Number.MIN_VALUE);", + ); + assert_eq!( + out, + vec![ + json!([0, true, true, 1, 0, true]), + json!(true), + json!(true), + json!([0, -2, 3, 0, 0, 0]), + json!("RangeError"), + json!(true), + json!(1), + json!(true), + json!(true), + json!(true), + json!(true) + ] + ); +} + +#[test] +fn a_concatenated_translation_next_to_the_largest_number_is_rounded_once() { + let mut s = Session::new(); + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var a = Math.pow(2, 969), b = Math.pow(2, 970);\ + function tx(f, t) { try { return app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, f]), mat([1, 0, 1, 1, t, 0])).mValueTX === Number.MAX_VALUE; }\ + catch (e) { return e.name; } }\ + vc.log(tx(-a, b)); vc.log(tx(a, a));", + ); + // MAX + 2^969 is below the halfway point to 2^1024, and MAX + 2^970 is that point, which rounds + // to 2^1024. + assert_eq!(out, vec![json!(true), json!("RangeError")]); +} + +#[test] +fn a_turn_just_short_of_a_negative_quarter_turn_is_not_rounded_to_it() { + let mut s = Session::new(); + let out = log( + &mut s, + "function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD]; }\ + var m = app.getRotationMatrix(-89.99999999999999); vc.log(m.mValueA > 0); vc.log(m.mValueB);\ + vc.log(v(app.getRotationMatrix(-90))); vc.log(v(app.getRotationMatrix(-180))); vc.log(v(app.getRotationMatrix(-450)));", + ); + assert_eq!(out, vec![json!(true), json!(-1), json!([0, -1, 1, 0]), json!([-1, 0, 0, -1]), json!([0, -1, 1, 0])]); +} + +#[test] +fn an_inverse_translation_next_to_the_overflow_midpoint_rounds_once() { + let mut s = Session::new(); + // The x-translation's numerator is MAX + 2^970, the overflow midpoint. With b = 2^-53 the + // determinant is 1 + 2^-53, so the exact quotient is MAX - 2^970 + about 2^917, which rounds + // to MAX, while the rounded determinant 1 gives infinity. With b = 0 the quotient is the + // midpoint itself, which rounds to infinity. With a = 1 + 2^-51 and the numerator + // 2^1024 + 3·2^971, the rounded quotient overflows while the exact one is MAX - 2^971 and a + // little more, which rounds to the number below MAX. With b = -2^-54 and ty = -2^969 the rounded + // quotient is MAX, while the exact one is past the overflow midpoint. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var i = app.invertMatrix(mat([1, Math.pow(2, -53), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)]));\ + vc.log(i.mValueTX === Number.MAX_VALUE);\ + try { app.invertMatrix(mat([1, 0, -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)])); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }\ + var j = app.invertMatrix(mat([1 + Math.pow(2, -51), Math.pow(2, -53), -1, 1, -Math.pow(2, 1023), -(Math.pow(2, 1023) + 3 * Math.pow(2, 971))]));\ + vc.log(j.mValueTX === Number.MAX_VALUE - Math.pow(2, 971));\ + try { app.invertMatrix(mat([1, -Math.pow(2, -54), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 969)])); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }", + ); + assert_eq!(out, vec![json!(true), json!("RangeError"), json!(true), json!("RangeError")]); +} + +#[test] +fn an_inverse_translation_next_to_half_the_smallest_number_rounds_once() { + let mut s = Session::new(); + // The x-translation's numerator is 2^-1021 + 2^-1075 and the determinant 2^54, so the exact + // quotient is 2^-1075 + 2^-1129, just past half the smallest number, which rounds to it. The + // rounded numerator 2^-1021 gives 2^-1075, which rounds to 0. With c = 0 the quotient is 2^-1075 + // itself, which rounds to 0. With both translations negated, the x-translation rounds to minus + // the smallest number. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var t = Math.pow(2, -1021), big = Math.pow(2, 54), small = Math.pow(2, -54);\ + var i = app.invertMatrix(mat([big, 0, small, 1, -t, t]));\ + vc.log([i.mValueTX === Number.MIN_VALUE, i.mValueTY === -t]);\ + var j = app.invertMatrix(mat([big, 0, 0, 1, -t, t]));\ + vc.log([j.mValueTX, 1 / j.mValueTX > 0]);\ + var k = app.invertMatrix(mat([big, 0, small, 1, t, -t]));\ + vc.log([k.mValueTX === -Number.MIN_VALUE, k.mValueTY === t]);", + ); + assert_eq!(out, vec![json!([true, true]), json!([0, true]), json!([true, true])]); +} + +#[test] +fn inverse_singular_and_equal_matrices() { + let mut s = Session::new(); + let out = log( + &mut s, + "var m = app.concatenateTranslationMatrix(app.concatenateRotationMatrix(app.getScaleMatrix(40, 250), 33), 17, -4);\ + var i = app.invertMatrix(m), back = app.concatenateMatrix(m, i), id = app.getIdentityMatrix();\ + var d = [back.mValueA - 1, back.mValueB, back.mValueC, back.mValueD - 1, back.mValueTX, back.mValueTY];\ + vc.log(Math.max.apply(null, d.map(Math.abs)) < 1e-12);\ + vc.log(app.isSingularMatrix(app.getScaleMatrix(0, 100))); vc.log(app.isSingularMatrix(m));\ + vc.log(app.isEqualMatrix(id, app.getRotationMatrix(360))); vc.log(app.isEqualMatrix(id, app.getTranslationMatrix(0, 1e-300)));\ + var tiny = app.getScaleMatrix(1e-198, 1e202), t = app.invertMatrix(tiny);\ + function near(v, w) { return Math.abs(v / w - 1) < 1e-12; }\ + vc.log([app.isSingularMatrix(tiny), near(t.mValueA, 1e200), near(t.mValueD, 1e-200), t.mValueB, t.mValueC]);\ + vc.log(near(app.invertMatrix(app.getScaleMatrix(1e202)).mValueA, 1e-200));\ + function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: 0, mValueTY: 0}; }\ + var wide = mat([1e308, 0, 1e308, 1e-100]), w = app.invertMatrix(wide);\ + vc.log([app.isSingularMatrix(wide), near(w.mValueA, 1e-308), near(w.mValueC, -1e100), near(w.mValueD, 1e100)]);\ + var thin = app.invertMatrix(mat([1e300, 0, 1e300, 5e-24]));\ + vc.log([near(thin.mValueA, 1e-300), near(thin.mValueC, -2e23), near(thin.mValueD, 2e23)]);\ + var close = mat([7207, 7440, 382, 394.34993756070486]), ci = app.invertMatrix(close);\ + vc.log([app.isSingularMatrix(close), app.isSingularMatrix(mat([6, 4, 3, 2])), near(ci.mValueD, 7207 / -8.009237717487849e-11)]);\ + var far = mat([1e-100, 1e-100, 1e-100, 1e-100 + 1e-115]); far.mValueTX = 1e200; far.mValueTY = 1e200;\ + var fi = app.invertMatrix(far); vc.log([Math.abs(fi.mValueTX / -1e300 - 1) < 1e-6, fi.mValueTY]);", + ); + assert_eq!(out[..5], [json!(true), json!(true), json!(false), json!(true), json!(false)]); + assert_eq!(out[5], json!([false, true, true, 0, 0])); + assert_eq!(out[6], json!(true)); + assert_eq!(out[7], json!([false, true, true, true])); + assert_eq!(out[8], json!([true, true, true])); + assert_eq!(out[9], json!([false, true, true])); + assert_eq!(out[10], json!([true, 0])); + let mut wrong = Vec::new(); + for (source, message) in [ + ("app.invertMatrix(app.getScaleMatrix(100, 0));", "singular"), + ("app.getTranslationMatrix(NaN);", "not a finite number"), + ("app.getScaleMatrix('50');", "scaleX must be a finite number"), + ("app.getRotationMatrix(Infinity);", "not a finite number"), + ("app.getRotationMatrix(null);", "angle must be a finite number"), + ("app.concatenateMatrix(app.getIdentityMatrix(), {mValueA: 1});", "secondMatrix must be a Matrix"), + ( + "app.concatenateMatrix(app.getIdentityMatrix(), {mValueA: 1, mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: '0', mValueTY: 0});", + "secondMatrix must be a Matrix", + ), + ("app.invertMatrix(5);", "matrix must be a Matrix"), + ("var m = app.getIdentityMatrix(); m.mValueTX = Infinity; app.isSingularMatrix(m);", "not a finite number"), + ("app.concatenateScaleMatrix(app.getScaleMatrix(1e300), 1e300);", "too large"), + ] { + match run(&mut s, source) { + Err(e) if e.to_string().contains(message) => {} + r => wrong.push(format!("{source}: {r:?}")), + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +#[test] +fn copy_and_paste_run_as_one_undo_step() { + let mut s = Session::new(); + assert!(failure(&mut s, "app.paste();").contains("No active document")); + log(&mut s, "app.copy(); app.cut();"); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let steps = s.active().unwrap().history.undo.len(); + // Nothing selected and the clipboard empty: nothing happens and no step is added. + log(&mut s, "app.copy(); app.cut(); app.paste();"); + assert_eq!(s.active().unwrap().history.undo.len(), steps); + assert!(s.clipboard.is_empty()); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let steps = s.active().unwrap().history.undo.len(); + let out = log(&mut s, "app.copy(); app.paste(); app.paste(); vc.log(app.activeDocument.pageItems.length);"); + assert_eq!(out, vec![json!(3)]); + assert_eq!(s.active().unwrap().history.undo.len(), steps + 1); + // A cut in a run that fails is put back. + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let steps = s.active().unwrap().history.undo.len(); + assert!(failure(&mut s, "app.cut(); throw new Error('stop');").contains("stop")); + assert!(s.active().unwrap().doc.node(NodeId(a)).is_some()); + assert_eq!(s.active().unwrap().history.undo.len(), steps); + log(&mut s, "app.cut();"); + assert!(s.active().unwrap().doc.node(NodeId(a)).is_none()); +} + +#[test] +fn only_copies_that_fill_the_clipboard_and_are_kept_are_counted() { + let mut s = Session::new(); + s.clipboard_copied = true; + s.note_copy(); + assert_eq!(s.copies, 0); + assert!(!s.clipboard_copied); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + assert_eq!(s.copies, 1); + assert!(s.clipboard_copied); + // A batch that copies and then fails puts the count back with the clipboard. + s.execute("clipboard.importSvg", &json!({"svg": ""})).unwrap(); + assert!(!s.clipboard_copied); + let batch = json!({"commands": [{"command": "edit.copy", "params": {}}, {"command": "no.such", "params": {}}]}); + assert!(s.execute("command.batch", &batch).is_err()); + assert_eq!(s.copies, 1); + assert!(!s.clipboard_copied); +} + +#[test] +fn a_copy_or_cut_the_run_puts_back_is_not_reported() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + // The clipboard holds a copy from before the run. + s.execute("edit.copy", &json!({})).unwrap(); + let copies = s.copies; + // No command result reaches the script, so each command below is put back. + crate::script::TEST_RESULT_BYTES.with(|b| b.set(Some(1))); + let r = run( + &mut s, + "try { vc.run('command.batch', {commands: [{command: 'edit.copy', params: {}}]}); } catch (e) { vc.log(e.name); }\ + try { vc.run('edit.cut'); } catch (e) { vc.log(e.name); }\ + try { vc.run('edit.copy'); } catch (e) { vc.log(e.name); }\ + try { vc.run('artboard.copy', {indices: [0]}); } catch (e) { vc.log(e.name); }\ + try { vc.run('clipboard.importSvg', {svg: ''}); }\ + catch (e) { vc.log(e.name); }", + ); + crate::script::TEST_RESULT_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", "RangeError", "RangeError"]), "{r}"); + assert_eq!(r.get("copied"), None, "{r}"); + assert_eq!(s.copies, copies); + assert!(s.clipboard_copied); + assert!(s.active().unwrap().doc.node(NodeId(a)).is_some()); +} diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs new file mode 100644 index 0000000000..ede881af0d --- /dev/null +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -0,0 +1,1467 @@ +//! Tracing in the script object model: `trace()` on placed and raster items, the `PluginItem`, its +//! `TracingObject` and its `TracingOptions`, and the checks on what a script gives them. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +/// A fresh folder for test `name`, with a `main` folder for the script, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-dom-tracing-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// A 60 × 60 PNG of a black disc on white. +fn disc_png() -> Vec { + vectorcraft_trace::Raster::from_fn(60, 60, |x, y| { + let (dx, dy) = (f64::from(x) + 0.5 - 30.0, f64::from(y) + 0.5 - 30.0); + if dx * dx + dy * dy <= 400.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] } + }) + .encode_png() +} + +/// A session with one 400 × 300 pt document holding the disc image, linked (`link`) or embedded. +fn session(base: &Path, link: bool) -> (Session, NodeId) { + let png = base.join("main/disc.png"); + std::fs::write(&png, disc_png()).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": link})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + (s, id) +} + +/// Runs `text` as `main/main.jsx` in `base`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn log(s: &mut Session, base: &Path, text: &str) -> Vec { + let r = run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The Image Trace objects of the active document. +fn traces(s: &Session) -> Vec { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| { + if crate::cmd::is_trace_group(n) { + out.push(n.id); + } + }); + out +} + +/// The `trace` settings of the Image Trace object `id`. +fn trace_of(s: &Session, id: NodeId) -> Value { + s.active().unwrap().doc.node(id).and_then(|n| n.extras().trace.as_deref().cloned()).unwrap_or(Value::Null) +} + +/// Every top-level object of the active document's first layer. +fn top(s: &Session) -> Vec { + let d = &s.active().unwrap().doc; + d.children(Some(d.layers[0].id)).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default() +} + +/// Traces with the Default preset as a script does, which the script's counts should match: its +/// `paths` and `anchors`, and the different paints of the result. +fn command_counts(base: &Path, link: bool) -> (u64, u64, u64) { + let (mut s, id) = session(base, link); + let r = s.execute("imageTrace.make", &json!({"id": id.0})).unwrap(); + (r["paths"].as_u64().unwrap(), r["anchors"].as_u64().unwrap(), r["colors"].as_u64().unwrap()) +} + +#[test] +fn raster_trace_returns_plugin_with_counts() { + let base = folder("raster"); + let (mut s, image) = session(&base, false); + let ppi = s.execute("image.info", &json!({"id": image.0})).unwrap()["ppi"][0].clone(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, r = d.rasterItems[0]; r.name = 'src'; var p = r.trace(), t = p.tracing;\ + vc.log(p.typename); vc.log(p.isTracing); vc.log(t.typename); vc.log(t.sourceArt.name); vc.log(r.typename);\ + vc.log(t.pathCount); vc.log(t.anchorCount); vc.log(t.usedColorCount); vc.log(t.imageResolution);\ + vc.log(p.tracing.pathCount === t.pathCount); vc.log(t.parent.isTracing); vc.log(t.tracingOptions.typename);\ + vc.log(t.tracingOptions.parent.typename); vc.log(d.pageItems[0].typename); vc.log(t.tracingOptions.preset);", + ); + assert_eq!(out[..5], [json!("PluginItem"), json!(true), json!("TracingObject"), json!("src"), json!("RasterItem")]); + let (paths, anchors, colors) = command_counts(&base, false); + assert!(paths > 0 && anchors > 0, "{paths} {anchors}"); + assert_eq!(out[5], json!(paths)); + assert_eq!(out[6], json!(anchors)); + let used = out[7].as_u64().unwrap(); + assert!(used >= 1 && used <= colors, "{used} of {colors}"); + assert_eq!(out[8].as_f64(), ppi.as_f64()); + assert_eq!(out[9..], [json!(true), json!(true), json!("TracingOptions"), json!("TracingObject"), json!("PluginItem"), json!("Default")]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_eq!(top(&s), groups); + assert_eq!(undo_steps(&s), 2, "the place and the run"); + let _ = std::fs::remove_dir_all(base); +} + +/// A group moved into a tracing above its paths counts even when its name and contents look like +/// seam fills: only the tracing's lowest item can be its seam fills. +#[test] +fn added_group_named_as_seam_fills_is_counted() { + let base = folder("seam-name"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(), t = p.tracing, n = t.pathCount, a = t.anchorCount;\ + var r = d.pathItems.rectangle(0, 0, 10, 10); r.filled = true; r.stroked = false; d.selection = [r]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Seam Fills'; vc.log(g.typename); g.move(p, ElementPlacement.PLACEATBEGINNING); vc.log(p.tracing.pathCount - n); vc.log(p.tracing.anchorCount - a);\ + var q = d.pathItems.rectangle(0, 0, 10, 10); q.move(p, ElementPlacement.PLACEATEND); vc.log(p.tracing.pathCount - n); vc.log(p.tracing.anchorCount - a);", + ); + assert_eq!(out, [json!("GroupItem"), json!(1), json!(4), json!(2), json!(8)]); + let d = &s.active().unwrap().doc; + let kids = d.children(Some(traces(&s)[0])).unwrap(); + assert!( + kids.iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. }) && crate::cmd::is_seam_fills(n)), + "the trace keeps its own seam fills, below the path placed at the end" + ); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_image_resolution_is_one_number_or_none() { + let base = folder("resolution"); + let (mut s, image) = session(&base, false); + let ppi = s.execute("image.info", &json!({"id": image.0})).unwrap()["ppi"][0].as_f64().unwrap(); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.width = r.width * 2; r.height = r.height * 2;\ + var t = r.trace().tracing; vc.log(t.imageResolution); t.releaseTracing(); r.width = r.width * 2;\ + var m = ''; try { r.trace().tracing.imageResolution; } catch (e) { m = e.message; } vc.log(m);", + ); + assert!((out[0].as_f64().unwrap() - ppi / 2.0).abs() < 1e-9, "{out:?}"); + assert_eq!(out[1], json!("the source image has no single resolution")); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn placed_trace_returns_plugin_with_source_art() { + let base = folder("placed"); + let (mut s, image) = session(&base, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, pl = d.placedItems[0]; pl.name = 'src'; var p = pl.trace();\ + vc.log(p.typename); vc.log(p.tracing.sourceArt.name); vc.log(pl.typename); vc.log(pl.file.name);\ + var m = ''; try { pl.trace(); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!("PluginItem"), json!("src"), json!("PlacedItem"), json!("disc.png"), json!("The image is the source art of a tracing")]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(image), Some(groups[0]), "the image is the tracing's source"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_checks_the_image_first() { + let base = folder("unbound"); + let (mut s, image) = session(&base, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], n = d.placedItems.add(), m = [];\ + try { n.trace(); } catch (e) { m.push(e.message); } p.embed(); try { p.trace(); } catch (e) { m.push(e.message); }\ + try { PlacedItem.prototype.trace.call(d.rasterItems[0]); } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out, [json!(["PlacedItem.file is required", "Stale page item", "this is not a PlacedItem"])]); + assert!(traces(&s).is_empty()); + assert!(s.active().unwrap().doc.node(image).is_some()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_missing_link_refuses_preview() { + let base = folder("missing"); + let (mut s, image) = session(&base, true); + std::fs::remove_file(base.join("main/disc.png")).unwrap(); + let out = log(&mut s, &base, "var m = ''; try { app.activeDocument.placedItems[0].trace(); } catch (e) { m = e.message; } vc.log(m);"); + assert_eq!(out, [json!("Linked image is missing")]); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + assert_eq!(undo_steps(&s), 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_release_restores_source_kind() { + let base = folder("release"); + let (mut s, image) = session(&base, false); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.name = 'src';\ + var p = r.trace(), t = p.tracing, o = t.tracingOptions, back = t.releaseTracing();\ + vc.log(back.name); vc.log(back.typename); vc.log(r.hidden);\ + var m = []; try { p.name; } catch (e) { m.push(e.message); } try { t.pathCount; } catch (e) { m.push(e.message); }\ + try { o.threshold; } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out[..3], [json!("src"), json!("RasterItem"), json!(false)]); + assert_eq!(out[3], json!(["Stale page item", "Stale page item", "Stale page item"])); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_expand_returns_group_and_stales_plugin() { + let base = folder("expand"); + let (mut s, image) = session(&base, false); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0], p = r.trace(), t = p.tracing, m = [];\ + try { t.expandTracing(true); } catch (e) { m.push(e.message); }\ + try { t.expandTracing('yes'); } catch (e) { m.push(e.name); }\ + vc.log(m); vc.log(p.isTracing);\ + var g = t.expandTracing(); vc.log(g.typename); vc.log(p === g); m = [];\ + try { p.isTracing; } catch (e) { m.push(e.message); } try { t.anchorCount; } catch (e) { m.push(e.message); }\ + try { r.name; } catch (e) { m.push(e.message); } vc.log(m); vc.log(app.activeDocument.pageItems[0] === g);", + ); + assert_eq!(out[0], json!(["TracingObject.expandTracing(true) is not implemented", "TypeError"])); + assert_eq!(out[1..4], [json!(true), json!("GroupItem"), json!(false)], "the group is a new object"); + assert_eq!(out[4], json!(["Stale page item", "Stale page item", "Stale page item"])); + assert_eq!(out[5], json!(true), "the group read again is the object expandTracing gave"); + assert!(traces(&s).is_empty()); + let d = &s.active().unwrap().doc; + assert!(d.node(image).is_none(), "the expanded group keeps no source image"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn expand_keeps_images_moved_and_duplicated_into_the_tracing() { + let base = folder("expand-other-images"); + let (mut s, source) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0]; r.name = 'other';\ + r.duplicate(p, ElementPlacement.PLACEATEND); r.move(p, ElementPlacement.PLACEATBEGINNING);\ + var g = p.tracing.expandTracing(); vc.log(g.typename); vc.log(d.rasterItems.length); vc.log(r.name);", + ); + assert_eq!(out, [json!("GroupItem"), json!(2), json!("other")]); + let d = &s.active().unwrap().doc; + assert!(d.node(source).is_none()); + let group = top(&s)[0]; + let images: Vec<_> = d.children(Some(group)).unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Image(_))).collect(); + assert_eq!(images.len(), 2); + assert!(images.iter().all(|n| n.name.as_deref() == Some("other"))); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn tracing_replacements_refuse_protected_artwork() { + let base = folder("protected-replacements"); + for operation in ["trace", "retrace", "expand", "release", "view"] { + for protection in ["locked", "hidden", "locked-layer", "hidden-layer", "locked-artboard"] { + let (mut s, image) = session(&base, false); + let (target, action) = if operation == "trace" { + (image, "item.trace();") + } else { + let r = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + let action = match operation { + "retrace" => "item.tracing.tracingOptions.threshold = 90;", + "expand" => "item.tracing.expandTracing();", + "view" => "item.tracing.tracingOptions.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES;", + _ => "item.tracing.releaseTracing();", + }; + (NodeId(r["id"].as_u64().unwrap()), action) + }; + s.edit("Protect artwork", |d, _| { + if protection == "locked-artboard" { + d.artboards[0].locked = true; + } else { + let protected = if protection.ends_with("-layer") { d.layers[0].id } else { target }; + let node = d.node_mut(protected).unwrap(); + node.locked = protection.starts_with("locked"); + node.visible = !protection.starts_with("hidden"); + } + Ok(()) + }) + .unwrap(); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let selection = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!("var item = app.activeDocument.pageItems[0], m = ''; try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);"), + ); + assert_eq!(out, [json!(format!("Cannot edit page item {}", target.0))], "{operation}: {protection}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{operation}: {protection}"); + assert_eq!(s.active().unwrap().selection, selection); + assert_eq!(undo_steps(&s), steps); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retrace_refuses_added_artwork_before_changing_the_document() { + let base = folder("retrace-added-artwork"); + for artwork in [ + "r.move(p, ElementPlacement.PLACEATEND);", + "r.duplicate(p, ElementPlacement.PLACEATEND);", + "d.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);", + ] { + for action in ["o.threshold = 90;", "o.loadFromPreset('Silhouettes');"] { + let (mut s, _) = session(&base, false); + s.execute("file.place", &json!({"path": base.join("main/disc.png").to_string_lossy(), "link": false})).unwrap(); + let setup = format!("var d = app.activeDocument, r = d.rasterItems[0], p = d.rasterItems[1].trace(); {artwork}"); + let mut expected = Session::new(); + expected.docs = s.docs.clone(); + expected.active = s.active; + log(&mut expected, &base, &setup); + let before = vectorcraft_format::save(&expected.active().unwrap().doc, false); + let selection = expected.active().unwrap().selection.clone(); + let steps = undo_steps(&expected); + let out = log( + &mut s, + &base, + &format!( + "{setup} var items = app.activeDocument.pageItems;\ + for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') p = items[i];\ + var o = p.tracing.tracingOptions, m = '';\ + try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);" + ), + ); + assert_eq!(out, [json!("Cannot retrace a tracing containing added artwork")], "{artwork} {action}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(s.active().unwrap().selection, selection); + assert_eq!(undo_steps(&s), steps); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn copied_traces_remap_child_records_without_accepting_added_artwork() { + let base = folder("retrace-copied-artwork"); + for (added, retraced) in [(false, false), (true, false), (false, true), (true, true)] { + let (mut s, _) = session(&base, false); + let retrace = if retraced { "o.threshold = 100;" } else { "" }; + let artwork = if added { "d.pathItems.rectangle(20, 20, 10, 10).move(copy, ElementPlacement.PLACEATEND);" } else { "" }; + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.rasterItems[0].trace(), copy = p.duplicate(), o = copy.tracing.tracingOptions;\ + {retrace} {artwork}\ + var m = ''; try {{ o.threshold = 90; }} catch (e) {{ m = e.message; }}\ + vc.log(m); vc.log(copy.isTracing); vc.log(o.threshold);" + ), + ); + let message = if added { "Cannot retrace a tracing containing added artwork" } else { "" }; + assert_eq!(out[..2], [json!(message), json!(true)], "added: {added}, retraced: {retraced}"); + if !added { + assert_eq!(out[2], json!(90)); + } + } + let _ = std::fs::remove_dir_all(base); +} + +/// The objects in the object `id` of the active document, without it, in order. +fn members(s: &Session, id: NodeId) -> Vec { + let mut out = vec![]; + if let Some(n) = s.active().unwrap().doc.node(id) { + n.walk(&mut |m| { + if m.id != id { + out.push(m.id); + } + }); + } + out +} + +/// A new session with the active document of `s`, saved and opened again. +fn reopened(s: &Session) -> Session { + let bytes = vectorcraft_format::save(&s.active().unwrap().doc, false); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "traced.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap(); + o +} + +/// Traces the Image Trace object `index` of the active document's page items again with a +/// threshold of 90, and logs the error, or `""`. +fn retrace_item(index: usize) -> String { + format!( + "(function () {{ var items = app.activeDocument.pageItems, found = [];\ + for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') found.push(items[i]);\ + var o = found[{index}].tracing.tracingOptions, m = '';\ + try {{ o.threshold = 90; }} catch (e) {{ m = e.message; }} vc.log(m); }})();" + ) +} + +const ADDED_ARTWORK: &str = "Cannot retrace a tracing containing added artwork"; + +#[test] +fn retrace_refuses_artwork_added_before_the_run() { + let base = folder("retrace-earlier-artwork"); + for by_command in [false, true] { + for reopen in [false, true] { + let (mut s, image) = session(&base, false); + let trace = if by_command { + s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + "var p = app.activeDocument.pageItems[0];" + } else { + "var p = app.activeDocument.rasterItems[0].trace();" + }; + log(&mut s, &base, &format!("{trace} app.activeDocument.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);")); + let mut s = if reopen { reopened(&s) } else { s }; + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log(&mut s, &base, &retrace_item(0)); + assert_eq!(out, [json!(ADDED_ARTWORK)], "by command: {by_command}, reopened: {reopen}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "by command: {by_command}, reopened: {reopen}"); + assert_eq!(undo_steps(&s), steps); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retrace_takes_a_tracing_whose_traced_objects_were_edited() { + let base = folder("retrace-edited-artwork"); + for reopen in [false, true] { + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let made = s.active().unwrap().doc.node(group).and_then(|g| g.trace_made()).expect("the trace records what it made"); + let held = members(&s, group); + assert!(held.len() > 1 && held.iter().all(|m| made.contains(*m)), "{held:?} {made:?}"); + assert!(!made.contains(group)); + let path = held[held.len() - 1]; + s.execute("object.move", &json!({"ids": [path.0], "dx": 5, "dy": 0})).unwrap(); + let mut s = if reopen { reopened(&s) } else { s }; + let out = log(&mut s, &base, &format!("{} vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.threshold);", retrace_item(0))); + assert_eq!(out, [json!(""), json!(90)], "reopened: {reopen}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_copied_tracing_retraces_in_a_later_run() { + let base = folder("retrace-copy-later"); + for added in [false, true] { + for reopen in [false, true] { + let (mut s, _) = session(&base, false); + let artwork = if added { "app.activeDocument.pathItems.rectangle(20, 20, 10, 10).move(copy, ElementPlacement.PLACEATEND);" } else { "" }; + log(&mut s, &base, &format!("var p = app.activeDocument.rasterItems[0].trace(), copy = p.duplicate(); {artwork}")); + let groups = traces(&s); + assert_eq!(groups.len(), 2); + let records: Vec<_> = groups.iter().map(|g| s.active().unwrap().doc.node(*g).and_then(|n| n.trace_made()).unwrap()).collect(); + for (k, g) in groups.iter().enumerate() { + assert!(members(&s, *g).iter().all(|m| !records[1 - k].contains(*m)), "a tracing records none of the other's objects"); + } + let mut s = if reopen { reopened(&s) } else { s }; + let out = log(&mut s, &base, &format!("{} {}", retrace_item(0), retrace_item(1))); + let message = if added { ADDED_ARTWORK } else { "" }; + assert_eq!(out, [json!(message), json!("")], "added: {added}, reopened: {reopen}"); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_tracing_saved_without_its_record_is_checked_only_within_a_run() { + let base = folder("retrace-legacy"); + for same_run in [false, true] { + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + let add = "var r = app.activeDocument.pathItems.rectangle(20, 20, 10, 10); r.name = 'added'; r.move(app.activeDocument.pageItems[1], ElementPlacement.PLACEATEND);"; + let out = if same_run { + log(&mut s, &base, &format!("{add} {}", retrace_item(0))) + } else { + log(&mut s, &base, add); + log(&mut s, &base, &retrace_item(0)) + }; + let message = if same_run { ADDED_ARTWORK } else { "" }; + assert_eq!(out, [json!(message)], "same run: {same_run}"); + let mut named = false; + s.active().unwrap().doc.walk(|n| named |= n.name.as_deref() == Some("added")); + assert_eq!(named, same_run, "tracing again drops what was added, as before"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_tracing_saved_without_its_record_counts_artwork_added_through_its_paths() { + let base = folder("retrace-legacy-paths"); + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + let held = members(&s, group); + // The script reaches the tracing's paths before the tracing itself. + let add = "var d = app.activeDocument, p = d.pathItems[0], r = d.pathItems.rectangle(20, 20, 10, 10);\ + r.name = 'added'; r.move(p, ElementPlacement.PLACEBEFORE);"; + let out = log(&mut s, &base, &format!("{add} {}", retrace_item(0))); + assert_eq!(out, [json!(ADDED_ARTWORK)]); + assert_eq!(members(&s, group).len(), held.len() + 1, "the added path stays in the tracing"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_tracing_saved_without_its_record_is_checked_again_after_a_revert() { + let base = folder("retrace-legacy-revert"); + let path = base.join("main/legacy.vectorcraft"); + for seen_first in [false, true] { + for added in [false, true] { + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + s.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap(); + let held = members(&s, group); + s.execute("edit.clear", &json!({"ids": [held[held.len() - 1].0]})).unwrap(); + let seen = if seen_first { "var p = app.activeDocument.pageItems[0];" } else { "app.activeDocument.pathItems[0].name = 'x';" }; + let add = if added { + format!( + "var d = app.activeDocument, r = d.pathItems.rectangle(20, 20, 10, 10);\ + r.move(d.pageItems[1], ElementPlacement.PLACEATEND); vc.run('file.saveAs', {{path: {}}}); r.name = 'after';", + json!(path.to_string_lossy()) + ) + } else { + String::new() + }; + let out = log(&mut s, &base, &format!("{seen} {add} vc.run('file.revert'); {}", retrace_item(0))); + // A revert keeps the snapshot taken before it. + let message = if added || seen_first { ADDED_ARTWORK } else { "" }; + assert_eq!(out, [json!(message)], "seen first: {seen_first}, added: {added}"); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn engine_trace_can_be_retraced_by_a_script() { + let base = folder("retrace-engine-artwork"); + let (mut s, image) = session(&base, false); + let made = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + let group = NodeId(made["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.pageItems[0], o = p.tracing.tracingOptions;\ + o.threshold = 90; vc.log(o.threshold); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!(90), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_ne!(groups[0], group); + assert_eq!(trace_of(&s, groups[0])["params"]["threshold"], json!(90)); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(groups[0])); + assert_eq!(undo_steps(&s), steps + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retrace_limit_counts_retraces_of_an_undone_group() { + let base = folder("retrace-limit-undo"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions, count = 0, m = '';\ + try { for (; count < 10001; count++) { o.threshold = 90; app.undo(); } } catch (e) { m = e.message; }\ + vc.log(count); vc.log(m); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!(10000), json!("a run traces a tracing again at most 10000 times"), json!(true)]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_and_option_changes_log_command_warnings() { + let base = folder("trace-warnings"); + let (mut s, _) = session(&base, false); + let png = base.join("main/wide.png"); + std::fs::write(&png, vectorcraft_trace::Raster::from_fn(1501, 2, |_, _| [0, 0, 0, 255]).encode_png()).unwrap(); + let placed = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let image = placed["ids"][0].as_u64().unwrap(); + let made = s.execute("imageTrace.make", &json!({"id": image})).unwrap(); + let warnings = made["warnings"].as_array().unwrap().clone(); + assert!(!warnings.is_empty()); + s.execute("imageTrace.release", &json!({"id": made["id"]})).unwrap(); + let report = run(&mut s, &base, "var p = app.activeDocument.rasterItems[0].trace(); p.tracing.tracingOptions.threshold = 90;").unwrap(); + let lines = report["console"]["lines"].as_array().unwrap(); + let expected: Vec<_> = warnings.iter().map(|w| json!(format!("imageTrace.make: {}", w.as_str().unwrap()))).collect(); + assert_eq!(lines, &expected.iter().chain(&expected).cloned().collect::>()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn option_changes_log_why_no_paths_were_traced() { + let base = folder("trace-no-paths-warning"); + let (mut s, image) = session(&base, false); + let made = s.execute("imageTrace.make", &json!({"id": image.0, "params": {"keepColors": ["#ff00ff"]}})).unwrap(); + assert_eq!(made["paths"], json!(0)); + let warnings = made["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("Nothing was traced"))); + let report = run(&mut s, &base, "app.activeDocument.pageItems[0].tracing.tracingOptions.threshold = 90;").unwrap(); + let expected: Vec<_> = warnings.iter().map(|w| json!(format!("imageTrace.make: {}", w.as_str().unwrap()))).collect(); + assert_eq!(report["console"]["lines"], json!(expected)); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn tracing_parent_keeps_plugin_identity_after_retracing() { + let base = folder("parent-identity"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing;\ + vc.log(t.parent === p); t.tracingOptions.threshold = 90; vc.log(t.parent === p);\ + vc.log(p.tracing.parent === p); t.tracingOptions.threshold = 100; vc.log(t.parent === p);", + ); + assert_eq!(out, vec![json!(true); 4]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn plugin_is_tracing_refuses_a_replaced_source_without_reading_tracing() { + let base = folder("plugin-replaced-source"); + let (mut s, source) = session(&base, false); + s.execute("file.place", &json!({"path": base.join("main/disc.png").to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0];\ + r.move(p, ElementPlacement.PLACEATEND); vc.run('edit.clear', {{ids: [{}]}}); var m = [];\ + try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }}\ + try {{ p.tracing; }} catch (e) {{ m.push(e.message); }} vc.log(m);", + source.0 + ), + ); + assert_eq!(out, [json!(["Stale page item", "Stale page item"])]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn tracing_handle_is_stale_when_another_image_replaces_its_source() { + let base = folder("replaced-source"); + let (mut s, source) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.rasterItems[1].trace(), t = p.tracing, o = t.tracingOptions, r = d.rasterItems[0];\ + r.move(p, ElementPlacement.PLACEATEND); vc.run('edit.clear', {{ids: [{}]}}); var m = [];\ + try {{ t.sourceArt; }} catch (e) {{ m.push(e.message); }}\ + try {{ t.pathCount; }} catch (e) {{ m.push(e.message); }}\ + try {{ o.threshold; }} catch (e) {{ m.push(e.message); }}\ + try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }} vc.log(m);", + source.0 + ), + ); + assert_eq!(out, [json!(vec!["Stale page item"; 4])]); + assert!(s.active().unwrap().doc.node(source).is_none()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn tracing_replacements_preserve_direct_selection_of_other_paths() { + for (name, finish) in [ + ("make", ""), + ("retrace", "p.tracing.tracingOptions.threshold = 90;"), + ("expand", "p.tracing.expandTracing();"), + ("release", "p.tracing.releaseTracing();"), + ] { + let base = folder(&format!("direct-selection-{name}")); + let (mut s, image) = session(&base, false); + let mut paths = vec![]; + for x in [100, 200] { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 20, "height": 20})).unwrap(); + paths.push(NodeId(r["id"].as_u64().unwrap())); + } + s.execute("select.anchors", &json!({"id": paths[0].0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.segments", &json!({"id": paths[1].0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.add", &json!({"ids": [image.0]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + log(&mut s, &base, &format!("var p = app.activeDocument.rasterItems[0].trace(); {finish}")); + let after = &s.active().unwrap().selection; + assert_eq!(after.anchors, before.anchors, "{name}"); + assert_eq!(after.segments, before.segments, "{name}"); + assert_eq!(after.objects.len(), before.objects.len(), "{name}"); + assert_eq!(after.objects[..2], paths, "{name}"); + if name == "release" { + assert_eq!(after.objects[2], image); + } else { + assert_ne!(after.objects[2], image, "{name}"); + assert!(matches!(s.active().unwrap().doc.node(after.objects[2]).unwrap().kind, NodeKind::Group { .. })); + } + let _ = std::fs::remove_dir_all(base); + } +} + +#[test] +fn trace_options_retrace_preserves_source_and_view() { + let base = folder("options"); + let (mut s, image) = session(&base, false); + let defaults = serde_json::to_value(vectorcraft_trace::TraceParams::default()).unwrap(); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.name = 'src'; var p = r.trace(), t = p.tracing, o = t.tracingOptions;\ + vc.log([o.tracingMode, o.threshold, o.fills, o.strokes, o.maxColors, o.palette, o.ignoreWhite, o.minArea]);\ + vc.log([o.viewRaster, o.viewVector]);\ + o.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES; o.viewRaster = ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE;\ + o.threshold = 200; o.minArea = 4;\ + vc.log([o.threshold, o.minArea, o.preset, o.viewRaster, o.viewVector]);\ + vc.log(t.sourceArt.name); vc.log(r.name); vc.log(p.isTracing); vc.log(p.tracing.tracingOptions.threshold); vc.log(t.pathCount > 0);", + ); + let mode = |m: &str| json!(format!("TracingModeType.TRACINGMODE{m}")); + let expected_mode = match defaults["mode"].as_str() { + Some("blackAndWhite") => mode("BLACKANDWHITE"), + Some("grayscale") => mode("GRAY"), + _ => mode("COLOR"), + }; + assert_eq!( + out[0], + json!([ + expected_mode, + defaults["threshold"], + defaults["fills"], + defaults["strokes"], + defaults["colors"], + "Limited", + defaults["ignoreWhite"], + defaults["noise"] + ]) + ); + assert_eq!(out[1], json!(["ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"])); + assert_eq!(out[2], json!([200, 4, "Custom", "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"])); + assert_eq!(out[3..], [json!("src"), json!("src"), json!(true), json!(200), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let t = trace_of(&s, groups[0]); + assert_eq!( + (t["params"]["threshold"].clone(), t["params"]["noise"].clone(), t["view"].clone()), + (json!(200), json!(4), json!("outlinesWithSourceImage")) + ); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(groups[0])); + + // Assigning the values the options have already changes nothing. + let before = (undo_steps(&s), traces(&s)); + let out = log( + &mut s, + &base, + "var o = app.activeDocument.pageItems[0].tracing.tracingOptions; o.threshold = 200; o.minArea = 4; o.fills = true;\ + o.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES; vc.log(o.threshold);", + ); + assert_eq!(out, [json!(200)]); + assert_eq!((undo_steps(&s), traces(&s)), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_invalid_option_is_atomic() { + let base = folder("invalid"); + let (mut s, _) = session(&base, false); + log(&mut s, &base, "app.activeDocument.rasterItems[0].trace();"); + let before = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0])); + let saved = vectorcraft_format::save(&s.active().unwrap().doc, false); + let cases = [ + ("o.threshold = 'x'", "TypeError"), + ("o.threshold = 256", "TracingOptions.threshold is out of range"), + ("o.threshold = -1", "TracingOptions.threshold is out of range"), + ("o.threshold = 1.5", "TracingOptions.threshold is out of range"), + ("o.threshold = NaN", "TypeError"), + ("o.maxColors = 1", "TracingOptions.maxColors is out of range"), + ("o.maxColors = 257", "TracingOptions.maxColors is out of range"), + ("o.minArea = 1e12", "TracingOptions.minArea is out of range"), + ("o.fills = 1", "TypeError"), + ("o.fills = false", "TracingOptions requires fills or strokes"), + ("o.tracingMode = 'color'", "TypeError"), + ("o.palette = 'Spectrum'", "TracingOptions.palette has an invalid value"), + ("o.palette = 3", "TypeError"), + ("o.viewRaster = ViewRasterType.TRACINGVIEWRASTERADJUSTEDIMAGE", "TracingOptions.viewRaster has an invalid value"), + ("o.viewRaster = ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "TracingOptions.viewRaster has an invalid value"), + ("o.viewVector = 'outlines'", "TypeError"), + ("o.pathFitting = 3", "TracingOptions.pathFitting is not implemented"), + ("o.cornerAngle", "TracingOptions.cornerAngle is not implemented"), + ("o.resampleResolution = 72", "TracingOptions.resampleResolution is not implemented"), + ("t.areaCount", "TracingObject.areaCount is not implemented"), + ("o.loadFromPreset('No Such Preset')", "no built-in or saved preset has that name"), + ("o.loadFromPreset('../Default')", "cannot hold"), + ("o.loadFromPreset('C:\\\\x')", "cannot hold"), + ("o.loadFromPreset('a\\u0000b')", "cannot hold"), + ("o.loadFromPreset(new Array(300).join('x'))", "at most 256 bytes"), + ("o.loadFromPreset(' ')", "the preset name is empty"), + ("o.loadFromPreset(5)", "TypeError"), + ("o.storeToPreset('Mine')", "a script cannot run `imageTrace.presets.save`"), + ("o.storeToPreset('../Mine')", "cannot hold"), + ]; + let mut wrong = vec![]; + for (code, message) in cases { + let out = log( + &mut s, + &base, + &format!( + "var t = app.activeDocument.pageItems[0].tracing, o = t.tracingOptions, m = 'none';\ + try {{ {code}; }} catch (e) {{ m = e.name + ': ' + e.message; }} vc.log(m); vc.log(o.threshold);" + ), + ); + let m = out[0].as_str().unwrap_or_default().to_string(); + let now = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0])); + let unchanged = vectorcraft_format::save(&s.active().unwrap().doc, false) == saved; + if !m.contains(message) || out[1] != before.2["params"]["threshold"] || now != before || !unchanged { + wrong.push(format!("{code}: {m}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + assert!(s.prefs.trace_presets.is_empty(), "no preset was saved"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_presets_load_and_locked_store() { + let base = folder("presets"); + let (mut s, _) = session(&base, false); + let silhouettes = serde_json::to_value(vectorcraft_trace::preset("Silhouettes").unwrap()).unwrap(); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions;\ + vc.log(o.loadFromPreset('Silhouettes')); vc.log(o.preset); vc.log(o.threshold);\ + vc.log(o.storeToPreset('Default')); vc.log(o.storeToPreset('custom')); vc.log(o.storeToPreset('Silhouettes'));", + ); + assert_eq!(out, [json!(true), json!("Silhouettes"), silhouettes["threshold"].clone(), json!(false), json!(false), json!(false)]); + let t = trace_of(&s, traces(&s)[0]); + assert_eq!(t["params"], silhouettes); + + // Loading the preset the tracing has already traces nothing again. + let before = (undo_steps(&s), traces(&s)); + let out = log(&mut s, &base, "vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.loadFromPreset('silhouettes'));"); + assert_eq!(out, [json!(true)]); + assert_eq!((undo_steps(&s), traces(&s)), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_external_retrace_undo_and_source_delete() { + let base = folder("stale"); + let (mut s, image) = session(&base, false); + let threshold = serde_json::to_value(vectorcraft_trace::TraceParams::default()).unwrap()["threshold"].clone(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, m = [];\ + var p = d.rasterItems[0].trace(), t = p.tracing; d.selection = p; vc.run('imageTrace.make', {{}});\ + try {{ t.pathCount; }} catch (e) {{ m.push(e.message); }} try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }}\ + var q = d.pageItems[0], u = q.tracing, o = u.tracingOptions; o.threshold = 90; vc.log(o.threshold); vc.log(q.isTracing);\ + vc.run('edit.undo'); vc.log(q.isTracing); vc.log(o.threshold); vc.log(u.pathCount > 0);\ + var r = ''; try {{ u.sourceArt.remove(); }} catch (e) {{ r = e.message; }} vc.log(r); vc.log(u.pathCount > 0);\ + vc.run('edit.clear', {{ids: [{}]}});\ + try {{ u.pathCount; }} catch (e) {{ m.push(e.message); }} try {{ q.isTracing; }} catch (e) {{ m.push(e.message); }}\ + vc.log(d.pageItems[0].typename); vc.log(m);", + image.0 + ), + ); + assert_eq!(out[..5], [json!(90), json!(true), json!(true), threshold, json!(true)], "the undo puts the first tracing back"); + assert!(out[5].as_str().is_some_and(|m| m.starts_with("cannot delete hidden or locked objects")), "{:?}", out[5]); + assert_eq!(out[6], json!(true), "the refused remove leaves the tracing"); + assert_eq!(out[7], json!("GroupItem"), "a group without its source image is no longer a tracing"); + assert_eq!(out[8], json!(vec!["Stale page item"; 4])); + let _ = std::fs::remove_dir_all(base); +} + +/// After two option changes, an Undo puts back the tracing the first change made, and the objects +/// of the first tracing follow it there. +#[test] +fn trace_undo_of_the_second_retrace_reaches_the_first() { + let base = folder("chain"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions;\ + o.threshold = 90; o.threshold = 60; vc.log(o.threshold); vc.run('edit.undo');\ + vc.log(o.threshold); vc.log(p.isTracing); vc.log(p.tracing.pathCount > 0);", + ); + assert_eq!(out, [json!(60), json!(90), json!(true), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_eq!(trace_of(&s, groups[0])["params"]["threshold"], json!(90)); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_deleted_plugin_is_stale() { + let base = folder("deleted"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing, o = t.tracingOptions, m = []; p.remove();\ + try { p.name; } catch (e) { m.push(e.message); } try { t.sourceArt; } catch (e) { m.push(e.message); }\ + try { o.threshold = 10; } catch (e) { m.push(e.message); } try { t.releaseTracing(); } catch (e) { m.push(e.message); }\ + try { o.pathFitting; } catch (e) { m.push(e.message); } try { o.cornerAngle = 1; } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out, [json!(vec!["Stale page item"; 6])]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +/// A script's trace of an image past the tracer's source limit (`vectorcraft_trace::MAX_SOURCE_PIXELS`, +/// 192 megapixels) is refused from the image's header before its pixels are decoded, and the run +/// leaves the document as it was. +#[test] +fn trace_large_image_is_bounded() { + let base = folder("large"); + let png = base.join("main/wall.png"); + std::fs::write(&png, super::linkspanel::png_header(30_000, 30_000)).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let image = NodeId(r["ids"][0].as_u64().unwrap()); + let steps = undo_steps(&s); + let out = log(&mut s, &base, "var m = ''; try { app.activeDocument.rasterItems[0].trace(); } catch (e) { m = e.message; } vc.log(m);"); + let m = out[0].as_str().unwrap_or_default(); + assert!(m.contains("30000 × 30000 pixels") && m.contains("(192 megapixels)"), "{m}"); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + assert_eq!(undo_steps(&s), steps); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_remove_all_takes_the_tracing() { + let base = folder("remove-all"); + let (mut s, _) = session(&base, false); + let out = log(&mut s, &base, "var d = app.activeDocument; d.rasterItems[0].trace(); d.pageItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, [json!(0)]); + assert!(traces(&s).is_empty()); + assert!(top(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_stop_rolls_back_long_work() { + let base = folder("stop"); + let (mut s, image) = session(&base, false); + let before = top(&s); + s.script_in_run = true; + let stop = s.script_interrupt(); + stop.set(); + let r = s.execute("imageTrace.make", &json!({"id": image.0})); + stop.clear(); + s.script_in_run = false; + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!(top(&s), before); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_stop_rolls_back_a_handed_in_trace() { + let base = folder("stop-hand-off"); + let (mut s, image) = session(&base, false); + let before = top(&s); + let p = json!({"id": image.0}); + let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap(); + run.run(&|_, _| true).unwrap().hand_in(&mut s); + s.script_in_run = true; + let stop = s.script_interrupt(); + stop.set(); + let r = s.execute("imageTrace.make", &p); + stop.clear(); + s.script_in_run = false; + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!(top(&s), before); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_trace_refuses_the_source_image_of_a_trace() { + let base = folder("source"); + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let e = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap_err().to_string(); + assert!(e.contains("source image of an Image Trace object"), "{e}"); + assert_eq!(traces(&s), [group]); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(group)); + + // With another image named after the source image, that other image is traced. + let png = base.join("main/disc.png"); + let other = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let other = NodeId(other["ids"][0].as_u64().unwrap()); + let r = s.execute("imageTrace.make", &json!({"ids": [image.0, other.0]})).unwrap(); + let second = NodeId(r["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(other), Some(second)); + assert_eq!(d.parent_of(image), Some(group)); + assert_eq!(traces(&s).len(), 2); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_of_another_image_inside_a_tracing() { + let base = folder("inside"); + let (mut s, image) = session(&base, false); + let png = base.join("main/disc.png"); + let other = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let other = NodeId(other["ids"][0].as_u64().unwrap()); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0]; r.move(p, ElementPlacement.PLACEATBEGINNING);\ + var q = r.trace(); vc.log(q.typename); vc.log(q.tracing.sourceArt === r); vc.log(p.tracing.pathCount > 0);\ + vc.log(p.tracing.pathCount === 2 * q.tracing.pathCount); vc.log(p.tracing.anchorCount === 2 * q.tracing.anchorCount);", + ); + // The two traces are of the same image with the same settings: the outer counts take in the + // inner trace's paths without its seam fills. + assert_eq!(out, [json!("PluginItem"), json!(true), json!(true), json!(true), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 2); + let d = &s.active().unwrap().doc; + let (a, b) = (d.parent_of(image).unwrap(), d.parent_of(other).unwrap()); + assert!(groups.contains(&a) && groups.contains(&b) && a != b, "each image is the source of its own tracing"); + assert!(d.parent_of(a) == Some(b) || d.parent_of(b) == Some(a), "one tracing is inside the other"); + let _ = std::fs::remove_dir_all(base); +} + +/// An object moved or duplicated to the end of a tracing goes directly above its source image, +/// which stays the tracing's first child. +#[test] +fn an_object_placed_at_the_end_of_a_tracing_stays_above_its_source() { + let base = folder("at-end"); + let (mut s, _) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, a = d.rasterItems[1]; a.name = 'src'; var p = a.trace(), r = d.rasterItems[0]; r.name = 'moved';\ + r.duplicate(p, ElementPlacement.PLACEATEND); r.move(p, ElementPlacement.PLACEATEND);\ + var s = p.tracing.sourceArt; s.hidden = false; s.move(p, ElementPlacement.PLACEATEND);\ + vc.log(p.tracing.sourceArt.name); vc.log(d.rasterItems.length); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!("src"), json!(2), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let d = &s.active().unwrap().doc; + let names: Vec> = d.children(Some(groups[0])).unwrap().iter().map(|n| n.name.clone()).collect(); + let name = |n: &str| Some(n.to_string()); + assert_eq!(names[..3], [name("src"), name("moved"), name("moved")], "the source stays first: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The source image stays a tracing's first child when it goes to the front of the tracing, and +/// when another object in the tracing is sent to the back or the source is brought to the front. +#[test] +fn reordering_inside_a_tracing_keeps_the_source_first() { + let base = folder("reorder"); + let (mut s, _) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, a = d.rasterItems[1]; a.name = 'src'; var p = a.trace(), r = d.rasterItems[0]; r.name = 'moved';\ + r.move(p, ElementPlacement.PLACEATBEGINNING);\ + var s = p.tracing.sourceArt; s.hidden = false; s.move(p, ElementPlacement.PLACEATBEGINNING); vc.log(p.isTracing);\ + r.zOrder(ZOrderMethod.SENDTOBACK); vc.log(p.isTracing); r.zOrder(ZOrderMethod.SENDBACKWARD); vc.log(p.isTracing);\ + s.zOrder(ZOrderMethod.BRINGTOFRONT); s.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(p.isTracing); vc.log(p.tracing.sourceArt.name);", + ); + assert_eq!(out, [json!(true), json!(true), json!(true), json!(true), json!("src")]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let d = &s.active().unwrap().doc; + let names: Vec> = d.children(Some(groups[0])).unwrap().iter().map(|n| n.name.clone()).collect(); + assert_eq!(names[..2], [Some("src".to_string()), Some("moved".to_string())], "the source stays first: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A tracing's source image cannot be moved out of its tracing, and the refused move leaves the +/// document as it was. +#[test] +fn the_source_image_cannot_leave_its_tracing() { + let base = folder("source-leaves"); + let (mut s, _) = session(&base, false); + log(&mut s, &base, "app.activeDocument.rasterItems[0].trace().tracing.sourceArt.hidden = false;"); + let saved = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.pageItems[0], m = 'none';\ + try { p.tracing.sourceArt.move(p, ElementPlacement.PLACEBEFORE); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!("a tracing's source image cannot leave its tracing"), json!(true)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), saved); + assert_eq!(undo_steps(&s), steps); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_source_art_is_not_listed_with_the_images() { + let base = folder("lists"); + let (mut s, _) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument; d.rasterItems[0].trace(); var n = d.rasterItems.length, k = 0;\ + for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename === 'RasterItem') k++; }\ + d.rasterItems.removeAll(); vc.log(n); vc.log(k); vc.log(d.rasterItems.length); vc.log(d.pageItems[0].typename);", + ); + assert_eq!(out, [json!(1), json!(1), json!(0), json!("PluginItem")]); + assert_eq!(traces(&s).len(), 1, "removing the raster items leaves the tracing"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_plugin_keeps_its_name() { + let base = folder("renamed"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(), t = p.tracing, m = '', n = p.name; p.name = n;\ + try { p.name = 'logo'; } catch (e) { m = e.message; } vc.log(m); vc.log(p.name === n); vc.log(p.typename); vc.log(t.pathCount > 0);", + ); + assert_eq!(out, [json!("The name of a tracing cannot be changed"), json!(true), json!("PluginItem"), json!(true)]); + assert_eq!(traces(&s).len(), 1); + assert_eq!(undo_steps(&s), 2, "the place and the run"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_group_holding_an_image_cannot_take_the_tracing_name() { + let base = folder("rename-to-trace"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, m = ''; d.selection = [d.rasterItems[0]]; vc.run('object.group'); var g = d.pageItems[0];\ + try { g.name = 'Image Trace'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.typename); g.name = 'Logo'; vc.log(g.name);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem"), json!("Logo")]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn an_image_cannot_move_first_into_a_group_named_as_a_tracing() { + let base = folder("move-into-trace-name"); + let (mut s, _) = session(&base, false); + let before = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, r = d.rasterItems[0], m = [];\ + d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group'); var g = d.pageItems[0];\ + g.name = 'Image Trace';\ + try { r.move(g, ElementPlacement.PLACEATEND); m.push('moved'); } catch (e) { m.push(e.message); }\ + try { r.duplicate(g, ElementPlacement.PLACEATEND); m.push('copied'); } catch (e) { m.push(e.message); }\ + vc.log(m); vc.log(d.rasterItems.length); vc.log(g.typename);\ + r.move(g, ElementPlacement.PLACEATBEGINNING); vc.log(g.typename);", + ); + let refused = json!("Only Image Trace can make a tracing"); + assert_eq!(out, [json!([refused, refused]), json!(1), json!("GroupItem"), json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let d = &s.active().unwrap().doc; + let g = top(&s)[0]; + let kids: Vec = d.children(Some(g)).unwrap().iter().map(|n| matches!(n.kind, crate::doc::NodeKind::Image(_))).collect(); + assert_eq!(kids, [false, true], "the image went in above the rectangle"); + assert_eq!(undo_steps(&s), before + 1, "the run is one step"); + let _ = std::fs::remove_dir_all(base); +} + +/// `move`, `remove()` and `zOrder` refuse to leave an image at the bottom of an ordinary group named +/// as a tracing, before the document changes, and allow the same moves when another object stays +/// at the bottom. +#[test] +fn an_image_cannot_be_left_first_in_a_group_named_as_a_tracing() { + let base = folder("leave-trace-name"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], r = d.rasterItems[0], p = d.pathItems[0], m = [];\ + function t(f) { try { f(); m.push('done'); } catch (e) { m.push(e.message); } }\ + t(function () { p.move(g, ElementPlacement.PLACEBEFORE); });\ + t(function () { p.move(g, ElementPlacement.PLACEATBEGINNING); });\ + t(function () { p.remove(); });\ + t(function () { p.zOrder(ZOrderMethod.BRINGTOFRONT); });\ + t(function () { p.zOrder(ZOrderMethod.BRINGFORWARD); });\ + t(function () { r.zOrder(ZOrderMethod.SENDTOBACK); });\ + t(function () { r.zOrder(ZOrderMethod.SENDBACKWARD); });\ + vc.log(m); vc.log(g.typename);", + ); + assert_eq!(out, [json!(vec!["Only Image Trace can make a tracing"; 7]), json!("GroupItem")]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], p = d.pathItems[0];\ + d.pathItems.rectangle(40, 40, 5, 5).move(g, ElementPlacement.PLACEATEND);\ + p.move(g, ElementPlacement.PLACEBEFORE); vc.log(g.typename);", + ); + assert_eq!(out, [json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let d = &s.active().unwrap().doc; + let g = top(&s).into_iter().find(|i| d.node(*i).is_some_and(|n| n.name.as_deref() == Some(crate::cmd::TRACE_NAME))).unwrap(); + assert_eq!(d.children(Some(g)).unwrap().len(), 2, "the rectangle left the group"); + let _ = std::fs::remove_dir_all(base); +} + +/// Deleting the clipping path of a clip group named as a tracing releases its mask, so `remove()` and +/// `textFrames.removeAll()` refuse it when an image would be left first in the released group. +#[test] +fn removing_a_clipping_path_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let base = folder("release-trace-name"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.rasterItems[0], d.pathItems.rectangle(10, 10, 20, 20)];\ + vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], m = '';\ + try { d.pathItems[0].remove(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.clipped);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(true)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument, t = d.textFrames.add(); t.contents = 'Clip';\ + d.selection = [d.rasterItems[0], t]; vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], m = '';\ + try { g.textFrames.removeAll(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.textFrames.length);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(1)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +/// `textFrames.removeAll()` and `groupItems.removeAll()` on an ordinary group named as a tracing +/// refuse to leave an image first in it, before the document changes, and delete when another +/// object stays first. +#[test] +fn remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let base = folder("remove-all-trace-name"); + let refused = json!("Only Image Trace can make a tracing"); + for (under, call) in [ + ("var u = d.textFrames.add(); u.contents = 'Under';", "g.textFrames.removeAll();"), + ("d.selection = [d.pathItems.rectangle(50, 50, 5, 5)]; vc.run('object.group'); var u = d.pageItems[0];", "g.groupItems.removeAll();"), + ] { + let (mut s, _) = session(&base, false); + // The group holds the type or group at the bottom and the image above it. + log( + &mut s, + &base, + &format!( + "var d = app.activeDocument; var p = d.pathItems.rectangle(10, 10, 20, 20); d.selection = [p]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; {under} u.move(g, ElementPlacement.PLACEATEND);\ + d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING); p.remove();" + ), + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, g = d.pageItems[0], m = ''; try {{ {call} m = 'done'; }} catch (e) {{ m = e.message; }} vc.log(m); vc.log(g.typename);" + ), + ); + assert_eq!(out, [refused.clone(), json!("GroupItem")], "{call}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{call}"); + assert_eq!(undo_steps(&s), steps, "{call}"); + assert!(traces(&s).is_empty()); + } + // With a rectangle left first, the type goes and the group stays an ordinary group. + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; var t = d.textFrames.add(); t.contents = 'Over';\ + t.move(g, ElementPlacement.PLACEATBEGINNING); d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);\ + g.textFrames.removeAll(); vc.log(g.textFrames.length); vc.log(g.pageItems.length); vc.log(g.typename);", + ); + assert_eq!(out, [json!(0), json!(2), json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +/// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object +/// its trace did not make, before the document changes. +#[test] +fn release_refuses_added_artwork_before_changing_the_document() { + let base = folder("release-added-artwork"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(); d.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var items = app.activeDocument.pageItems, p, m = '';\ + for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') p = items[i];\ + try { p.tracing.releaseTracing(); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!("Cannot release a tracing containing added artwork")]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + assert_eq!(traces(&s).len(), 1); + let _ = std::fs::remove_dir_all(base); +} + +/// Retracing and releasing discard the objects the trace made, so both refuse a tracing that holds +/// a locked one, before the document changes. +#[test] +fn retrace_and_release_refuse_locked_traced_artwork() { + let base = folder("locked-traced-artwork"); + for action in ["p.tracing.tracingOptions.threshold = 90;", "p.tracing.releaseTracing();"] { + let (mut s, image) = session(&base, false); + let r = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + let group = NodeId(r["id"].as_u64().unwrap()); + let made = s.active().unwrap().doc.node(group).unwrap().children().unwrap()[1].id; + s.edit("Lock traced artwork", |d, _| { + d.node_mut(made).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!("var p = app.activeDocument.pageItems[0], m = ''; try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);"), + ); + assert_eq!(out, [json!(format!("Cannot edit page item {}", made.0))], "{action}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{action}"); + assert_eq!(undo_steps(&s), steps, "{action}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// The `TracingOptions` and `TracingObject` members that are not implemented are left out of +/// `hasOwnProperty` and `reflect`, and still throw when read. +#[test] +fn unimplemented_tracing_members_are_not_reported() { + let base = folder("unimplemented-members"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing, o = t.tracingOptions, m = '';\ + vc.log([o.hasOwnProperty('pathFitting'), t.hasOwnProperty('areaCount'), t.hasOwnProperty('pathCount')]);\ + vc.log([o.reflect.find('pathFitting') === null, t.reflect.find('areaCount') === null, t.reflect.find('pathCount') === null]);\ + try { t.areaCount; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!([false, false, true]), json!([true, true, false]), json!("TracingObject.areaCount is not implemented")]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn new_group_at_the_bottom_of_a_tracing_is_refused() { + let base = folder("new-group-bottom"); + let (mut s, id) = session(&base, false); + let tid = NodeId(s.execute("imageTrace.make", &json!({"id": id.0})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let e = s.execute("object.newGroup", &json!({"parent": tid.0, "index": 0})).unwrap_err().to_string(); + assert!(e.contains("source image"), "{e}"); + assert_eq!(traces(&s), [tid]); + assert_eq!(undo_steps(&s), steps); + let g = NodeId(s.execute("object.newGroup", &json!({"parent": tid.0, "index": 1})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(traces(&s), [tid]); + assert_eq!(s.active().unwrap().doc.children(Some(tid)).unwrap()[1].id, g); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retrace_keeps_the_tracing_opacity_and_blend_mode() { + let base = folder("retrace-appearance"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(); p.opacity = 50; p.blendingMode = BlendModes.MULTIPLY;\ + p.tracing.tracingOptions.threshold = 90; vc.log(p.opacity); vc.log(p.blendingMode === BlendModes.MULTIPLY);\ + p.tracing.tracingOptions.threshold = 100; vc.log(p.opacity); vc.log(p.blendingMode === BlendModes.MULTIPLY);", + ); + assert_eq!(out, [json!(50), json!(true), json!(50), json!(true)]); + let id = traces(&s)[0]; + assert_eq!(s.active().unwrap().doc.node(id).unwrap().opacity, 0.5); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retraced_plugin_is_the_same_object_as_its_collection_handle() { + let base = folder("retrace-identity"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(); vc.log(d.pageItems[0] === p);\ + p.tracing.tracingOptions.threshold = 90; vc.log(d.pageItems[0] === p); vc.log(app.selection[0] === p);\ + p.tracing.tracingOptions.threshold = 100; vc.log(d.pageItems[0] === p); vc.log(p.tracing.parent === d.pageItems[0]);", + ); + assert_eq!(out, vec![json!(true); 5]); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs new file mode 100644 index 0000000000..f3aa67c361 --- /dev/null +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -0,0 +1,404 @@ +//! The script object model: a page item's `translate`, `rotate`, `resize` and `transform`. + +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 rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// A 400 × 300 pt document with a 30 × 40 pt rectangle above a 50 × 50 pt one, so that `pageItems` +/// (topmost first) lists the 30 × 40 pt one first. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The numbers of a logged array, or a logged number as one. +fn numbers(v: &Value) -> Vec { + match v.as_array() { + Some(a) => a.iter().map(|n| n.as_f64().unwrap()).collect(), + None => vec![v.as_f64().unwrap()], + } +} + +fn close(a: &[f64], b: &[f64]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6) +} + +#[test] +fn translate_moves_by_the_offsets_with_y_up_in_one_undo_step() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0]; var l = i.left, t = i.top;\ + i.translate(10, 0); vc.log([i.left - l, i.top - t]);\ + i.translate(0, 10); vc.log([i.left - l, i.top - t]);\ + app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var t2 = i.top;\ + i.translate(0, 5); vc.log(i.top - t2);", + ); + assert!(close(&numbers(&out[0]), &[10.0, 0.0]), "{out:?}"); + assert!(close(&numbers(&out[1]), &[10.0, 10.0]), "{out:?}"); + // With Y down from the artboard's top, a move up reads as a smaller top. + assert!(close(&numbers(&out[2]), &[-5.0]), "{out:?}"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.active().unwrap().doc.bounds_of(&[a], false).unwrap(); + assert!(close(&[r.x0, r.y0], &[10.0, 20.0]), "{r:?}"); +} + +#[test] +fn rotate_turns_counterclockwise_about_the_center_or_the_named_point() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var g = app.activeDocument.pageItems[0], r = g.geometricBounds; vc.log(g.typename);\ + vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);\ + g.rotate(90); r = g.geometricBounds; vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);", + ); + assert_eq!(out[0], json!("GroupItem")); + let (before, after) = (numbers(&out[1]), numbers(&out[2])); + // The width and height trade places, and the center stays. + assert!(close(&after, &[before[1], before[0], before[2], before[3]]), "{before:?} {after:?}"); + + // A positive angle about the bottom-left corner swings a rectangle to the left of that corner. + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0]; vc.log(i.geometricBounds);\ + i.rotate(90, true, true, true, true, Transformation.BOTTOMLEFT); vc.log(i.geometricBounds);", + ); + let (b0, b1) = (numbers(&out[0]), numbers(&out[1])); + // [left, top, right, bottom], Y up: the 30 pt wide side now stands up, and the 40 pt tall side + // lies to the left. + assert!(close(&b1, &[b0[0] - 40.0, b0[3] + 30.0, b0[0], b0[3]]), "{b0:?} {b1:?}"); +} + +#[test] +fn resize_scales_about_the_center_and_line_widths_follow_their_argument() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, i = p[0], j = p[1];\ + function stroke(o) { return (o.visibleBounds[2] - o.visibleBounds[0]) - o.width; }\ + var r = i.geometricBounds, s0 = stroke(i); i.resize(50, 50); var q = i.geometricBounds;\ + vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3]), stroke(i) - s0]);\ + var s1 = stroke(j); j.resize(50, 50, true, true, true, true, 50); vc.log([s0, stroke(j) / s1]);", + ); + let first = numbers(&out[0]); + assert!(close(&first, &[15.0, 20.0, 0.0, 0.0, 0.0]), "{first:?}"); + let second = numbers(&out[1]); + assert!(second[0] > 0.0, "the rectangles have a stroke: {second:?}"); + assert!(close(&second[1..], &[0.5]), "{second:?}"); + // On a path, any other line width sets the stroke weight to that percent of what it was. + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0], w = i.strokeWidth; i.resize(50, 50, true, true, true, true, 70); vc.log(i.strokeWidth / w);", + ); + assert!(close(&numbers(&out[0]), &[0.7]), "{out:?}"); + // On a group, a line width that is neither 100 nor the scale itself is refused. + s.execute("select.all", &json!({})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(50, 50, true, true, true, true, 70);"); + assert!(e.contains("changeLineWidths") && e.contains("not available yet"), "{e}"); +} + +#[test] +fn a_line_width_of_the_scale_itself_keeps_a_path_stroke_within_1000_points() { + let (mut s, _, _) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 600;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for call in ["resize(200, 200, true, true, true, true, 200)", "transform(app.getScaleMatrix(200), true, true, true, true, 200)"] { + let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};")); + assert!(e.contains("more than 1000 points"), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + // A scale that keeps the weight within the limit still scales it. + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.resize(150, 150, true, true, true, true, 150); vc.log(i.strokeWidth);"); + assert!(close(&numbers(&out[0]), &[900.0]), "{out:?}"); + + // The lower stroke must stay within the limit too. + let (mut s, a, _) = doc(); + s.execute("stroke.set", &json!({"id": a.0, "weight": 600})).unwrap(); + s.execute("appearance.addStroke", &json!({"id": a.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 1;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(200, 200, true, true, true, true, 200);"); + assert!(e.contains("more than 1000 points"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + + // A nonfinite scale must not turn a zero-width stroke into NaN. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.strokeWidth = 0;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].resize(1e202, 1e202, true, true, true, true, 1e202);"); + assert!(e.contains("more than 1000 points"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); +} + +#[test] +fn an_empty_path_takes_any_transformation_about_any_point() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "app.activeDocument.pathItems.add();"); + let out = log( + &mut s, + "var n = app.activeDocument.pathItems[0]; n.rotate(30); n.rotate(30, true, true, true, true, Transformation.TOPLEFT);\ + n.resize(50, 200); n.resize(50, 50, true, true, true, true, 100, Transformation.BOTTOM);\ + n.transform(app.getRotationMatrix(45)); n.rotate(30, true, true, true, true, Transformation.DOCUMENTORIGIN);\ + vc.log(n.pathPoints.length);", + ); + assert_eq!(out, vec![json!(0)]); + // Its stroke weight still scales with the transformation. + let out = log( + &mut s, + "var n = app.activeDocument.pathItems[0]; n.strokeWidth = 10; n.resize(200, 200, true, true, true, true, 200); vc.log(n.strokeWidth);", + ); + assert!(close(&numbers(&out[0]), &[20.0]), "{out:?}"); + let e = failure(&mut s, "app.activeDocument.pathItems[0].rotate(30, true, true, true, true, 'x');"); + assert!(e.contains("Transformation value"), "{e}"); +} + +#[test] +fn transform_applies_a_matrix_record_about_the_center() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0], r = i.geometricBounds;\ + i.transform(app.getRotationMatrix(45)); var q = i.geometricBounds;\ + vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3])]);\ + var l = i.left; i.transform(app.getTranslationMatrix(5, 0)); vc.log(i.left - l);", + ); + let side = 70.0 / 2f64.sqrt(); + assert!(close(&numbers(&out[0]), &[side, side, 0.0, 0.0]), "{out:?}"); + assert!(close(&numbers(&out[1]), &[5.0]), "{out:?}"); + assert_eq!(undo_steps(&s), steps + 1); +} + +#[test] +fn transforms_that_change_nothing_add_no_undo_step() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + log( + &mut s, + "var i = app.activeDocument.pageItems[0]; i.translate(); i.translate(0, 0); i.rotate(0); i.rotate(360);\ + i.resize(100, 100); i.transform(app.getIdentityMatrix()); i.translate(10, 0, false, false, false, false);\ + i.translate(7000000, 0, false, false, false, false);\ + i.transform(app.getScaleMatrix(Math.pow(2, 600) * 100), false, false, false, false, 100);", + ); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn a_scale_whose_square_is_too_large_for_a_number_keeps_its_own_line_width() { + let (mut s, _, _) = doc(); + let call = "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(Math.pow(2, 600) * 100), false, false, false, false, 70);"; + let e = failure(&mut s, call); + assert!(e.contains("other than 100 or the scale itself"), "{e}"); +} + +#[test] +fn a_line_width_of_zero_is_not_the_scale_itself_however_small_the_scale() { + let (mut s, _, _) = doc(); + let call = "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(1e-10), true, false, true, false, 0);"; + let e = failure(&mut s, call); + assert!(e.contains("other than 100 or the scale itself"), "{e}"); + // A positive request still matches a tiny scale of its own. + log(&mut s, "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(1e-10), true, false, true, false, 1e-10);"); +} + +#[test] +fn an_offset_past_the_canvas_is_taken_when_the_call_moves_nothing() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().doc.clone(); + log(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0, false, false, false, false);"); + // The object uses no pattern, so moving patterns moves nothing either. + log(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0, false, true, false, true);"); + assert_eq!(*s.active().unwrap().doc, *before); + let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(Infinity, 0, false, false, false, false);"); + assert!(e.contains("finite number"), "{e}"); + let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0);"); + assert!(e.contains("outside the canvas"), "{e}"); +} + +#[test] +fn a_move_too_small_to_round_away_moves_the_object() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0], l = i.left; i.translate(5e-13, 0); vc.log(i.left > l);"); + assert_eq!(out, vec![json!(true)]); + assert_eq!(undo_steps(&s), steps + 1); +} + +#[test] +fn a_tiny_move_about_a_distant_center_moves_the_object() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The center is at x = 100, where 1e-15 rounds away; the left edge at 0 keeps it. + rect(&mut s, 0.0, 0.0, 200.0, 10.0); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0], l = i.left;\ + i.transform({mValueA: 1, mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: 1e-15, mValueTY: 0}); vc.log(i.left > l);", + ); + assert_eq!(out, vec![json!(true)]); +} + +#[test] +fn a_scale_and_translation_about_the_center_straddle_the_origin() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 127, "y1": 0, "x2": 129, "y2": 0})).unwrap()["id"].as_u64().unwrap()); + log( + &mut s, + "app.activeDocument.pageItems[0].transform({mValueA: Math.pow(2, -55), mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: -128, mValueTY: 0});", + ); + let r = s.active().unwrap().doc.bounds_of(&[line], false).unwrap(); + assert!(r.x0 < 0.0 && r.x1 > 0.0, "{r:?}"); +} + +#[test] +fn a_clipped_object_moved_past_the_canvas_is_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let far = rect(&mut s, 0.9 * crate::MAX_COORD, 0.0, 10.0, 10.0); + let mask = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [far.0, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].translate({}, 0);", 0.2 * crate::MAX_COORD)); + assert!(e.contains("past the canvas"), "{e}"); + assert_eq!(s.active().unwrap().doc.node(far), before.node(far)); +} + +#[test] +fn a_transformation_whose_bounds_reach_past_the_canvas_is_kept_when_the_art_does_not() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // A diagonal line through the origin, 0.6 of the canvas limit out each way. + let a = 0.6 * crate::MAX_COORD; + let line = NodeId(s.execute("shape.line", &json!({"x1": -a, "y1": a, "x2": a, "y2": -a})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + // On the page (Y down), x' = x + y about the center: the line becomes upright at x = 0, while + // a corner of its bounds would go to 1.2 times the limit. + log( + &mut s, + "var m = {mValueA: 1, mValueB: 0, mValueC: -1, mValueD: 1, mValueTX: 0, mValueTY: 0};\ + app.activeDocument.pageItems[0].transform(m);", + ); + let r = s.active().unwrap().doc.bounds_of(&[line], false).unwrap(); + assert!(r.width() < 1e-6 && (r.height() - 2.0 * a).abs() < 1e-3, "{r:?}"); + // The same shear twice takes the line itself past the canvas. + let e = failure( + &mut s, + "var m = {mValueA: 1, mValueB: 0, mValueC: -2, mValueD: 1, mValueTX: 0, mValueTY: 0};\ + app.activeDocument.pageItems[0].transform(m);", + ); + assert!(e.contains("past the canvas"), "{e}"); +} + +#[test] +fn locked_art_and_art_on_a_locked_artboard_are_refused() { + let (mut s, a, b) = doc(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for call in ["translate(5, 0)", "rotate(30)", "resize(50, 50)", "transform(app.getScaleMatrix(200))"] { + let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0]; i.locked = true; i.{call};")); + assert!(e.contains(&format!("cannot transform locked objects: {}", a.0)), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + // A group that holds a locked object is refused too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let (before, steps) = (s.active().unwrap().doc.clone(), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(5, 0);"); + assert!(e.contains("cannot transform locked objects"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).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.pageItems[1].rotate(45);"); + assert!(e.contains("cannot transform objects on a locked artboard"), "{e}"); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn bad_arguments_throw_and_change_nothing() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for (call, says) in [ + ("rotate('x')", "angle must be a finite number"), + ("rotate()", "angle must be a finite number"), + ("resize(50)", "scaleY must be a finite number"), + ("resize(0, 50)", "must not be 0"), + ("resize(50, 50, true, true, true, true, -1)", "changeLineWidths must not be negative"), + ("transform({})", "transformationMatrix must be a Matrix"), + ("transform(app.getScaleMatrix(0))", "singular"), + ("translate(1, 0, 'yes')", "transformObjects must be true or false"), + ("translate(7000000, 0)", "past the canvas"), + ("translate('x')", "deltaX must be a finite number"), + ("translate(NaN)", "is not a finite number"), + ("rotate(5, true, false, false)", "changeFillGradients different from changePositions"), + ("rotate(5, true, true, true, false)", "changeFillPatterns and changeStrokePattern"), + // Left out, the stroke pattern follows the Transform Pattern Tiles preference (off), and + // gradients default to true. + ("rotate(5, true, true)", "changeFillPatterns and changeStrokePattern"), + ("translate(10, 0, false)", "transformFillGradients different from transformObjects"), + ("rotate(5, true, true, true, true, 'Transformation.NOPE')", "Transformation value"), + ("rotate(5, true, true, true, true, 3)", "Transformation value"), + ("resize(1e9, 1e9)", "past the canvas"), + // Stroke weights cannot scale while the object stays where it is. + ("resize(50, 50, false, false, false, false, 50)", "with changePositions false is not available yet"), + ] { + let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};")); + assert!(e.contains(says), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + // A deleted object is stale before its arguments are used. + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.rotate(10);"); + assert!(e.contains("Stale page item"), "{e}"); +} diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 1b41d992fd..3ab8f8be82 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -24,6 +24,11 @@ fn write(path: &Path, text: &str) { std::fs::write(path, text).unwrap(); } +/// `text` as a quoted script string literal, with its quotes, backslashes and line breaks escaped. +fn js_string(text: &str) -> String { + serde_json::to_string(text).unwrap() +} + /// Runs `main/main.jsx` in `base`, with the text `text`. fn run(base: &Path, text: &str) -> Result { let main = base.join("main/main.jsx"); @@ -443,11 +448,12 @@ fn script_file_name_names_the_file_of_the_code_that_reads_it() { #[test] fn script_eval_file_outside_scope_refused() { - let base = folder("evaloutside"); + // The apostrophe in the folder name would end a quoted script string. + let base = folder("eval'outside"); write(&base.join("outside.jsx"), "1;"); - let absolute = base.join("outside.jsx").to_string_lossy().replace('\\', "/"); + let absolute = js_string(&base.join("outside.jsx").to_string_lossy().replace('\\', "/")); let script = format!( - "var out = [];\ntry {{ $.evalFile('../outside.jsx'); }} catch (e) {{ out.push(String(e)); }}\ntry {{ $.evalFile('{absolute}'); }} catch (e) {{ out.push(String(e)); }}\nvc.log(out);" + "var out = [];\ntry {{ $.evalFile('../outside.jsx'); }} catch (e) {{ out.push(String(e)); }}\ntry {{ $.evalFile({absolute}); }} catch (e) {{ out.push(String(e)); }}\nvc.log(out);" ); let r = run(&base, &script).unwrap(); let out = r["log"][0].as_array().unwrap(); @@ -461,6 +467,21 @@ fn script_eval_file_outside_scope_refused() { let _ = std::fs::remove_dir_all(base); } +/// A refused absolute path whose URI form is read by no candidate either keeps the refusal of +/// the path as written, not a missing file. +#[cfg(not(windows))] +#[test] +fn script_eval_file_keeps_the_refusal_when_no_uri_form_is_read() { + let base = folder("eval'uri"); + write(&base.join("out%20side.jsx"), "1;"); + let absolute = base.join("out%20side.jsx").to_string_lossy().into_owned(); + let script = format!("try {{ $.evalFile({}); }} catch (e) {{ vc.log(String(e)); }}", js_string(&absolute)); + let r = run(&base, &script).unwrap(); + let e = r["log"][0].as_str().unwrap_or_default().to_string(); + assert!(e.starts_with(&format!("Error: script file read refused: {absolute}")), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_directives_in_strings_and_block_comments_are_inert() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs new file mode 100644 index 0000000000..cf873ec324 --- /dev/null +++ b/crates/engine/src/tests/script_palettes.rs @@ -0,0 +1,1018 @@ +//! ScriptUI palettes in a script: a named engine to show them in, the events that wait for a run +//! and run one at a time after it, the events that take a waiting one's place, `close()` and the +//! close box, the engine's end, and the limits. + +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::script::palettes::{MAX_PALETTES, MAX_WAITING}; +use crate::script::scriptui::PALETTE_NEEDS_ENGINE; +use crate::script::{DialogAnswer, SETTLE_FAILS, TEST_ELAPSED, UiEvent, Waiting}; +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 run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "p.js"})) +} + +/// Pumps the run in the app until it ends, or until it waits at a dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_dialog().is_some() || s.script_window().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +/// Runs `source` in the app to its end. +fn run_in_app(s: &mut Session, source: &str) -> Value { + s.script_frames = true; + assert_eq!(run(s, source).unwrap()["running"], true); + pump(s).expect("the run ended").unwrap() +} + +/// A palette in the engine `tools` with a button (control 1) whose handler counts its clicks and +/// adds a rectangle, and a field (control 2). +const TOOLS: &str = "#targetengine tools\n\ + var clicks = 0; var p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + var field = p.add('edittext', undefined, ''); \ + go.onClick = function () { clicks++; vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); vc.log('click ' + clicks); }; \ + field.onChange = function () { vc.log('change ' + field.text); }; p.show(); vc.log('shown');"; + +fn only_palette(s: &Session) -> u64 { + let list = s.script_palettes(); + assert_eq!(list.len(), 1, "{list:?}"); + list[0].id +} + +#[test] +fn show_returns_at_once_and_the_palette_stays_after_the_run() { + let mut s = one_doc(); + let r = run(&mut s, TOOLS).unwrap(); + assert_eq!(r["log"], json!(["shown"]), "show() did not wait: {r}"); + let id = only_palette(&s); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["engine"], "tools"); + assert_eq!(listed["palettes"][0]["title"], "Tools"); + assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Go"); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"])); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a handler's run is one undo step"); + let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 2, "value": "abc"})).unwrap(); + assert_eq!(changed["log"], json!(["change abc"])); +} + +#[test] +fn update_in_a_palette_s_handler_runs_and_the_palette_shows_the_last_value() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 10); \ + var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { for (var k = 1; k <= 10; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["done"]), "update() in the handler does not throw"); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["value"].as_f64(), Some(10.0), "{listed}"); +} + +#[test] +fn update_outside_a_handler_pauses_the_run_so_the_app_draws_the_palette_at_most_once_per_interval() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); p.show(); \ + for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); }"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + let value = |s: &Session| s.script_palettes().first().map_or(0.0, |p| p.dialog.nodes[1].value); + for _ in 0..100 { + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + if value(&s) > 0.0 { + break; + } + } + let first = value(&s); + assert!(first > 0.0); + TEST_ELAPSED.set(Some(Duration::from_millis(16))); + assert!(s.script_pump().is_none(), "an update() a frame later pauses the run too"); + let second = value(&s); + assert!(second > first, "the palette shows the second update()"); + assert!(s.script_pump().expect("an update() within the same frame does not pause the run").is_ok()); + assert!(value(&s) > second); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_hands_a_click_given_during_the_run_to_its_handler_so_cancel_stops_the_loop() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100000); \ + var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; cancel.onClick = function () { stopped = true; }; \ + p.show(); var k = 0; while (!stopped && k < 100000) { k++; bar.value = k; p.update(); } vc.log(stopped ? 'canceled' : 'ran out');"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + for _ in 0..100 { + if !s.script_palettes().is_empty() { + break; + } + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + } + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + let report = pump(&mut s).expect("the run ended").unwrap(); + assert_eq!(report["log"], json!(["canceled"]), "{report}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the click was handled in the run, not left for a run of its own"); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_drops_a_waiting_click_on_a_control_an_earlier_handler_disabled() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var stop = p.add('button', undefined, 'Stop'); \ + var other = p.add('button', undefined, 'Other'); var stopped = false; var log = []; \ + stop.onClick = function () { stopped = true; other.enabled = false; log.push('stop'); }; \ + other.onClick = function () { log.push('other'); }; \ + p.show(); var k = 0; while (!stopped && k < 100000) { k++; p.update(); } vc.log(log.join());"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + for _ in 0..100 { + if !s.script_palettes().is_empty() { + break; + } + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + } + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + let report = pump(&mut s).expect("the run ended").unwrap(); + assert_eq!(report["log"], json!(["stop"]), "the click on the disabled button runs no handler: {report}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the click on the disabled button is dropped"); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_in_a_handler_does_not_pause_the_run() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); \ + var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + let report = s.script_pump().expect("the handler's run ends without a pause after the handler").unwrap(); + assert_eq!(report["log"], json!(["done"])); + TEST_ELAPSED.set(None); +} + +#[test] +fn many_update_calls_within_one_interval_give_the_controls_once() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + let report = run_in_app( + &mut s, + "#targetengine progress\nvar names = []; for (var n = 0; n < 500; n++) { names.push('a long list item name ' + n); } \ + var p = new Window('palette'); var list = p.add('listbox', undefined, names); var bar = p.add('progressbar', undefined, 0, 1000); \ + p.show(); for (var k = 1; k <= 1000; k++) { bar.value = k; p.update(); }", + ); + let calls = report["hostCalls"].as_u64().unwrap(); + assert!(calls < 1000, "an update() the app does not draw costs no host call: {calls}"); + let bar = s.script_palettes()[0].dialog.nodes[2].value; + assert_eq!(bar, 1000.0, "the palette shows the last value once the run ends"); + TEST_ELAPSED.set(None); +} + +#[test] +fn a_later_run_in_the_engine_changes_what_the_palette_shows() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + run(&mut s, "#targetengine tools\ngo.enabled = false; go.text = 'Wait';").unwrap(); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); + assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Wait"); + assert!(s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).is_err(), "a disabled button takes no click"); +} + +#[test] +fn a_handler_keeps_the_file_grants_of_the_script_that_showed_the_palette() { + let base = std::env::temp_dir().join(format!("vc-script-palette-grants-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("picked")).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + let data = base.join("picked/data.txt"); + std::fs::write(&data, "hello").unwrap(); + let path = serde_json::to_string(&data.to_string_lossy()).unwrap(); + let main = base.join("main/main.jsx"); + let source = format!( + "#targetengine grants\nif (typeof picked == 'undefined') {{ var picked = File.openDialog('p'); }} \ + var p = new Window('palette'); var b = p.add('button', undefined, 'Read'); \ + b.onClick = function () {{ var f = new File({path}); vc.log(f.open('r') ? f.read() : f.error); }}; p.show();" + ); + std::fs::write(&main, source).unwrap(); + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + for _ in 0..10_000 { + if s.script_picker().is_some() { + break; + } + assert!(s.script_pump().is_none(), "the run waits at its file dialog"); + } + let picked = data.to_string_lossy().into_owned(); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked], always: true })); + pump(&mut s).expect("the run ended").unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!(["hello"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn update_takes_eligible_events_past_deferred_events_in_scope_order() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine eligible\nvar p = new Window('palette'); var stopped = false; \ + var a = p.add('button', undefined, 'A'); var b = p.add('button', undefined, 'B'); \ + var c = p.add('button', undefined, 'C'); var cancel = p.add('button', undefined, 'Cancel'); \ + a.onClick = function () { vc.log('a'); }; b.onClick = function () { vc.log('b'); }; \ + c.onClick = function () { vc.log('c'); }; cancel.onClick = function () { stopped = true; vc.log('cancel'); }; p.show();", + ); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for control in 1..=4 { + let queued = if control % 2 == 1 { + crate::file_access::confine(Some(&roots), || s.script_palette_event(id, UiEvent::Click(control))) + } else { + crate::file_access::unconfined(|| s.script_palette_event(id, UiEvent::Click(control))) + }; + assert_eq!(queued, Ok(Waiting::Added)); + } + let report = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine eligible\nwhile (!stopped) p.update(); vc.log('stopped');")); + assert_eq!(report["log"], json!(["b", "cancel", "stopped"])); + assert_eq!(s.script_palette_events_waiting(), 2); + for expected in ["a", "c"] { + crate::file_access::unconfined(|| { + assert!(s.script_palette_start().unwrap().is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([expected])); + }); + } + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_change_does_not_take_the_place_of_a_waiting_change_given_in_another_scope() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine merge\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ + var b = p.add('button', undefined, 'B'); t.onChange = function () { vc.log('change ' + t.text); }; \ + b.onClick = function () { vc.log('click'); }; p.show();", + ); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + let change = |text: &str| UiEvent::Change(1, crate::script::UiValue::Text(text.into())); + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("x"))), Ok(Waiting::Added)); + crate::file_access::unconfined(|| { + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, change("y")), Ok(Waiting::Added), "the confined change keeps its own place"); + }); + let report = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine merge\np.update();")); + assert_eq!(report["log"], json!(["click", "change y"]), "the click stays before the later change of its scope"); + assert_eq!(s.script_palette_events_waiting(), 1); +} + +#[test] +fn a_change_does_not_merge_past_a_waiting_change_given_in_another_scope() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine merge\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ + t.onChange = function () { vc.log('change ' + t.text); }; p.show();", + ); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + let change = |text: &str| UiEvent::Change(1, crate::script::UiValue::Text(text.into())); + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("x"))), Ok(Waiting::Added)); + assert_eq!(crate::file_access::unconfined(|| s.script_palette_event(id, change("y"))), Ok(Waiting::Added)); + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("z"))), Ok(Waiting::Added)); + assert_eq!(s.script_palette_events_waiting(), 3); + let mut logs = Vec::new(); + crate::file_access::unconfined(|| { + while let Some(started) = s.script_palette_start() { + started.unwrap(); + logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); + } + }); + assert_eq!(logs, [json!(["change x"]), json!(["change y"]), json!(["change z"])]); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_click_does_not_take_a_place_ahead_of_a_change_that_waits_after_it() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine ahead\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ + var b = p.add('button', undefined, 'B'); t.onChange = function () { vc.log('change ' + t.text); }; \ + b.onClick = function () { vc.log('click ' + t.text); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Text("y".into()))), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added), "the click waits after the change"); + let report = run_in_app(&mut s, "#targetengine ahead\np.update();"); + assert_eq!(report["log"], json!(["click ", "change y", "click y"])); +} + +#[test] +fn repeated_clicks_and_closes_merge_after_the_last_change_of_their_palette() { + use crate::file_access::{AutomationRoots, confine, unconfined}; + + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for closing in [UiEvent::Click(1), UiEvent::Close] { + for confined_change in [false, true] { + let mut s = one_doc(); + run_in_app(&mut s, &format!("{TOOLS} p.onClose = function () {{ vc.log('close'); return false; }};")); + let id = only_palette(&s); + unconfined(|| assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Added))); + let change = UiEvent::Change(2, crate::script::UiValue::Text("typed".into())); + let queued = if confined_change { + confine(Some(&roots), || s.script_palette_event(id, change)) + } else { + unconfined(|| s.script_palette_event(id, change)) + }; + assert_eq!(queued, Ok(Waiting::Added)); + unconfined(|| { + assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Merged)); + }); + assert_eq!(s.script_palette_events_waiting(), 3); + let mut logs = Vec::new(); + unconfined(|| { + while let Some(started) = s.script_palette_start() { + started.unwrap(); + logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); + } + }); + let expected = if matches!(closing, UiEvent::Close) { + [json!(["close"]), json!(["change typed"]), json!(["close"])] + } else { + [json!(["click 1"]), json!(["change typed"]), json!(["click 2"])] + }; + assert_eq!(logs, expected); + } + } +} + +#[test] +fn update_takes_only_events_whose_roots_grant_what_the_run_s_roots_grant() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine contain\nvar p = new Window('palette'); var b = p.add('button', undefined, 'B'); \ + b.onClick = function () { vc.log('clicked'); }; p.show();", + ); + let id = only_palette(&s); + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap(); + let inner = base.join(format!("vc-script-palette-contain-{}", std::process::id())); + std::fs::create_dir_all(&inner).unwrap(); + let wide = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); + let same = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); + let narrow = crate::file_access::AutomationRoots::new(&[&inner], &[]).unwrap().unwrap(); + assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + let report = crate::file_access::confine(Some(&same), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); + assert_eq!(report["log"], json!(["clicked", "after"]), "the same roots made again: {report}"); + assert_eq!(s.script_palette_events_waiting(), 0); + // A run whose roots lie inside the event's roots would run the handler with less access than + // the event was given: the event waits for a run of its own. + assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + let report = crate::file_access::confine(Some(&narrow), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); + assert_eq!(report["log"], json!(["after"]), "roots inside the event's roots: {report}"); + assert_eq!(s.script_palette_events_waiting(), 1); + crate::file_access::confine(Some(&wide), || { + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!(["clicked"])); + }); + let _ = std::fs::remove_dir(inner); +} + +#[test] +fn a_handler_keeps_the_file_access_scope_of_the_request_that_gave_its_event() { + let base = std::env::temp_dir().join(format!("vc-script-palette-scope-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("other")).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + std::fs::write(base.join("main/data.txt"), "hello").unwrap(); + let main = base.join("main/main.jsx"); + let path = serde_json::to_string(&base.join("main/data.txt").to_string_lossy()).unwrap(); + std::fs::write( + &main, + format!( + "#targetengine scope\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Read'); var stop = false; \ + b.onClick = function () {{ stop = true; vc.log(new File({path}).exists); }}; p.show();" + ), + ) + .unwrap(); + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + pump(&mut s).expect("the run ended").unwrap(); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&base.join("other")], &[]).unwrap().unwrap(); + // A confined request gives the click; the frame that starts its run later is not confined. + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + // An update() in a later unconfined run of the engine leaves the confined click waiting. + let r = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine scope\np.update(); vc.log(stop);")); + assert_eq!(r["log"], json!([false]), "{r}"); + assert_eq!(s.script_palette_events_waiting(), 1); + crate::file_access::unconfined(|| { + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!([false]), "the handler reads inside the roots only"); + // A click the person gives, as the desktop app's pass gives it, goes to an update() at once. + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + let r = run_in_app(&mut s, "#targetengine scope\nstop = false; for (var k = 0; k < 1000 && !stop; k++) p.update(); vc.log(stop);"); + assert_eq!(r["log"].as_array().and_then(|l| l.last()), Some(&json!(true)), "the handler ran in the update() loop: {r}"); + }); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_failed_run_in_the_engine_still_changes_what_the_palette_shows() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + assert!(run(&mut s, "#targetengine tools\ngo.enabled = false; throw new Error('after');").is_err()); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); +} + +#[test] +fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine lists\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "#targetengine lists\nconfirm('Go?'); l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + let pick = UiEvent::Change(1, crate::script::UiValue::Index(Some(1))); + assert_eq!(s.script_palette_event(id, pick.clone()), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the change starts its run").is_ok()); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); + assert_eq!(s.script_palette_event(id, pick), Ok(Waiting::Added), "a change given after it is for the new items"); + assert!(s.script_palette_start().unwrap().is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); +} + +#[test] +fn a_list_change_for_an_item_a_run_removed_since_ends_its_run() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine shrink\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.removeAll(); l.add('item', 'a');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(1)))), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the change starts its run").is_ok()); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); + assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.add('item', 'c'); l.enabled = false;").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(0)))), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().is_none(), "a change of a list a run changed and disabled since is dropped"); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine places\nvar p = new Window('palette'); var g = p.add('group'); g.add('button', undefined, 'First'); \ + var last = p.add('button', undefined, 'Last'); last.onClick = function () { vc.log('last'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(3)); + let added = "#targetengine places\nconfirm('Go?'); g.add('button', undefined, 'Added').onClick = function () { vc.log('added'); };"; + assert_eq!(run(&mut s, added).unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(3)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(4), "the added button comes before Last in the list of controls"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["last"])); +} + +#[test] +fn a_waiting_click_on_a_button_a_handler_disabled_is_dropped() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine switches\nvar p = new Window('palette'); var off = p.add('button', undefined, 'Off'); \ + var go = p.add('button', undefined, 'Go'); off.onClick = function () { go.enabled = false; vc.log('off'); }; \ + go.onClick = function () { vc.log('go'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the first click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["off"])); + assert!(s.script_palette_start().is_none(), "the click on the button the handler disabled does not run"); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_palette_click_during_another_run_runs_after_it() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + let id = only_palette(&s); + assert_eq!(run(&mut s, "var a = confirm('Go?'); vc.log('busy done');").unwrap()["running"], true); + assert!(pump(&mut s).is_none(), "the run waits at its confirm"); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().is_none(), "the click waits while another run holds the lease"); + assert_eq!(s.script_palette_events_waiting(), 1); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["busy done"])); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["click 1"])); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn closing_a_palette_id_in_another_engine_keeps_that_palette_s_waiting_events() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + run_in_app(&mut s, "#targetengine other\nvar q = new Window('palette', 'Other'); q.add('button', undefined, 'B'); q.show();"); + let tools = s.script_palettes().iter().find(|p| p.engine == "tools").expect("the tools palette").id; + assert_eq!(s.script_palette_event(tools, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(!s.script_palettes.close(tools, "other"), "the other engine has no palette with that id"); + assert_eq!(s.script_palette_events_waiting(), 1, "the tools palette's click still waits"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["click 1"])); +} + +#[test] +fn double_clicks_while_queued_run_once() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Merged)); + let text = |t: &str| UiEvent::Change(2, crate::script::UiValue::Text(t.into())); + assert_eq!(s.script_palette_event(id, text("a")), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, text("ab")), Ok(Waiting::Merged), "a later change takes the waiting one's place"); + assert_eq!(s.script_palette_events_waiting(), 2); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + let mut logs = vec![]; + while let Some(started) = s.script_palette_start() { + started.unwrap(); + logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); + } + assert_eq!(logs, [json!(["click 1"]), json!(["change ab"])]); +} + +#[test] +fn a_list_change_takes_a_whole_float_as_its_item_index() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine floats\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let picked = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": 1.0})).unwrap(); + assert_eq!(picked["log"], json!(["b"])); + for value in [json!(0.5), json!(-1)] { + let given = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": value})); + assert!(given.is_err(), "{value}"); + } +} + +#[test] +fn with_nobody_to_ask_an_event_while_an_undo_group_is_open_is_refused_and_not_kept() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("undo group is open"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the refused click does not wait"); + s.execute("edit.undoGroup.end", &json!({})).unwrap(); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after the group ran"); +} + +#[test] +fn with_nobody_to_ask_an_event_whose_run_cannot_begin_ends_with_its_error_and_the_next_waits() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Change(2, crate::script::UiValue::Text("a".into()))), Ok(Waiting::Added)); + // The document has changes, and the session has nowhere to keep a recovery copy of it. + s.script_copy_first = true; + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("recovery copy"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 1, "the click after the change whose run could not begin still waits"); + s.script_copy_first = false; + assert_eq!(s.script_palette_run_waiting().unwrap()["log"], json!(["click 1"])); +} + +#[test] +fn with_nobody_to_ask_an_event_whose_open_edit_cannot_be_settled_ends_with_that_error_and_does_not_wait() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + SETTLE_FAILS.with(|f| f.set(true)); + let r = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})); + let waiting = s.script_palette_events_waiting(); + SETTLE_FAILS.with(|f| f.set(false)); + let e = r.unwrap_err().to_string(); + assert!(e.contains("could not be settled"), "{e}"); + assert_eq!(waiting, 0, "the refused click does not wait to run later"); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after it ran"); +} + +#[test] +fn a_waiting_event_whose_open_edit_cannot_be_settled_gives_the_app_that_error_and_keeps_waiting() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + SETTLE_FAILS.with(|f| f.set(true)); + let started = s.script_palette_start(); + SETTLE_FAILS.with(|f| f.set(false)); + let e = started.expect("the start gives the app its error").unwrap_err().to_string(); + assert!(e.contains("could not be settled"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 1, "the click waits for a later start"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); +} + +/// A palette in the engine `acts` whose button plays the action `Box` of the set `Set`, shown by +/// a run given that action, which draws a rectangle; and how many objects the document holds. +fn acts_palette(s: &mut Session, handler: &str) -> (u64, fn(&Session) -> usize) { + let actions = + json!([{"set": "Set", "name": "Box", "steps": [{"command": "shape.rectangle", "params": {"x": 40, "y": 0, "width": 5, "height": 5}}]}]); + let source = format!( + "#targetengine acts\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); b.onClick = function () {{ {handler} }}; p.show();" + ); + s.execute("script.run", &json!({"source": source, "name": "p.js", "actions": actions})).unwrap(); + fn objects(s: &Session) -> usize { + s.documents()[0].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() + } + (only_palette(s), objects) +} + +#[test] +fn a_handler_that_update_runs_plays_the_actions_of_the_run_that_showed_its_palette() { + let mut s = one_doc(); + let (id, objects) = acts_palette(&mut s, "app.doScript('Box', 'Set'); vc.log('played');"); + let before = objects(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + // A later run of the engine, given no actions, takes the click in its update(). + let log = + run(&mut s, "#targetengine acts\np.update(); try { app.doScript('Box', 'Set'); } catch (e) { vc.log(e.message); }").unwrap()["log"].clone(); + assert_eq!(log, json!(["played", "there is no action set “Set”"]), "the run's own call plays the run's own actions"); + assert_eq!(objects(&s), before + 1, "the handler's action drew its rectangle"); +} + +#[test] +fn after_a_handler_that_update_runs_throws_the_run_plays_its_own_actions() { + let mut s = one_doc(); + let (id, objects) = acts_palette(&mut s, "throw new Error('broken');"); + let before = objects(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + let log = run( + &mut s, + "#targetengine acts\ntry { p.update(); } catch (e) { vc.log(e.message); } \ + try { app.doScript('Box', 'Set'); } catch (e) { vc.log(e.message); }", + ) + .unwrap()["log"] + .clone(); + assert_eq!(log, json!(["broken", "there is no action set “Set”"])); + assert_eq!(objects(&s), before); +} + +#[test] +fn after_a_limit_ends_a_handler_that_update_runs_the_refresh_plays_the_run_s_own_actions() { + let mut s = one_doc(); + let (id, _) = acts_palette(&mut s, "started = true; for (;;) {}"); + // The getter records what it plays only once the handler has started, so a read before the + // click is taken does not count. + run( + &mut s, + "#targetengine acts\nvar started = false; var after = []; Object.defineProperty(p, 'text', {get: function () { \ + var played; try { app.doScript('Box', 'Set'); played = 'palette'; } catch (e) { played = 'own'; } \ + if (started) { after.push(played); } return 'P'; }});", + ) + .unwrap(); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(run(&mut s, "#targetengine acts\nstarted = false; after = []; p.update();").is_err(), "the handler's loop ends the run"); + let log = run(&mut s, "#targetengine acts\nvc.log(after.join(' '));").unwrap()["log"].clone(); + let after = log[0].as_str().unwrap_or_default(); + assert!(!after.is_empty(), "the palette is refreshed after the handler hit its limit: {log}"); + assert!(after.split(' ').all(|p| p == "own"), "the refresh after the limit plays the run's own actions, not the palette's: {log}"); +} + +#[test] +fn a_handler_plays_the_actions_of_the_run_that_showed_its_palette() { + let mut s = one_doc(); + let actions = + json!([{"set": "Set", "name": "Box", "steps": [{"command": "shape.rectangle", "params": {"x": 40, "y": 0, "width": 5, "height": 5}}]}]); + let source = "#targetengine acts\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { app.doScript('Box', 'Set'); vc.log('played'); }; p.show();"; + s.execute("script.run", &json!({"source": source, "name": "p.js", "actions": actions})).unwrap(); + let id = only_palette(&s); + let objects = |s: &Session| s.documents()[0].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::(); + let before = objects(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); + assert_eq!(clicked["log"], json!(["played"])); + assert_eq!(objects(&s), before + 1, "the action drew its rectangle"); +} + +#[test] +fn a_change_does_not_take_the_place_of_a_change_that_waits_before_a_click() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + let text = |t: &str| UiEvent::Change(2, crate::script::UiValue::Text(t.into())); + assert_eq!(s.script_palette_event(id, text("a")), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, text("b")), Ok(Waiting::Added), "the text typed after the click waits after it"); + assert_eq!(s.script_palette_event(id, text("c")), Ok(Waiting::Merged), "changes with no click between them still merge"); + let log = s.script_palette_run_waiting().unwrap()["log"].clone(); + assert_eq!(log, json!(["change c"])); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_point_change_a_palette_getter_makes_after_the_run_is_kept() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine points\nvar armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; app.activeDocument.pathItems[0].pathPoints[0].anchor = [3, 4]; } return 'P'; }}); \ + p.show();", + ) + .unwrap(); + let before = format!("{:?}", s.documents()[0].doc.layers); + run(&mut s, "#targetengine points\narmed = true;").unwrap(); + assert_ne!(format!("{:?}", s.documents()[0].doc.layers), before, "the getter's point change was written"); + let anchor = run(&mut s, "vc.log(app.activeDocument.pathItems[0].pathPoints[0].anchor);").unwrap()["log"].clone(); + assert_eq!(anchor, json!([[3, 4]])); +} + +#[test] +fn with_nobody_to_ask_an_event_that_replaces_a_waiting_one_answers_with_its_own_report() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine fields\nvar p = new Window('palette'); var one = p.add('edittext', undefined, ''); \ + var two = p.add('edittext', undefined, ''); one.onChange = function () { vc.log('change ' + one.text); }; \ + two.onChange = function () { vc.log('other ' + two.text); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let text = |c: usize, t: &str| UiEvent::Change(c, crate::script::UiValue::Text(t.into())); + assert_eq!(s.script_palette_event(id, text(1, "a")), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, text(2, "q")), Ok(Waiting::Added)); + // The new change takes the place of the first field's change, ahead of the second field's. + let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": "z"})).unwrap(); + assert_eq!(changed["log"], json!(["change z"]), "the report is the given change's, not the last run's"); + assert_eq!(s.script_palette_events_waiting(), 0, "the second field's change ran too"); + let texts = run(&mut s, "#targetengine fields\nvc.log(one.text + ' ' + two.text);").unwrap()["log"].clone(); + assert_eq!(texts, json!(["z q"])); +} + +#[test] +fn a_handler_s_error_keeps_its_file_when_a_palette_getter_throws_after_it() { + let base = std::env::temp_dir().join(format!("vc-script-palette-place-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + let first = base.join("first.jsx"); + std::fs::write( + &first, + "#targetengine places\nvar armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go');\n\ + Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }});\np.show();", + ) + .unwrap(); + let second = base.join("second.jsx"); + std::fs::write(&second, "#targetengine places\n\n\nb.onClick = function () { armed = true; throw new Error('handler'); };").unwrap(); + let mut s = one_doc(); + for file in [&first, &second] { + s.execute("script.run", &json!({"path": file.to_string_lossy()})).unwrap(); + } + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("handler"), "{e}"); + let report = s.script_report().unwrap(); + assert!(report["file"].as_str().is_some_and(|f| f.ends_with("second.jsx")), "{report}"); + assert_eq!(report["line"], 4, "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_palette_from_a_script_without_a_named_engine_is_refused() { + let mut s = one_doc(); + for source in ["", "#targetengine main\n"] { + let r = run(&mut s, &format!("{source}try {{ new Window('palette'); }} catch (e) {{ vc.log(e.message); }}")).unwrap(); + assert_eq!(r["log"], json!([PALETTE_NEEDS_ENGINE]), "{source:?}"); + } + assert!(s.script_palettes().is_empty()); +} + +#[test] +fn close_fires_on_close_and_frees_the_window() { + let mut s = one_doc(); + run(&mut s, &format!("{TOOLS} p.onClose = function () {{ vc.log('closing'); }};")).unwrap(); + let id = only_palette(&s); + let closed = s.execute("script.palette.event", &json!({"palette": id, "event": "close"})).unwrap(); + assert_eq!(closed["log"], json!(["closing"])); + assert!(s.script_palettes().is_empty(), "the close box freed the palette"); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains(&format!("there is no script palette {id}")), "{e}"); + + run(&mut s, TOOLS).unwrap(); + let r = + run(&mut s, "#targetengine tools\nvar asked = 0; p.onClose = function () { asked++; return asked > 1; }; p.close(); vc.log(asked);").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(s.script_palettes().len(), 1, "onClose returned false: the palette stays open"); + run(&mut s, "#targetengine tools\np.close();").unwrap(); + assert!(s.script_palettes().is_empty(), "close() freed the palette"); +} + +#[test] +fn update_on_a_removed_group_throws_an_error_the_script_catches_and_keeps_the_engine() { + let mut s = one_doc(); + let r = run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var g = p.add('group'); p.show(); p.remove(g); \ + try { g.update(); } catch (e) { vc.log(e.message); } vc.log('after');", + ) + .unwrap(); + assert_eq!(r["log"], json!(["update: the control was removed from its dialog", "after"]), "{r}"); + assert_eq!(s.script_palettes().len(), 1, "the engine and its palette stay"); +} + +#[test] +fn a_palette_still_takes_events_after_the_script_replaces_window() { + let mut s = one_doc(); + run(&mut s, &format!("{TOOLS} Window = function () {{}};")).unwrap(); + let id = only_palette(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"])); + run(&mut s, "#targetengine tools\nWindow = 5;").unwrap(); + let closed = s.execute("script.palette.event", &json!({"palette": id, "event": "close"})).unwrap(); + assert!(closed["ok"].as_bool().unwrap_or(false), "{closed}"); + assert!(s.script_palettes().is_empty(), "the close box reached the palette"); +} + +#[test] +fn closing_a_palette_whose_visible_is_read_only_still_closes_it() { + let mut s = one_doc(); + let r = run( + &mut s, + &format!( + "{TOOLS} Object.defineProperty(p, 'visible', {{value: true, writable: false}}); try {{ p.close(); }} catch (e) {{ vc.log(e.name); }}" + ), + ) + .unwrap(); + assert!(s.script_palettes().is_empty(), "the host closed the palette: {r}"); +} + +#[test] +fn dropping_the_engine_closes_its_palettes() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + run_in_app(&mut s, "#targetengine other\nnew Window('palette').show();"); + let id = s.script_palettes()[0].id; + s.script_palette_event(id, UiEvent::Click(1)).unwrap(); + s.execute("script.engine.drop", &json!({"name": "tools"})).unwrap(); + let left: Vec<&str> = s.script_palettes().iter().map(|p| p.engine.as_str()).collect(); + assert_eq!(left, ["other"]); + assert_eq!(s.script_palette_events_waiting(), 0, "the dropped palette's event no longer waits"); + assert!(s.script_palette_start().is_none()); +} + +#[test] +fn an_erroring_handler_ends_its_run_and_leaves_the_palette_open() { + let mut s = one_doc(); + let before = s.documents()[0].history.undo.len(); + run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); throw new Error('broken'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let art = format!("{:?}", s.documents()[0].doc.layers); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("broken"), "{e}"); + assert_eq!(format!("{:?}", s.documents()[0].doc.layers), art, "the failed handler's rectangle was rolled back"); + assert_eq!(s.documents()[0].history.undo.len(), before, "the failed handler adds no undo step"); + assert_eq!(only_palette(&s), id); +} + +#[test] +fn a_dialog_in_a_handler_throws_in_the_app() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { try { confirm('Sure?'); } catch (e) { vc.log('confirm'); } \ + try { var d = new Window('dialog'); d.add('button', undefined, 'OK'); d.show(); } catch (e) { vc.log('dialog'); } }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("no dialog waits").unwrap()["log"], json!(["confirm", "dialog"])); + assert_eq!(only_palette(&s), id); +} + +#[test] +fn a_handler_with_nobody_to_ask_ends_at_its_dialog() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); p.add('button', undefined, 'Go').onClick = function () { alert('hi'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("no answer left"), "{e}"); + assert_eq!(only_palette(&s), id, "the palette stays open"); +} + +#[test] +fn palettes_and_waiting_events_have_limits() { + let mut s = one_doc(); + let r = run( + &mut s, + "#targetengine many\nfor (var i = 0; i < 40; i++) { try { new Window('palette').show(); } catch (e) { vc.log([i, e.name]); break; } }", + ) + .unwrap(); + assert_eq!(r["log"], json!([[MAX_PALETTES, "RangeError"]])); + s.execute("script.engine.drop", &json!({"name": "many"})).unwrap(); + assert!(s.script_palettes().is_empty()); + + run_in_app( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); for (var i = 0; i < 70; i++) p.add('button', undefined, 'B' + i); p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + for c in 1..=MAX_WAITING { + assert_eq!(s.script_palette_event(id, UiEvent::Click(c)), Ok(Waiting::Added)); + } + let e = s.script_palette_event(id, UiEvent::Click(MAX_WAITING + 1)).unwrap_err(); + assert!(e.contains("this one was not kept"), "{e}"); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Merged), "a waiting control still takes a click"); +} diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 1c15b3e9f0..624a108d1e 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -389,6 +389,39 @@ fn file_print_max_pages_composes_only_what_fits() { let _ = std::fs::remove_dir_all(base); } +/// A job past `maxPages` is turned away before its raster effects are flattened. +#[test] +fn file_print_max_pages_turns_a_job_away_before_raster_effects_are_flattened() { + use crate::cmd::rasterfx::FLATTENED; + let base = folder("max-pages-raster"); + let mut s = session(&base); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow"})).unwrap(); + let before = FLATTENED.with(std::cell::Cell::get); + let r = s.execute("file.print", &json!({"maxPages": 5, "settings": {"copies": 3}})).unwrap(); + assert_eq!((&r["pages"], r.get("dataBase64").is_none()), (&json!(6), true), "{r}"); + assert_eq!(FLATTENED.with(std::cell::Cell::get), before, "nothing was flattened"); + let r = s.execute("file.print", &json!({"maxPages": 6, "settings": {"copies": 3}})).unwrap(); + assert!(r["dataBase64"].is_string(), "{r}"); + assert!(FLATTENED.with(std::cell::Cell::get) > before, "a job that fits is flattened"); + let _ = std::fs::remove_dir_all(base); +} + +/// A job past the page limit throws before its raster effects are flattened. +#[test] +fn file_print_max_pages_returns_a_page_cap_error_before_raster_effects_are_flattened() { + use crate::cmd::rasterfx::FLATTENED; + let base = folder("max-pages-raster-cap"); + let mut s = session(&base); + s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 3})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow"})).unwrap(); + let before = FLATTENED.with(std::cell::Cell::get); + let e = s.execute("file.print", &json!({"maxPages": 5, "settings": {"copies": 700}})).unwrap_err().to_string(); + assert!(e.contains("more than 2000 pages"), "{e}"); + assert_eq!(FLATTENED.with(std::cell::Cell::get), before, "nothing was flattened"); + let _ = std::fs::remove_dir_all(base); +} + /// Bad values throw when they are assigned, and nothing prints. #[test] fn print_options_refuse_bad_values() { @@ -589,6 +622,94 @@ fn assigned_job_and_scale_options_apply_over_the_saved_settings() { let _ = std::fs::remove_dir_all(base); } +/// Each option group prints the PostScript `file.print` writes for the settings it maps to, and +/// each of those settings changes the file. +#[test] +fn option_groups_print_what_their_settings_print() { + let base = folder("groups"); + let mut s = session(&base); + // A red rectangle whose fill overprints, printed through a CMYK printer profile: the intent + // decides its inks and the overprint option whether it keeps overprinting. + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("attributes.set", &json!({"overprintFill": true})).unwrap(); + let profile = vectorcraft_color::cms::GENERIC_CMYK; + let saved = + json!({"media": "letter", "autoRotate": false, "orientation": "portrait", "artboards": "range", "range": "1", "color": {"profile": profile}}); + s.execute("print.setup", &json!({"settings": saved})).unwrap(); + let dir = data_folder(&mut s, &base); + // The jobs print to PostScript, whose only line that depends on the clock is its + // `%%CreationDate` comment. + let undated = |path: &Path| { + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.starts_with("%!PS"), "{}: {}", path.display(), &text[..text.len().min(40)]); + text.lines().filter(|l| !l.starts_with("%%CreationDate:")).collect::>().join("\n") + }; + s.execute("file.print", &json!({"format": "postscript", "path": dir.join("plain.ps").to_string_lossy()})).unwrap(); + let plain = undated(&dir.join("plain.ps")); + let mut wrong = Vec::new(); + let cases = [ + ("o.flattenerOptions.overprint = PDFOverprint.DISCARDPDFOVERPRINT;", json!({"advanced": {"overprints": "discard"}})), + ( + "o.pageMarksOptions.pageMarksType = PageMarksTypes.Japanese; o.pageMarksOptions.trimMarks = true;", + json!({"marks": {"kind": "japanese", "trim": true}}), + ), + ("o.coordinateOptions.orientation = PrintOrientation.LANDSCAPE;", json!({"autoRotate": false, "orientation": "landscape"})), + ("o.colorSeparationOptions.colorSeparationMode = PrintColorSeparationMode.HOSTBASEDSEPARATION;", json!({"output": {"mode": "separations"}})), + ( + "var m = o.pageMarksOptions; m.trimMarks = true; m.registrationMarks = true; m.trimMarksWeight = 1;", + json!({"marks": {"trim": true, "registration": true, "weight": 1.0}}), + ), + ("o.paperOptions.width = 400; o.paperOptions.height = 300;", json!({"media": "custom", "width": 400.0, "height": 300.0})), + ("o.paperOptions.transverse = true;", json!({"transverse": true})), + ("o.coordinateOptions.emulsion = true;", json!({"output": {"emulsion": "down"}})), + ("o.postScriptOptions.negativePrinting = true;", json!({"output": {"image": "negative"}})), + ("o.coordinateOptions.position = PrintPosition.TRANSLATETOPLEFT;", json!({"placement": {"origin": "topLeft"}})), + ]; + for (i, (body, settings)) in cases.iter().enumerate() { + let [want, got] = ["want", "got"].map(|name| dir.join(format!("{name}{i}.ps"))); + s.execute("file.print", &json!({"format": "postscript", "settings": settings, "path": want.to_string_lossy()})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); {body} app.activeDocument.print(o);", + quoted(&got) + ), + ); + let want = undated(&want); + if want == plain { + wrong.push(format!("{i}: {settings} does not change the printed file")); + } + if undated(&got) != want { + wrong.push(format!("{i}: {body} does not print as {settings}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + let page_count = |path: &Path| undated(path).lines().filter(|l| l.starts_with("%%Page:")).count(); + assert!(page_count(&dir.join("want3.ps")) > page_count(&dir.join("plain.ps")), "a page for each ink"); + // PostScript leaves the printer profile out, so the intent is compared in PDF, by the art the + // printed file opens as, which leaves out the file's date. + let art = |name: &str| { + let doc = vectorcraft_pdf::import(&std::fs::read(dir.join(name)).unwrap()).unwrap(); + serde_json::to_string(&doc.layers).unwrap() + }; + let perceptual = json!({"color": {"intent": "perceptual"}}); + s.execute("file.print", &json!({"path": dir.join("plain.pdf").to_string_lossy()})).unwrap(); + s.execute("file.print", &json!({"settings": perceptual, "path": dir.join("want.pdf").to_string_lossy()})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\ + o.colorManagementOptions.intent = PrintColorIntent.PERCEPTUALINTENT; app.activeDocument.print(o);", + quoted(&dir.join("got.pdf")) + ), + ); + assert!(art("want.pdf") != art("plain.pdf"), "the intent changes the inks"); + assert_eq!(art("got.pdf"), art("want.pdf"), "PrintColorIntent.PERCEPTUALINTENT prints as {perceptual}"); + let _ = std::fs::remove_dir_all(base); +} + /// The format follows the name `jobOptions.file` gives, not the extension of the file a link in the /// granted folder leads to. #[cfg(unix)] @@ -661,6 +782,7 @@ fn print_refuses_profile_paper_and_blank_preset_names() { ("c.name = 'No Such Profile';", profile), ("c.colorProfileMode = PrintColorProfile.SOURCEPROFILE; c.name = '../cmyk.icc';", profile), ("c.name = ' ';", "PrintColorManagementOptions.name must name a color profile"), + ("c.colorProfileMode = PrintColorProfile.CUSTOMPROFILE;", "PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE"), ("p.name = '../letter';", paper), ("p.name = 'let\\u0007ter';", paper), ("p.name = '\\tA4\\n';", paper), diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs new file mode 100644 index 0000000000..9e0d53c696 --- /dev/null +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -0,0 +1,1069 @@ +//! Rasterizing and capturing art from a script: `Document.rasterize`, `Document.imageCapture`, +//! `RasterizeOptions`, `ImageCaptureOptions` and `object.rasterize` with `ids` and `clipBounds`. + +use std::path::{Path, PathBuf}; + +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"})) +} + +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() +} + +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// Fills the objects `ids` with `color` and takes their strokes off. +fn paint(s: &mut Session, ids: &[NodeId], color: &str) { + let ids: Vec = ids.iter().map(|i| i.0).collect(); + s.execute("paint.setFill", &json!({"ids": ids, "color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": ids, "none": true})).unwrap(); +} + +/// A 400 × 300 pt document with two rectangles without strokes: `a` at (10, 20) 30 × 40 pt, `b` at +/// (100, 100) 50 × 50 pt. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + paint(&mut s, &[a, b], "#ff0000"); + s.execute("select.none", &json!({})).unwrap(); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The size of each embedded image of the active document, in pixels. +fn images(s: &Session) -> Vec<(u32, u32)> { + let mut out = Vec::new(); + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(i) = &n.kind { + out.push((i.width, i.height)); + } + }); + out +} + +/// A script that selects `b` and rasterizes `a` (the second and first page items: the list starts +/// with the topmost object). +const RASTERIZE_A: &str = "var d = app.activeDocument, a = d.pageItems[1], b = d.pageItems[0]; b.name = 'b'; d.selection = [b];"; + +#[test] +fn script_rasterize_explicit_sources_preserves_selection() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + let out = log( + &mut s, + &format!( + "{RASTERIZE_A} var r = d.rasterize(a); vc.log(r.typename); vc.log(d.selection.length); vc.log(d.selection[0].name === 'b');\ + try {{ a.name; }} catch (e) {{ vc.log(e.message); }} vc.log(d.pageItems.length);" + ), + ); + assert_eq!(out, [json!("RasterItem"), json!(1), json!(true), json!("Stale page item"), json!(2)]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none(), "the source art is replaced"); + assert_eq!(st.selection.objects, vec![b], "the selection stays as it was"); + assert_eq!(undo_steps(&s), undo + 1, "one undo step"); +} + +#[test] +fn script_rasterize_defaults_override_document_raster_settings() { + let (mut s, ..) = doc(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 72, "background": "transparent"})).unwrap(); + log(&mut s, &format!("{RASTERIZE_A} d.rasterize(a);")); + // 30 × 40 pt at 300 ppi, snapped out to whole pixels (at 72 ppi it would be about 30 × 40). + let [(w, h)] = images(&s)[..] else { panic!("one image: {:?}", images(&s)) }; + assert!((125..=126).contains(&w) && (167..=168).contains(&h), "300 ppi, the help page's default, not the document's 72: {w} × {h}"); + let (mut s, ..) = doc(); + log(&mut s, &format!("{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 144; o.padding = 5; d.rasterize(a, undefined, o);")); + assert_eq!(images(&s), vec![(80, 100)], "40 × 50 pt with the padding, at 144 ppi"); +} + +#[test] +fn script_rasterize_options_have_the_help_page_defaults() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var o = new RasterizeOptions(); vc.log([o.typename, o.antiAliasingMethod, o.backgroundBlack, o.clippingMask, o.colorModel, \ + o.convertSpotColors, o.convertTextToOutlines, o.includeLayers, o.padding, o.resolution, o.transparency]);\ + var c = new ImageCaptureOptions(); vc.log([c.typename, c.antiAliasing, c.matte, c.matteColor.red, c.matteColor.green, \ + c.matteColor.blue, c.resolution, c.transparency]); vc.log([AntiAliasingMethod.TYPEOPTIMIZED, RasterizationColorModel.BITMAP]);", + ); + let rasterize = json!([ + "RasterizeOptions", + "AntiAliasingMethod.ARTOPTIMIZED", + false, + false, + "RasterizationColorModel.DEFAULTCOLORMODEL", + false, + false, + false, + 0, + 300, + false + ]); + assert_eq!(out[0], rasterize); + assert_eq!(out[1], json!(["ImageCaptureOptions", false, false, 255, 255, 255, 150, false])); + assert_eq!(out[2], json!(["AntiAliasingMethod.TYPEOPTIMIZED", "RasterizationColorModel.BITMAP"])); +} + +#[test] +fn script_rasterize_clip_mask_returns_image_child() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.clippingMask = true; var r = d.rasterize([a], null, o); vc.log([r.typename, r.parent.typename]);" + ), + ); + assert_eq!(out, [json!(["RasterItem", "GroupItem"])]); +} + +#[test] +fn script_rasterize_clip_bounds_cut_the_image() { + let (mut s, ..) = doc(); + // The left half of `a`: x 10 to 25, and its whole height (y 280 to 240, Y up). + log(&mut s, &format!("{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 72; d.rasterize(a, [10, 280, 25, 240], o);")); + assert_eq!(images(&s), vec![(15, 40)]); +} + +/// A clip rectangle that ends partway through a pixel keeps partial coverage in the image's last +/// column and row. +#[test] +fn script_rasterize_fractional_clip_bounds_stay_inside_the_rectangle() { + let (mut s, ..) = doc(); + log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 72; o.transparency = true; d.rasterize(a, [10, 280, 25.5, 240.5], o);" + ), + ); + assert_eq!(images(&s), vec![(16, 40)]); + let st = s.active().unwrap(); + let blob = st.doc.images.values().next().unwrap(); + let pixels = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + assert_eq!(pixels.get_pixel(14, 20)[3], 255); + assert!((1..255).contains(&pixels.get_pixel(15, 20)[3]), "the last column keeps only its in-bounds coverage"); + assert_eq!(pixels.get_pixel(7, 38)[3], 255); + assert!((1..255).contains(&pixels.get_pixel(7, 39)[3]), "the last row keeps only its in-bounds coverage"); +} + +/// A clip rectangle from a fractional origin that spans whole pixels keeps every one of them, +/// though the subtraction of its edges is not exact. +#[test] +fn script_rasterize_clip_bounds_from_a_fractional_origin_keep_whole_pixels() { + for (left, right, width, partial) in [(10.4, 10.7, 3, false), (10.1, 10.4, 3, false), (10.4, 10.75, 4, true)] { + let (mut s, ..) = doc(); + log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 720; o.transparency = true; d.rasterize(a, [{left}, 280, {right}, 240], o);" + ), + ); + assert_eq!(images(&s), vec![(width, 400)]); + let st = s.active().unwrap(); + let blob = st.doc.images.values().next().unwrap(); + let pixels = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + let alpha = pixels.get_pixel(width - 1, 200)[3]; + if partial { + assert!((1..255).contains(&alpha), "the last column keeps only its in-bounds coverage"); + } else { + assert_eq!(alpha, 255, "the whole boundary pixel stays opaque"); + } + } +} + +#[test] +fn script_rasterize_rejects_a_clipping_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The clipping path is `b`, the topmost of the two. + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [b.0]})).unwrap_err().to_string(); + assert!(e.contains("is a clipping path"), "{e}"); + assert_eq!(undo_steps(&s), undo, "a refused clipping path adds no undo step"); + s.execute("object.rasterize", &json!({"ids": [a.0]})).unwrap(); +} + +/// The new `RasterItem` is bound to the image's exact id, also for an id above 2^53, which a +/// script number does not hold exactly. +#[test] +fn script_rasterize_binds_an_image_id_above_two_to_the_53() { + let (mut s, a, _) = doc(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log(&mut s, &format!("{RASTERIZE_A} var r = d.rasterize(a); vc.log(r.typename); r.name = 'img';")); + assert_eq!(out, [json!("RasterItem")]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none(), "the source art is replaced"); + let mut named = Vec::new(); + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + named.push((n.id, n.name.clone())); + } + }); + assert_eq!(named.len(), 1, "{named:?}"); + assert!(named[0].0.0 > 1u64 << 53, "{named:?}"); + assert_eq!(named[0].1.as_deref(), Some("img"), "the item names the image itself"); +} + +/// The image takes the place of the last object, so objects in different clipping contexts are +/// refused before anything changes. +#[test] +fn script_rasterize_rejects_sources_clipped_differently() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 20.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [c.0, a.0]})).unwrap_err().to_string(); + assert!(e.contains("is clipped differently"), "{e}"); + assert!(*before == *s.active().unwrap().doc, "a refused call leaves the document as it was"); + assert_eq!(undo_steps(&s), undo); + assert!(s.active().unwrap().doc.node(c).is_some(), "the unclipped object stays"); +} + +#[test] +fn script_rasterize_disposes_several_sources_in_one_step() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + let out = log(&mut s, "var d = app.activeDocument; var r = d.rasterize([d.pageItems[1], d.pageItems[0]]); vc.log(d.pageItems.length);"); + assert_eq!(out, [json!(1)]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none() && st.doc.node(b).is_none()); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// Each bad call throws and leaves the document as it was, with no undo step. +fn refused(s: &mut Session, source: &str, message: &str) { + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(s); + let e = failure(s, source); + assert!(e.contains(message), "{source}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc) || *before == *s.active().unwrap().doc, "{source} changed the document"); + assert_eq!(undo_steps(s), undo, "{source} added an undo step"); +} + +#[test] +fn script_rasterize_rejects_other_documents_art() { + let (mut s, ..) = doc(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + rect(&mut s, 0.0, 0.0, 10.0, 10.0); + refused(&mut s, "app.documents[0].rasterize(app.documents[1].pageItems[0]);", "The source art must be in this document"); +} + +#[test] +fn script_rasterize_rejects_listed_twice() { + let (mut s, ..) = doc(); + refused(&mut s, "var d = app.activeDocument; d.rasterize([d.pageItems[0], d.pageItems[0]]);", "listed twice"); +} + +#[test] +fn script_rasterize_rejects_locked_art() { + let (mut s, ..) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].locked = true;"); + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); +} + +#[test] +fn script_rasterize_rejects_groups_with_locked_descendants() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let inner = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [inner, c.0]})).unwrap(); + let outer = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": a.0, "locked": true})).unwrap(); + for id in [inner, outer] { + let before = s.active().unwrap().doc.clone(); + let selection = s.active().unwrap().selection.objects.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [id]})).unwrap_err().to_string(); + assert!(e.contains("locked"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(s.active().unwrap().selection.objects, selection); + assert_eq!(undo_steps(&s), undo); + } + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); + s.execute("object.setProps", &json!({"id": a.0, "locked": false})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [outer], "ppi": 72})).unwrap(); +} + +#[test] +fn rasterize_rejects_explicit_hidden_art() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": a.0, "visible": false})).unwrap(); + s.execute("object.setProps", &json!({"id": group, "visible": false})).unwrap(); + for id in [a.0, b.0] { + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [id]})).unwrap_err().to_string(); + assert!(e.contains("hidden"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(undo_steps(&s), undo); + } + s.execute("object.setProps", &json!({"id": a.0, "visible": true})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [a.0], "ppi": 72})).unwrap(); +} + +#[test] +fn rasterize_rejects_explicit_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [a.0, b.0]})).unwrap_err().to_string(); + assert!(e.contains("locked artboard"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(undo_steps(&s), undo); + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked artboard"); + s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [a.0, b.0]})).unwrap(); +} + +#[test] +fn script_rasterize_logs_a_missing_image_warning() { + let (mut s, ..) = doc(); + let id = super::menucmds::place_undecodable_png(&mut s); + let out = run(&mut s, "var d = app.activeDocument; vc.log(d.rasterize(d.pageItems[0]).typename);").unwrap(); + let lines = out["console"]["lines"].as_array().unwrap(); + assert!(lines.iter().filter_map(Value::as_str).any(|s| s.starts_with("rasterize: ") && s.contains("couldn't be decoded")), "{out}"); + assert_eq!(out["log"], json!(["RasterItem"])); + assert!(s.active().unwrap().doc.node(id).is_none()); +} + +#[test] +fn image_capture_logs_a_missing_image_warning() { + let base = folder("warning"); + let (mut s, dir) = capture_doc(&base); + let id = super::menucmds::place_undecodable_png(&mut s); + let before = s.active().unwrap().doc.clone(); + let out = run_file(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join("capture.png")))).unwrap(); + let lines = out["console"]["lines"].as_array().unwrap(); + assert!(lines.iter().filter_map(Value::as_str).any(|s| s.starts_with("imageCapture: ") && s.contains("couldn't be decoded")), "{out}"); + assert!(dir.join("capture.png").is_file()); + assert!(s.active().unwrap().doc.node(id).is_some()); + assert_eq!(*s.active().unwrap().doc, *before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_rasterize_rejects_art_inside_listed_art() { + let (mut s, a, b) = doc(); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + refused(&mut s, "var d = app.activeDocument; d.rasterize([d.pageItems[0], d.pageItems[1]]);", "which is listed too"); +} + +#[test] +fn script_rasterize_rejects_a_compound_path_member() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The page items are the compound path, then its two paths. + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[1]);", "part of a compound path"); + let out = log(&mut s, "var d = app.activeDocument; vc.log(d.rasterize(d.pageItems[0]).typename);"); + assert_eq!(out, [json!("RasterItem")], "the compound path itself is rasterized"); +} + +#[test] +fn script_rasterize_rejects_stale_and_missing_sources() { + let (mut s, ..) = doc(); + refused(&mut s, "var d = app.activeDocument, a = d.pageItems[0]; a.remove(); d.rasterize(a);", "Stale page item"); + refused(&mut s, "app.activeDocument.rasterize([]);", "at least one page item"); + refused(&mut s, "app.activeDocument.rasterize();", "needs the source art"); + refused(&mut s, "app.activeDocument.rasterize(5);", "not a page item"); + let many = "var d = app.activeDocument, l = []; for (var i = 0; i < 10001; i++) l.push(d.pageItems[0]); d.rasterize(l);"; + refused(&mut s, many, "at most 10000 objects"); +} + +#[test] +fn script_rasterize_rejects_bad_options() { + let (mut s, ..) = doc(); + let cases = [ + ("var o = new RasterizeOptions(); o.resolution = 71;", "from 72 to 2400"), + ("var o = new RasterizeOptions(); o.resolution = 2401;", "from 72 to 2400"), + ("var o = new RasterizeOptions(); o.resolution = NaN;", "finite number"), + ("var o = new RasterizeOptions(); o.resolution = Infinity;", "finite number"), + ("var o = new RasterizeOptions(); o.padding = 1001;", "from 0 to 1000"), + ("var o = new RasterizeOptions(); o.padding = -Infinity;", "finite number"), + ("var o = new RasterizeOptions(); o.antiAliasingMethod = 'smooth';", "AntiAliasingMethod value"), + ("var o = new RasterizeOptions(); o.colorModel = AntiAliasingMethod.None;", "RasterizationColorModel value"), + ("var o = new RasterizeOptions(); o.clippingMask = 1;", "true or false"), + ("var o = new RasterizeOptions(); o.convertTextToOutlines = true;", "not available yet"), + ("var o = new RasterizeOptions(); o.includeLayers = true;", "not available yet"), + ("var o = new RasterizeOptions(); o.convertSpotColors = true;", "not available yet"), + ("var o = new ImageCaptureOptions();", "RasterizeOptions object"), + ("var o = {resolution: 300};", "RasterizeOptions object"), + ]; + for (options, message) in cases { + refused(&mut s, &format!("var d = app.activeDocument; {options} d.rasterize(d.pageItems[0], undefined, o);"), message); + } +} + +#[test] +fn script_rasterize_rejects_bad_clip_bounds() { + let (mut s, ..) = doc(); + let cases = [ + ("[25, 280, 10, 240]", "right edge right of its left edge"), + ("[10, 240, 25, 280]", "bottom edge below its top edge"), + ("[10, 280, 25]", "four numbers"), + ("[10, 280, 25, NaN]", "finite number"), + ("[10, 280, 25, 1e300]", "outside the canvas"), + ("[300, 20, 350, 10]", "does not overlap the art"), + ("'all'", "four numbers"), + ]; + for (bounds, message) in cases { + refused(&mut s, &format!("var d = app.activeDocument; d.rasterize(d.pageItems[1], {bounds});"), message); + } + // `a` spans x 10 to 40: a rectangle at x 42 to 48 reaches only the 10 pt padding around it. + refused( + &mut s, + "var d = app.activeDocument, o = new RasterizeOptions(); o.padding = 10; d.rasterize(d.pageItems[1], [42, 280, 48, 240], o);", + "does not overlap the art", + ); +} + +#[test] +fn object_rasterize_refuses_clip_bounds_between_the_sources() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + // The rectangle lies inside the box around `a` and `b` but reaches neither of them. + let e = s.execute("object.rasterize", &json!({"ids": [a.0, b.0], "clipBounds": [55, 45, 65, 55]})).unwrap_err().to_string(); + assert!(e.contains("does not overlap the art"), "{e}"); + assert_eq!(undo_steps(&s), undo, "no edit"); + assert_eq!(images(&s), Vec::<(u32, u32)>::new()); + // A rectangle that reaches only `a` is still accepted. + s.execute("object.rasterize", &json!({"ids": [a.0, b.0], "clipBounds": [30, 30, 65, 55]})).unwrap(); + assert_eq!(images(&s).len(), 1); +} + +#[test] +fn script_rasterize_rejects_an_image_past_the_size_limit() { + let (mut s, ..) = doc(); + let source = "var d = app.activeDocument, b = d.pageItems[0]; b.width = 3000; b.height = 3000; var o = new RasterizeOptions(); o.resolution = 2400; d.rasterize(b, undefined, o);"; + let e = failure(&mut s, source); + assert!(e.contains("too large"), "{e}"); + assert_eq!(images(&s), Vec::<(u32, u32)>::new()); +} + +#[test] +fn object_rasterize_with_ids_keeps_the_selection_and_names_the_image() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let r = s.execute("object.rasterize", &json!({"ids": [a.0], "ppi": 72, "clippingMask": true})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.selection.objects, vec![b]); + let (id, image) = (NodeId(r["id"].as_u64().unwrap()), NodeId(r["imageId"].as_u64().unwrap())); + assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Group { .. })); + assert!(matches!(st.doc.node(image).unwrap().kind, NodeKind::Image(_))); + assert_eq!(st.doc.parent_of(image), Some(id)); + let r = s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + assert_eq!(r["id"], r["imageId"], "without a clip group the image is the new object"); + assert_eq!(s.active().unwrap().selection.objects, vec![NodeId(r["id"].as_u64().unwrap())], "the selection is rasterized as before"); +} + +// ---- imageCapture ---- + +const DENIED: &str = "Script file access denied"; + +/// A fresh folder for test `name`, by its real path, with `main` for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-capture-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// [`doc`] in a session whose scripts keep their data folders in `base`, and the data folder, where +/// scripts may write. +fn capture_doc(base: &Path) -> (Session, PathBuf) { + let (mut s, ..) = doc(); + s.attach_script_data(base.join("settings/Script Data")); + let dir = PathBuf::from(script(&mut s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()); + (s, dir) +} + +/// Runs `main/main.jsx` in `base` with the text `text`. +fn run_file(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + // Reading `Folder.userData` makes the data folder, where the script may write. + std::fs::write(&main, format!("Folder.userData; {text}").as_bytes()).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn script(s: &mut Session, base: &Path, text: &str) -> Vec { + run_file(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].as_array().cloned().unwrap_or_default() +} + +fn file_failure(s: &mut Session, base: &Path, text: &str) -> String { + run_file(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +fn quoted(p: &Path) -> String { + serde_json::to_string(&p.to_string_lossy()).unwrap() +} + +/// The PNG at `path`, decoded by the `image` crate, as RGBA. +fn png(path: &Path) -> image::RgbaImage { + let bytes = std::fs::read(path).unwrap(); + assert!(bytes.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG signature"); + image::load_from_memory_with_format(&bytes, image::ImageFormat::Png).unwrap().to_rgba8() +} + +#[test] +fn image_capture_whole_artwork_including_pasteboard() { + let base = folder("whole"); + let (mut s, dir) = capture_doc(&base); + // A third rectangle off the artboard, left of it: the art spans x -90 to 150 and y 20 to 150. + let c = rect(&mut s, -90.0, 30.0, 20.0, 20.0); + paint(&mut s, &[c], "#0000ff"); + // The capture's own 150 ppi applies, not the document's raster effects resolution. + s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap(); + let undo = undo_steps(&s); + let out = script( + &mut s, + &base, + &format!("var r = app.activeDocument.imageCapture(new File({})); vc.log(r === undefined);", quoted(&dir.join("all.png"))), + ); + assert_eq!(out, [json!(true)]); + let img = png(&dir.join("all.png")); + assert_eq!((img.width(), img.height()), (500, 271), "240 × 130 pt at 150 ppi"); + assert_eq!(img.get_pixel(5, 30).0, [0, 0, 255, 255], "the art off the artboard is there"); + assert_eq!(img.get_pixel(499, 0).0, [255, 255, 255, 255], "white where there is no art"); + assert_eq!(undo_steps(&s), undo, "a capture changes nothing in the document"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_capture_exact_clip_bounds_and_matte() { + let base = folder("clip"); + let (mut s, dir) = capture_doc(&base); + // x 0 to 50 and y 300 to 250 (Y up): the top-left corner of the artboard, with `a` in it. + let f = |n: &str| quoted(&dir.join(n)); + let source = format!( + "var d = app.activeDocument, o = new ImageCaptureOptions(); o.resolution = 72;\ + d.imageCapture(new File({}), [0, 300, 50, 250], o);\ + o.matte = true; o.matteColor = {{red: 0, green: 128, blue: 0}}; d.imageCapture(new File({}), [0, 300, 50, 250], o);\ + o.transparency = true; d.imageCapture(new File({}), [0, 300, 50, 250], o);", + f("white.png"), + f("matte.png"), + f("clear.png") + ); + script(&mut s, &base, &source); + for (name, blank) in [("white.png", [255, 255, 255, 255]), ("matte.png", [0, 128, 0, 255]), ("clear.png", [0, 0, 0, 0])] { + let img = png(&dir.join(name)); + assert_eq!((img.width(), img.height()), (50, 50), "{name}"); + assert_eq!(img.get_pixel(2, 2).0, blank, "{name}: the area without art"); + assert_eq!(img.get_pixel(20, 30).0, [255, 0, 0, 255], "{name}: the art"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// `imageCapture` rounds fractional clip dimensions to the nearest whole pixel, as +/// `document.export` does, where `rasterize` rounds them up. +#[test] +fn image_capture_rounds_fractional_clip_dimensions_to_the_nearest_pixel() { + let base = folder("nearest"); + let (mut s, dir) = capture_doc(&base); + let source = format!( + "var o = new ImageCaptureOptions(); o.resolution = 72; app.activeDocument.imageCapture(new File({}), [0, 300, 10.25, 289.75], o);", + quoted(&dir.join("n.png")) + ); + script(&mut s, &base, &source); + let img = png(&dir.join("n.png")); + assert_eq!((img.width(), img.height()), (10, 10), "10.25 pt at 72 ppi"); + let _ = std::fs::remove_dir_all(base); +} + +/// Bounds that miss every object still give an image of that area, blank or transparent. +#[test] +fn image_capture_of_bounds_without_art_is_blank() { + let base = folder("empty"); + let (mut s, dir) = capture_doc(&base); + // x 300 to 350 and y 100 to 50 (Y up): below and right of both rectangles. + let f = |n: &str| quoted(&dir.join(n)); + let source = format!( + "var d = app.activeDocument, o = new ImageCaptureOptions(); o.resolution = 72;\ + d.imageCapture(new File({}), [300, 100, 350, 50], o);\ + o.transparency = true; d.imageCapture(new File({}), [300, 100, 350, 50], o);", + f("blank.png"), + f("clear.png") + ); + let undo = undo_steps(&s); + script(&mut s, &base, &source); + for (name, blank) in [("blank.png", [255, 255, 255, 255]), ("clear.png", [0, 0, 0, 0])] { + let img = png(&dir.join(name)); + assert_eq!((img.width(), img.height()), (50, 50), "{name}"); + assert_eq!(img.pixels().len(), 2500, "{name}"); + assert!(img.pixels().all(|p| p.0 == blank), "{name}: every pixel is {blank:?}"); + } + assert_eq!(undo_steps(&s), undo, "a capture changes nothing in the document"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_rejects_64mp_and_side_limit_before_render() { + let base = folder("huge"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("huge.png"); + // 4000 × 4000 pt at 2400 ppi is far past 64 megapixels; 40,000 × 1 pt at 72 ppi is past 32,768 a side. + let cases = [ + format!( + "var o = new ImageCaptureOptions(); o.resolution = 2400; app.activeDocument.imageCapture(new File({}), [0, 4000, 4000, 0], o);", + quoted(&target) + ), + format!( + "var o = new ImageCaptureOptions(); o.resolution = 72; app.activeDocument.imageCapture(new File({}), [0, 1, 40000, 0], o);", + quoted(&target) + ), + ]; + for case in &cases { + let e = file_failure(&mut s, &base, case); + assert!(e.contains("64 megapixels"), "{case}: {e}"); + } + assert!(!target.exists()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_rejects_bad_options_and_names() { + let base = folder("bad"); + let (mut s, dir) = capture_doc(&base); + let png = quoted(&dir.join("x.png")); + let cases = [ + ( + format!("var o = new ImageCaptureOptions(); o.resolution = 50; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "from 72 to 2400", + ), + ( + format!("var o = new ImageCaptureOptions(); o.resolution = Infinity; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "finite number", + ), + ( + format!( + "var o = new ImageCaptureOptions(); o.matteColor = {{red: NaN, green: 0, blue: 0}}; app.activeDocument.imageCapture(new File({png}), undefined, o);" + ), + "finite number", + ), + (format!("app.activeDocument.imageCapture(new File({png}), [0, 300, Infinity, 250]);"), "finite number"), + ( + format!("var o = new ImageCaptureOptions(); o.matte = 'yes'; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "true or false", + ), + ( + format!( + "var o = new ImageCaptureOptions(); o.matteColor = {{red: 300, green: 0, blue: 0}}; app.activeDocument.imageCapture(new File({png}), undefined, o);" + ), + "from 0 to 255", + ), + ( + format!("var o = new ImageCaptureOptions(); o.matteColor = 'red'; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "RGBColor", + ), + (format!("app.activeDocument.imageCapture(new File({png}), undefined, new RasterizeOptions());"), "ImageCaptureOptions object"), + (format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join("x.tif"))), "ends with .png"), + (format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join(".png"))), "ends with .png"), + ("app.activeDocument.imageCapture('x.png');".to_string(), "needs a File"), + (format!("app.activeDocument.imageCapture(new File({png}), [0, 0, 0, 0]);"), "right edge right of its left edge"), + (format!("app.activeDocument.windowCapture(new File({}), [100, 100]);", quoted(&dir.join("w.tif"))), "not available yet"), + ]; + for (case, message) in &cases { + let e = file_failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(message), "{case}: {e}"); + } + assert_eq!(std::fs::read_dir(&dir).unwrap().filter(|e| e.as_ref().is_ok_and(|e| e.path().extension().is_some())).count(), 0, "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + +/// A second hard link to an open document's file names the same file, so a capture to it is refused. +#[test] +fn capture_refuses_a_hard_link_to_an_open_document() { + let base = folder("hard-link"); + let (mut s, dir) = capture_doc(&base); + let source = dir.join("source.vectorcraft"); + std::fs::write(&source, b"kept").unwrap(); + let alias = dir.join("alias.png"); + if std::fs::hard_link(&source, &alias).is_err() { + // The volume has no hard links. + let _ = std::fs::remove_dir_all(base); + return; + } + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + assert_eq!(std::fs::read(&alias).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix a capture never writes over a file with other hard links, which an in-place write would +/// change under every name. +#[cfg(unix)] +#[test] +fn capture_refuses_a_file_with_other_hard_links() { + let base = folder("other-links"); + let (mut s, dir) = capture_doc(&base); + let other = dir.join("other.bin"); + std::fs::write(&other, b"kept").unwrap(); + let alias = dir.join("alias.png"); + std::fs::hard_link(&other, &alias).unwrap(); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); + assert!(e.contains("other hard links"), "{e}"); + assert_eq!(std::fs::read(&other).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// A destination that becomes a second name of an open document's file after the capture's checks, +/// while the art renders, is refused as the export commits its file. +#[test] +fn capture_refuses_a_destination_linked_to_an_open_document_during_the_export() { + let base = folder("rebind"); + let (mut s, dir) = capture_doc(&base); + let source = dir.join("source.vectorcraft"); + std::fs::write(&source, b"kept").unwrap(); + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let target = dir.join("late.png"); + let probe = dir.join("probe-link"); + if std::fs::hard_link(&source, &probe).is_err() { + // The volume has no hard links. + let _ = std::fs::remove_dir_all(base); + return; + } + std::fs::remove_file(&probe).unwrap(); + let (from, to) = (source.clone(), target.clone()); + crate::script::dom::BEFORE_CAPTURE_EXPORT.with(|f| *f.borrow_mut() = Some(Box::new(move || std::fs::hard_link(&from, &to).unwrap()))); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + assert_eq!(std::fs::read(&target).unwrap(), b"kept", "the late link is left as it was"); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix a destination whose real path is not valid UTF-8 is refused before anything is written, +/// rather than written under a name with its bytes replaced. +#[cfg(unix)] +#[test] +fn capture_refuses_a_destination_that_is_not_utf8() { + use std::os::unix::ffi::OsStrExt; + let base = folder("non-utf8"); + let (mut s, dir) = capture_doc(&base); + let odd = dir.join(std::ffi::OsStr::from_bytes(b"odd\xff")); + if std::fs::create_dir(&odd).is_err() { + // The volume refuses names that are not UTF-8. + let _ = std::fs::remove_dir_all(base); + return; + } + // A link with a UTF-8 name that leads into the folder whose name is not. + let link = dir.join("plain"); + std::os::unix::fs::symlink(&odd, &link).unwrap(); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&link.join("x.png")))); + assert!(e.contains("not valid UTF-8"), "{e}"); + assert_eq!(std::fs::read_dir(&odd).unwrap().count(), 0, "nothing written"); + assert!(!dir.join("odd\u{fffd}").exists(), "nothing written under the replaced name"); + let _ = std::fs::remove_dir_all(base); +} + +/// On macOS, whose volumes look names up in either Unicode normalization form, a missing linked +/// file's name in the other form is the linked file. +#[cfg(target_os = "macos")] +#[test] +fn capture_to_a_missing_links_name_in_the_other_normalization_form_writes_nothing() { + let base = folder("missing-nfd"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + // The link's name is composed (NFC); the capture names it decomposed (NFD). + place_linked( + &mut s, + "cafe", + vectorcraft_doc::LinkInfo { path: "caf\u{e9}.png".into(), relative: Some("caf\u{e9}.png".into()), ..Default::default() }, + ); + let nfd = dir.join("cafe\u{301}.png"); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&nfd))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!nfd.exists() && !dir.join("caf\u{e9}.png").exists(), "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_denied_or_source_path_writes_nothing() { + let base = folder("denied"); + let (mut s, dir) = capture_doc(&base); + let outside = base.join("outside/x.png"); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&outside))); + assert!(e.contains(DENIED), "{e}"); + assert!(!outside.exists()); + // An open document whose file is named .png in the folder the script may write: its source. + let source = dir.join("source.png"); + std::fs::write(&source, b"kept").unwrap(); + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&source))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + // An image linked by a path relative to the document's folder, not to the working directory. + let linked = dir.join("linked.png"); + std::fs::write(&linked, b"kept").unwrap(); + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "linked.png".into(), relative: Some("linked.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let e = + file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&linked))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&linked).unwrap(), b"kept"); + // An image linked only from a symbol's art, outside the layers. + let in_symbol = dir.join("in-symbol.png"); + std::fs::write(&in_symbol, b"kept").unwrap(); + s.edit("Symbol", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: in_symbol.to_string_lossy().into_owned(), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "symbol-pic".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + let art = vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))); + d.symbols.push(vectorcraft_doc::Symbol { name: "Mark".into(), art: std::sync::Arc::new(art), dynamic: false }); + Ok(()) + }) + .unwrap(); + let e = file_failure( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&in_symbol)), + ); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&in_symbol).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_to_a_missing_links_path_writes_nothing() { + let base = folder("missing-link"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + // An image linked by a path next to the document whose file is not there. + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "gone.png".into(), relative: Some("gone.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "gone".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let gone = dir.join("gone.png"); + assert!(!gone.exists()); + let e = + file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&gone))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!gone.exists(), "nothing written"); + // The same name in other letter case is the linked file only where the volume ignores case. + std::fs::write(dir.join("probe.txt"), b"x").unwrap(); + let volume_ignores_case = dir.join("PROBE.TXT").exists(); + let upper = dir.join("GONE.png"); + let text = format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&upper)); + if volume_ignores_case { + assert!(file_failure(&mut s, &base, &text).contains("cannot write over an open document")); + assert!(!gone.exists(), "nothing written"); + } else { + script(&mut s, &base, &text); + assert!(upper.exists() && !gone.exists(), "a different file on a volume that keeps case"); + // Two names for one file that differ only in case show that the folder keeps case. + let sub = dir.join("sub"); + std::fs::create_dir(&sub).unwrap(); + std::fs::write(sub.join("probe.txt"), b"x").unwrap(); + std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).unwrap(); + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "sub/gone.png".into(), relative: Some("sub/gone.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "sub-gone".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let sub_upper = sub.join("GONE.png"); + script(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&sub_upper))); + assert!(sub_upper.exists() && !sub.join("gone.png").exists()); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Places a linked image of the key `key` with `link` on the active document's default layer. +fn place_linked(s: &mut Session, key: &str, link: vectorcraft_doc::LinkInfo) { + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: key.into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link: Some(link), + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); +} + +/// An untitled document opened from a template finds a link by its relative path from the +/// template's folder, so a capture there is refused, also when the file is missing. +#[test] +fn capture_to_a_templates_relative_link_writes_nothing() { + let base = folder("template-link"); + let (mut s, dir) = capture_doc(&base); + let st = s.active_mut().unwrap(); + st.path = None; + st.links_from = Some(dir.join("t.vctemplate").to_string_lossy().into_owned()); + let stale = base.join("outside/gone/pic.png").to_string_lossy().into_owned(); + place_linked(&mut s, "pic", vectorcraft_doc::LinkInfo { path: stale, relative: Some("pic.png".into()), ..Default::default() }); + let target = dir.join("pic.png"); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!target.exists(), "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + +/// Two images that share a stale path and a content but keep different relative paths are each +/// looked for at their own relative path, so a capture over either one's file is refused. +#[test] +fn capture_over_either_relative_path_of_one_linked_content_writes_nothing() { + let base = folder("two-relatives"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + let stale = base.join("outside/gone/pic.png").to_string_lossy().into_owned(); + for relative in ["a.png", "b.png"] { + place_linked(&mut s, "pic", vectorcraft_doc::LinkInfo { path: stale.clone(), relative: Some(relative.into()), ..Default::default() }); + } + for name in ["a.png", "b.png"] { + let target = dir.join(name); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{name}: {e}"); + assert!(!target.exists(), "{name}: nothing written"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// A DCS image whose stored path is stale reads its plate files beside the main file its relative +/// path finds, so a capture over one of those is refused. +#[test] +fn capture_over_a_plate_beside_a_found_dcs_file_writes_nothing() { + use vectorcraft_doc::separated::{InkPlate, PlateFile, Separated}; + let base = folder("dcs-plate"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + std::fs::write(dir.join("main.eps"), b"main").unwrap(); + let plate = dir.join("cyan.png"); + std::fs::write(&plate, b"kept").unwrap(); + let separated = Separated::new(1, 1, vec![InkPlate { name: "Cyan".into(), cmyk: [1.0, 0.0, 0.0, 0.0], data: vec![255] }]).unwrap(); + let files = [PlateFile { name: "cyan.png".into(), size: 4, modified: 0 }]; + let blob = vectorcraft_doc::ImageBlob::separated_tiff(&separated, None, &files).unwrap(); + s.edit("Blob", |d, _| { + d.images.insert("dcs".into(), blob); + Ok(()) + }) + .unwrap(); + let stale = base.join("outside/gone/main.eps").to_string_lossy().into_owned(); + place_linked(&mut s, "dcs", vectorcraft_doc::LinkInfo { path: stale, relative: Some("main.eps".into()), ..Default::default() }); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&plate))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&plate).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// A document the interface opens while the run is paused is open too: a capture over its file is +/// refused. +#[test] +fn capture_over_a_document_opened_while_paused_writes_nothing() { + let base = folder("paused-open"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("opened.png"); + let main = base.join("main/main.jsx"); + let text = format!( + "Folder.userData; for (var i = 0; i < 2000000; i++) {{}}\ + try {{ app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]); vc.log('written'); }} catch (e) {{ vc.log(e.message); }}", + quoted(&target) + ); + std::fs::write(&main, text.as_bytes()).unwrap(); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + let svg = br#""#; + crate::cmd::fileio::open_bytes(&mut s, "opened.svg", svg, Some(target.to_string_lossy().into_owned())).unwrap(); + std::fs::write(&target, b"kept").unwrap(); + let r = loop { + if let Some(r) = s.script_pump() { + break r.unwrap(); + } + }; + s.script_frames = false; + let out = r["log"].as_array().cloned().unwrap_or_default(); + assert!(out.len() == 1 && out[0].as_str().is_some_and(|m| m.contains("cannot write over an open document")), "{out:?}"); + assert_eq!(std::fs::read(&target).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_written_before_a_failure_is_reported() { + let base = folder("report"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("kept.png"); + let r = run_file(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({})); throw new Error('later');", quoted(&target))); + let e = r.unwrap_err().to_string(); + assert!(e.contains("later") && e.contains("kept.png"), "the failure names the file it wrote: {e}"); + assert!(target.is_file()); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 2373640149..3952955779 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -182,6 +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"), + // Names the app's own reference errors give a hint for: a script's own text keeps none. ("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), ("throw new ReferenceError('BridgeTalk is not defined');", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), @@ -435,6 +436,29 @@ fn a_js_script_has_proxy_and_reflect_and_a_jsx_script_does_not() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them() { + let dir = fresh_folder("es2017"); + 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 src = "async function twice(p) { return 2 * await p; }\nvar half = async x => x / 2;\n\ + twice(Promise.resolve(3)).then(function (v) { vc.log(v); });\n\ + (async function () { try { await Promise.reject(new Error('no')); } catch (e) { vc.log(await half(8) + e.message); } })();\n\ + vc.log('sync');\n"; + let r = s.execute("script.run", &path(&write("async.js", src))).unwrap(); + assert_eq!(r["log"], json!(["sync", 6, "4no"]), "{r}"); + for (name, text) in [("async.jsx", "async function f() {}"), ("arrow.jsx", "var f = async x => x;")] { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() { let dir = fresh_folder("es2020"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index b683ddbbd9..5a58964284 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -10,6 +10,54 @@ use crate::*; const DENIED: &str = "Script file access denied"; +#[cfg(unix)] +#[test] +fn save_as_uses_the_scripts_extension_before_following_a_link() { + let base = folder("save-link-format"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let target = dir.join("target.vectorcraft"); + let alias = dir.join("alias.svg"); + std::fs::write(&target, b"keep").unwrap(); + std::os::unix::fs::symlink(&target, &alias).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&alias))); + assert!(std::fs::read_to_string(&target).unwrap().contains(" PathBuf { PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()) } +#[cfg(unix)] +#[test] +fn save_as_uses_the_supplied_alias_extension() { + let base = folder("save-alias-format"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let target = dir.join("output.vectorcraft"); + let alias = dir.join("output.svg"); + std::fs::write(&target, "before").unwrap(); + std::os::unix::fs::symlink(&target, &alias).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&alias))); + let svg = std::fs::read_to_string(&target).unwrap(); + assert!(svg.contains(" String { serde_json::to_string(&p.to_string_lossy()).unwrap() } @@ -157,6 +224,118 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn scripted_file_writes_log_command_warnings() { + for (method, extension, call) in [("saveAs", "pdf", "d.saveAs(file)"), ("exportFile", "png", "d.exportFile(file, ExportType.PNG24)")] { + let base = folder(&format!("warning-{method}")); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + super::menucmds::place_undecodable_png(&mut s); + let path = dir.join(format!("output.{extension}")); + let out = run(&mut s, &base, &format!("Folder.userData; var d = app.activeDocument, file = new File({}); {call};", quoted(&path))).unwrap(); + assert!(path.is_file(), "{method}"); + let prefix = format!("{method}: "); + let lines = out["console"]["lines"].as_array().unwrap(); + assert!(lines.iter().filter_map(Value::as_str).any(|s| s.starts_with(&prefix) && s.contains("couldn't be decoded")), "{method}: {out}"); + let _ = std::fs::remove_dir_all(base); + } +} + +#[test] +fn open_does_not_inherit_an_existing_documents_link_permission() { + let base = folder("inherited-link"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let linked = base.join("outside/linked.png"); + std::fs::write(&linked, super::links::png(2, 2, [255, 0, 0])).unwrap(); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + s.execute("file.place", &json!({"path": linked.to_string_lossy(), "link": true})).unwrap(); + let href = linked.to_string_lossy().replace('\\', "/").replace('&', "&").replace('<', "<").replace('\'', "'"); + let page = dir.join("page.svg"); + std::fs::write( + &page, + format!(""), + ) + .unwrap(); + let capture = dir.join("existing.png"); + logged( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.imageCapture(new File({})); app.open(new File({}));", quoted(&capture), quoted(&page)), + ); + let pixels = image::open(&capture).unwrap().to_rgb8(); + assert!(pixels.pixels().any(|p| p.0 == [255, 0, 0]), "existing art can still read its linked image"); + let mut images = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + images.push((im.width, im.height, im.link.as_ref().is_some_and(|l| l.hash.is_some()))); + } + }); + assert_eq!(images, [(64, 64, false)], "the new document cannot read the inherited link"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn export_file_logs_encoder_warnings() { + let base = folder("export-warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let text = format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\ + d.pathItems[0].name = 'invalid\\u0001name';\ + vc.log(String(d.exportFile(new File({}), ExportType.SVG)));", + quoted(&dir.join("warnings.svg")) + ); + let r = run(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!(["undefined"])); + assert!(dir.join("warnings.svg").is_file()); + let lines = r["console"]["lines"].as_array().unwrap(); + let warning = "exportFile: Object names containing invalid XML characters were left out of SVG name attributes"; + assert!(lines.iter().any(|line| line.as_str() == Some(warning)), "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The warnings of the save go to the console, and `saveAs` still returns nothing. +#[test] +fn save_as_logs_the_saves_warnings() { + let base = folder("warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let text = format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.log(String(d.saveAs(new File({d} + '/a.svg'))));" + ); + let r = run(&mut s, &base, &text).unwrap_or_else(|e| panic!("{text}: {e}")); + assert_eq!(r["log"], json!(["undefined"])); + let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default(); + let warned = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ") && l.contains("keeps the artwork")); + assert!(warned, "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn open_logs_warnings_for_an_unreadable_linked_image() { + let base = folder("open-warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let svg = dir.join("missing-image.svg"); + std::fs::write( + &svg, + "\ + ", + ) + .unwrap(); + let text = format!("Folder.userData; var d = app.open(new File({})); vc.log(d.typename);", quoted(&svg)); + let r = run(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!(["Document"])); + let lines = r["console"]["lines"].as_array().unwrap(); + assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("open: ") && l.contains("missing.png")), "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn relative_saved_paths_use_the_process_working_directory() { let cwd = crate::cmd::findfiles::plain(std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap()); @@ -260,13 +439,17 @@ fn omitted_options_are_a_new_options_objects_defaults() { d.exportFile(new File(dir + '/j2'), ExportType.JPEG, new ExportOptionsJPEG());\n\ d.exportFile(new File(dir + '/p1'), ExportType.PNG24);\n\ d.exportFile(new File(dir + '/p2'), ExportType.PNG24, new ExportOptionsPNG24());\n\ + var j3 = new ExportOptionsJPEG(); j3.matteColor = {{red: 255, green: 255, blue: 255}};\n\ + d.exportFile(new File(dir + '/j3'), ExportType.JPEG, j3);\n\ + var p3 = new ExportOptionsPNG24(); p3.matteColor = {{typename: 'RGBColor', red: 255, green: 255, blue: 255}};\n\ + d.exportFile(new File(dir + '/p3'), ExportType.PNG24, p3);\n\ d.exportFile(new File(dir + '/s1'), ExportType.SVG);\n\ d.exportFile(new File(dir + '/s2'), ExportType.SVG, new ExportOptionsSVG());\n\ d.saveAs(new File(dir + '/a1.pdf'));\n\ d.saveAs(new File(dir + '/a2.pdf'), new PDFSaveOptions());" ), ); - for (one, two) in [("j1.jpg", "j2.jpg"), ("p1.png", "p2.png"), ("s1.svg", "s2.svg")] { + for (one, two) in [("j1.jpg", "j2.jpg"), ("j1.jpg", "j3.jpg"), ("p1.png", "p2.png"), ("p1.png", "p3.png"), ("s1.svg", "s2.svg")] { assert!(std::fs::read(dir.join(one)).unwrap() == std::fs::read(dir.join(two)).unwrap(), "{one} and {two} differ"); } for name in ["a1.pdf", "a2.pdf"] { @@ -276,6 +459,39 @@ fn omitted_options_are_a_new_options_objects_defaults() { let _ = std::fs::remove_dir_all(base); } +/// White, the default `matteColor` of `ExportOptionsPNG24` and `ExportOptionsJPEG`, is accepted, and +/// another color is refused. +#[test] +fn a_white_matte_color_is_the_default() { + let base = folder("matte"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100), c = new RGBColor();\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); c.red = 255; c.green = 255; c.blue = 255;\n\ + var p = new ExportOptionsPNG24(); p.matteColor = c; d.exportFile(new File(dir + '/p'), ExportType.PNG24, p);\n\ + var j = new ExportOptionsJPEG(); j.matteColor = c; d.exportFile(new File(dir + '/j'), ExportType.JPEG, j);" + ), + ); + assert!(dir.join("p.png").exists() && dir.join("j.jpg").exists()); + for (class, kind) in [("ExportOptionsPNG24", "PNG24"), ("ExportOptionsJPEG", "JPEG")] { + let e = failure( + &mut s, + &base, + &format!( + "Folder.userData; var c = new RGBColor(); c.red = 255; c.green = 0; c.blue = 255; var o = new {class}(); o.matteColor = c;\ + app.activeDocument.exportFile(new File({d} + '/x'), ExportType.{kind}, o);" + ), + ); + assert!(e.contains("matteColor"), "{class}: {e}"); + } + let _ = std::fs::remove_dir_all(base); +} + /// A new `IllustratorSaveOptions` reads `compatibility` as its default, ILLUSTRATOR19, and saves /// with it untouched. #[test] @@ -411,6 +627,114 @@ fn a_raster_export_at_100_percent_has_a_pixel_per_point() { let _ = std::fs::remove_dir_all(base); } +/// The value of the DXF header variable `name` (the group after its name). +fn dxf_header(dxf: &str, name: &str) -> Option { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + lines.iter().position(|l| *l == name).and_then(|i| lines.get(i + 2)).map(|v| v.to_string()) +} + +/// The largest x coordinate (group code 10) in the entities of a DXF. +fn dxf_widest(dxf: &str) -> f64 { + dxf_xs(dxf).into_iter().reduce(f64::max).expect("DXF contains polyline vertices") +} + +/// The smallest x coordinate (group code 10) in the entities of a DXF. +fn dxf_leftmost(dxf: &str) -> f64 { + dxf_xs(dxf).into_iter().reduce(f64::min).expect("DXF contains polyline vertices") +} + +/// The x coordinates (group code 10) of the polyline vertices in a DXF. A hatch's code 10 is its +/// elevation point, so hatches are left out. +fn dxf_xs(dxf: &str) -> Vec { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + // The section's name is a value; the group codes start on the line after it. + let start = lines.iter().position(|l| *l == "ENTITIES").map_or(0, |i| i + 1); + let mut entity = ""; + let mut xs = Vec::new(); + for p in lines[start..].chunks(2).filter(|p| p.len() == 2) { + match p[0] { + "0" => entity = p[1], + "10" if entity == "LWPOLYLINE" => xs.extend(p[1].parse::().ok()), + _ => {} + } + } + xs +} + +/// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and +/// DWG, the help page's default format, throws without writing a file. +#[test] +fn an_autocad_export_writes_a_dxf_with_its_options() { + let base = folder("autocad"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\ + try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\ + o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\ + o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 1000; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ + d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 100; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ + o.unit = AutoCADUnit.Picas; d.exportFile(new File(dir + '/p'), ExportType.AutoCAD, o);\n\ + var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\ + d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});" + ), + ); + assert_eq!(out[0], json!(["ExportOptionsAutoCAD", "AutoCADExportFileFormat.DWG", "AutoCADCompatibility.AutoCADRelease24", true])); + assert!(out[1].as_str().is_some_and(|e| e.contains("DWG is not available")), "{}", out[1]); + assert!(!dir.join("w.dxf").exists() && !dir.join("w.dwg").exists() && !dir.join("w").exists(), "DWG writes nothing"); + let a = std::fs::read_to_string(dir.join("a.dxf")).unwrap(); + let b = std::fs::read_to_string(dir.join("b.DXF")).unwrap(); + assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it"); + assert_eq!(dxf_header(&a, "$ACADVER").as_deref(), Some("AC1015"), "AutoCADRelease15 is the 2000 format"); + assert_eq!(dxf_header(&b, "$INSUNITS").as_deref(), Some("1"), "inches, one drawing unit each"); + // The DXF writes six decimals. + assert!((dxf_widest(&a) - dxf_widest(&b) * 10.0).abs() < 1e-4, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b)); + for name in ["c.dxf", "u.dxf"] { + let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); + assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); + // The rectangle is 10 pt (3.5 mm) from the artboard's left edge. + assert!(dxf_leftmost(&dxf).abs() < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf)); + } + let p = std::fs::read_to_string(dir.join("p.dxf")).unwrap(); + assert!(dxf_widest(&p) > dxf_widest(&b) * 5.0, "a pica is a sixth of an inch: {} and {}", dxf_widest(&p), dxf_widest(&b)); + let _ = std::fs::remove_dir_all(base); +} + +/// `unitScaleRatio` is a percentage: 100 writes the drawing at the size an option left out gives, +/// and 200 writes it twice as wide. +#[test] +fn an_autocad_unit_scale_ratio_is_a_percentage() { + let base = folder("autocad-ratio"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF;\n\ + d.exportFile(new File(dir + '/n'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 100; d.exportFile(new File(dir + '/h'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 200; d.exportFile(new File(dir + '/t'), ExportType.AutoCAD, o);\n\ + vc.log(1);" + ), + ); + let width = |name: &str| dxf_widest(&std::fs::read_to_string(dir.join(name)).unwrap()); + let (n, h, t) = (width("n.dxf"), width("h.dxf"), width("t.dxf")); + assert!((h - n).abs() < 1e-6, "100 is full size: {h} and {n}"); + assert!((t - 2.0 * n).abs() < 1e-5, "200 is twice the size: {t} and {n}"); + let _ = std::fs::remove_dir_all(base); +} + /// With `pDFPreset` named, the options left at a new object's defaults keep the preset's values, and /// an option the script changes applies over the preset. #[test] @@ -462,11 +786,39 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); std::fs::set_permissions(&board, perms).unwrap(); + // A folder where an artboard's file goes writes none of them either. + std::fs::remove_file(&board).unwrap(); + std::fs::create_dir(&board).unwrap(); + let e = failure(&mut s, &base, &save); + assert!(e.contains("not a file"), "{e}"); + assert!(!central.exists(), "the central file is not written when a folder is where an artboard's file goes"); let _ = std::fs::remove_dir_all(base); } +/// An export that writes several files writes none of them when a folder is where one of them goes. +#[test] +fn an_export_writes_nothing_when_a_folder_is_where_one_of_its_files_goes() { + let dir = vectorcraft_testkit::TempDir::new("export-folder-target"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let path = dir.join("a.eps").to_string_lossy().into_owned(); + let export = json!({"path": path, "format": "eps", "useArtboards": true}); + let r = s.execute("document.export", &export).unwrap(); + let files: Vec = + r["files"].as_array().unwrap_or_else(|| panic!("several files: {r}")).iter().map(|f| PathBuf::from(f.as_str().unwrap())).collect(); + assert!(files.len() > 1, "{r}"); + for f in &files { + std::fs::remove_file(f).unwrap(); + } + std::fs::create_dir(files.last().unwrap()).unwrap(); + let e = s.execute("document.export", &export).unwrap_err().to_string(); + assert!(e.contains("not a file"), "{e}"); + assert!(files[..files.len() - 1].iter().all(|f| !f.exists()), "no file is written when a folder is where one goes"); +} + /// When the writer a save is given does not check the file access itself, a save of several files -/// whose file access refuses one of them hands none of them to the writer. +/// whose last file is refused hands none of them to the writer, the refused one included. #[test] fn a_refused_file_stops_a_save_whose_writer_does_not_check() { use crate::cmd::fileio::{SaveMode, save_job, save_plan}; @@ -503,9 +855,10 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() { Ok(()) }) }); - assert!(r.is_err(), "{r:?}"); + let e = r.unwrap_err().to_string(); let refused = refused.unwrap(); - assert_eq!(written, Vec::::new(), "no file went to the writer, the refused one ({refused}) included"); + assert!(e.contains(DENIED) && e.contains(&refused), "{e}"); + assert!(written.is_empty(), "no file went to the writer: {written:?}"); let mut perms = std::fs::metadata(&refused).unwrap().permissions(); #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); @@ -644,6 +997,34 @@ fn open_reads_linked_files_only_where_the_script_may() { let _ = std::fs::remove_dir_all(base); } +/// A file an open document links to is read by `open` only where the script may read, too. +#[test] +fn open_reads_files_open_documents_link_to_only_where_the_script_may() { + let base = folder("linked-by-open"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pic = base.join("outside/linked.png"); + std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": true})).unwrap(); + let href = pic.to_string_lossy().replace('\\', "/").replace('&', "&").replace('<', "<").replace('\'', "'"); + std::fs::write( + dir.join("page.svg"), + format!(""), + ) + .unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&dir.join("page.svg")))); + let mut sizes = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + sizes.push((im.width, im.height)); + } + }); + assert_eq!(sizes.len(), 1, "{sizes:?}"); + assert_ne!(sizes[0], (2, 2), "the linked file outside the script's folders is not read"); + let _ = std::fs::remove_dir_all(base); +} + /// An SVG export with `embedRasterImages` false writes the document's embedded image beside the /// SVG, and when that file may not be written, the SVG is not written either. #[test] @@ -780,6 +1161,12 @@ fn bad_arguments_are_refused_with_an_error() { (format!("var o = new EPSSaveOptions(); o.postScript = 'LEVEL2'; app.activeDocument.saveAs({f}, o);"), "EPSPostScriptLevelEnum"), (format!("app.activeDocument.exportFile({f}, 'PNG24');"), "ExportType"), (format!("app.activeDocument.exportFile({f}, ExportType.FLASH);"), "is not available yet"), + ( + format!( + "var p = new ExportOptionsPNG24(); p.matteColor = {{red: 255, green: 0, blue: 255}}; app.activeDocument.exportFile({f}, ExportType.PNG24, p);" + ), + "ExportOptionsPNG24.matteColor is not available yet", + ), (format!("app.activeDocument.exportFile({f}, ExportType.PNG24, new ExportOptionsJPEG());"), "ExportOptionsPNG24"), ( format!( @@ -802,6 +1189,47 @@ fn bad_arguments_are_refused_with_an_error() { "from 0 to 100", ), (format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"), + (format!("app.activeDocument.exportFile({f}, ExportType.AutoCAD);"), "DWG is not available"), + ( + format!("var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);"), + "DWG is not available", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScaleRatio = 2000; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "at most 1000", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScaleRatio = 0.00001; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "ExportOptionsAutoCAD.unitScaleRatio must be at least 0.0001", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = 'AutoCADCompatibility.AutoCADRelease99'; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "AutoCADCompatibility", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.colors = 256; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "AutoCADColors", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScale = 2; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "ExportOptionsAutoCAD has no option unitScale", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease14; o.colors = AutoCADColors.TrueColors; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "TrueColors needs AutoCADRelease18", + ), (format!("app.open({f}, 'RGB');"), "DocumentColorSpace"), (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), @@ -1106,6 +1534,51 @@ fn full_name_path_saved_and_close_follow_the_documents_file() { let _ = std::fs::remove_dir_all(base); } +/// A document whose file was saved under a relative name is in the working folder the file was +/// written in. +#[test] +fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() { + let base = folder("relative"); + let mut s = session(&base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.active_mut().unwrap().path = Some("drawing.svg".into()); + let out = logged( + &mut s, + &base, + "var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName, d.fullName.fsName]);", + ); + let cwd = std::env::current_dir().unwrap(); + assert_eq!(out[0][0], json!(true), "{out}"); + let same = |shown: &str, want: &Path| { + let shown = PathBuf::from(shown); + shown == want || std::fs::canonicalize(&shown).ok().zip(std::fs::canonicalize(want).ok()).is_some_and(|(a, b)| a == b) + }; + assert!(same(out[0][1].as_str().unwrap(), &cwd), "{out} is not in {cwd:?}"); + let file = out[0][2].as_str().unwrap(); + assert!(Path::new(file).is_absolute() && Path::new(file).file_name() == Some("drawing.svg".as_ref()), "{file}"); + assert!(same(&Path::new(file).parent().unwrap().to_string_lossy(), &cwd), "{file} is not in {cwd:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The warnings a save gives, such as editing data left out of a PDF of one artboard of several, go +/// to the Script Console. +#[test] +fn a_saves_warnings_go_to_the_console() { + let base = folder("warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + let save = format!( + "Folder.userData; var o = new PDFSaveOptions(); o.preserveEditability = true; o.artboardRange = '1';\n\ + app.activeDocument.saveAs(new File({}), o);", + quoted(&dir.join("one.pdf")) + ); + let r = run(&mut s, &base, &save).unwrap(); + let lines = r["console"]["lines"].as_array().unwrap(); + assert!(lines.iter().any(|l| l.as_str().is_some_and(|l| l.starts_with("saveAs: "))), "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + /// A document without unsaved changes closes with `SaveOptions.SAVECHANGES` and with no argument. #[test] fn a_document_without_unsaved_changes_closes_with_any_save_options() { @@ -1271,9 +1744,9 @@ fn closing_with_save_changes_checks_the_artboards_the_file_keeps() { let _ = std::fs::remove_dir_all(base); } -/// A `.ai` file saved without separate artboard files, and an SVG file that carries the native -/// document, keep every artboard whatever `range` names, so `close(SaveOptions.SAVECHANGES)` saves -/// them; a `range` the save refuses still refuses. +/// A native file and a `.ai` file saved without separate artboard files, and an SVG file that +/// carries the native document, keep every artboard whatever `range` names, so +/// `close(SaveOptions.SAVECHANGES)` saves them; a `range` the save refuses still refuses. #[test] fn closing_with_save_changes_saves_files_that_keep_every_artboard() { let base = folder("closekeepall"); @@ -1281,7 +1754,11 @@ fn closing_with_save_changes_saves_files_that_keep_every_artboard() { let mut s = session(&base); data_folder(&mut s, &base) }; - for (name, options) in [("whole.ai", json!({"range": "2"})), ("native.svg", json!({"preserveEditing": true, "range": "1"}))] { + for (name, options) in [ + ("whole.vectorcraft", json!({"range": "2"})), + ("whole.ai", json!({"range": "2"})), + ("native.svg", json!({"preserveEditing": true, "range": "1"})), + ] { let mut s = session(&base); data_folder(&mut s, &base); let file = dir.join(name); diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 2794e929b2..9581b43ae3 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -46,6 +46,17 @@ fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> { } } +#[test] +fn character_color_attributes_reflect_as_color() { + let (mut s, _) = doc_with("color"); + let out = log( + &mut s, + "var a = app.activeDocument.textFrames[0].textRange.characterAttributes;\ + vc.log(a.reflect.find('fillColor').dataType); vc.log(a.reflect.find('strokeColor').dataType);", + ); + assert_eq!(out, [json!("Color"), json!("Color")]); +} + #[test] fn text_frames_add_point_area_and_path_type() { let mut s = Session::new(); @@ -224,6 +235,10 @@ fn bad_attribute_values_are_refused_without_a_change() { ("r.size = NaN;", "not a finite number"), ("r.leading = 0;", "leading must be from 0.1"), ("r.characterAttributes.tracking = 1e9;", "tracking"), + ("r.baselineShift = -1297;", "baselineShift must be from -1296 to 1296"), + ("r.horizontalScale = 0.9;", "horizontalScale must be from 1 to 10000"), + ("r.characterAttributes.verticalScale = 10001;", "verticalScale must be from 1 to 10000"), + ("r.rotation = 361;", "rotation must be from -360 to 360"), ("r.underline = 1;", "underline must be true or false"), ("r.textFont = 'Arial';", "textFont must be a TextFont"), ("r.paragraphAttributes.justification = 'LEFT';", "Justification value"), @@ -252,6 +267,164 @@ fn setting_the_value_a_range_has_records_no_undo_step() { assert_eq!(undo_steps(&s), before); } +fn paints(s: &Session, id: NodeId) -> Vec<(String, Paint, Paint, f64)> { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.fill.clone(), r.style.stroke.clone(), r.style.stroke_width)).collect(), + _ => panic!("not text"), + } +} + +#[test] +fn character_attributes_paint_only_their_own_characters() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, b = r.characters[1].characterAttributes;\ + var red = new RGBColor(); red.red = 255; b.fillColor = red;\ + var k = new CMYKColor(); k.black = 100; b.strokeColor = k; b.strokeWeight = 2;\ + vc.log([b.fillColor.typename, b.fillColor.red, b.strokeColor.typename, b.strokeColor.black, b.strokeWeight]);\ + vc.log([r.characters[0].fillColor.red, r.characters[0].strokeColor.typename]);", + ); + let n = |v: &Value| v.as_f64().unwrap_or(f64::NAN); + assert_eq!((out[0][0].as_str(), out[0][2].as_str()), (Some("RGBColor"), Some("CMYKColor")), "{out:?}"); + assert_eq!((n(&out[0][1]), n(&out[0][3]), n(&out[0][4])), (255.0, 100.0, 2.0), "the paint reads back as given"); + assert_ne!(n(&out[1][0]), 255.0, "the first character keeps its fill"); + assert_eq!(out[1][1], json!("NoColor"), "the first character keeps no stroke"); + let runs = paints(&s, id); + let b = runs.iter().find(|r| r.0 == "b").expect("b is a run of its own"); + assert_eq!(b.1, Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(b.2, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert!(b.3 > 1.0); + assert!(runs.iter().filter(|r| r.0 != "b").all(|r| r.1 != b.1 && r.2 == Paint::None), "{runs:?}"); + assert!(undo_steps(&s) > before); + + let steps = undo_steps(&s); + log(&mut s, "var b = app.activeDocument.textFrames[0].textRange.characters[1]; b.fillColor = b.fillColor; b.strokeWeight = b.strokeWeight;"); + assert_eq!(undo_steps(&s), steps, "setting the paint a range has records no undo step"); + log(&mut s, "app.activeDocument.textFrames[0].textRange.characters[1].strokeColor = new NoColor();"); + assert!(paints(&s, id).iter().all(|r| r.2 == Paint::None), "a NoColor takes the stroke away"); +} + +#[test] +fn an_rgb_paint_a_cmyk_document_already_stores_records_no_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + s.execute("text.create", &json!({"x": 20, "y": 100, "text": "abc", "size": 12})).unwrap(); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, red = new RGBColor(); red.red = 255; r.fillColor = red; vc.log(r.fillColor.typename);", + ); + assert_eq!(out[0], json!("CMYKColor"), "the document stores the color as CMYK"); + let steps = undo_steps(&s); + log(&mut s, "var r = app.activeDocument.textFrames[0].textRange, red = new RGBColor(); red.red = 255; r.fillColor = red;"); + assert_eq!(undo_steps(&s), steps, "assigning the color the text already stores records no undo step"); +} + +#[test] +fn an_rgb_paint_on_text_in_a_background_rgb_document_is_kept_as_rgb() { + let (mut s, id) = doc_with("abc"); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + s.execute("text.create", &json!({"x": 20, "y": 100, "text": "abc", "size": 12})).unwrap(); + let out = log( + &mut s, + "var front = app.activeDocument, back = app.documents[0] === front ? app.documents[1] : app.documents[0];\ + var red = new RGBColor(); red.red = 255;\ + var f = front.textFrames[0].textRange, b = back.textFrames[0].textRange;\ + f.fillColor = red; b.fillColor = f.fillColor; b.fillColor = red; vc.log(b.fillColor.typename);", + ); + assert_eq!(out[0], json!("RGBColor"), "the RGB document keeps the RGB color it is given: {out:?}"); + let rgb = s.documents().iter().find(|d| d.doc.color_mode == vectorcraft_doc::ColorMode::Rgb).expect("the RGB document"); + let NodeKind::Text(t) = &rgb.doc.node(id).expect("the RGB document's text").kind else { panic!("not text") }; + assert!(t.runs.iter().all(|r| r.style.fill == Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "{:?}", t.runs); +} + +#[test] +fn stroke_weight_reads_back_in_document_points_on_scaled_type() { + let (mut s, id) = doc_with("abc"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = 2; vc.log(r.strokeWeight);"); + assert!((out[0].as_f64().unwrap_or(f64::NAN) - 2.0).abs() < 1e-9, "{out:?}"); + let stored = paints(&s, id)[0].3; + assert!(stored < 2.0, "the type's own scale draws the stored width wider: {stored}"); + let steps = undo_steps(&s); + log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = r.strokeWeight;"); + assert_eq!(undo_steps(&s), steps, "the weight read back is the weight it has"); +} + +#[test] +fn bad_text_paint_is_refused_without_a_change() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let runs = paints(&s, id); + for (src, want) in [ + ("r.fillColor = 'red';", "fillColor must be a color object"), + ("var c = new RGBColor(); c.red = 300; r.strokeColor = c;", "RGBColor.red"), + ("r.fillColor = new GradientColor();", "not available yet"), + ("r.strokeWeight = -1;", "strokeWeight must be from 0 to 1000"), + ("r.characterAttributes.strokeWeight = 'thick';", "strokeWeight 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!(paints(&s, id), runs); +} + +#[test] +fn hidden_or_locked_type_is_not_edited() { + let state = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (paints(s, id), plain(s, id), sizes(s, id), t.para_at(0).justify), + _ => panic!("not text"), + }; + for hide in ["t.locked = true;", "t.hidden = true;"] { + for edit in [ + "r.characters[1].fillColor = red;", + "r.size = 30;", + "r.contents = 'xyz';", + "r.characters.add('!');", + "r.justification = Justification.CENTER;", + "var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(r);", + "var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(t);", + "var c = app.activeDocument.paragraphStyles.add('C'); c.paragraphAttributes.justification = Justification.CENTER; c.applyTo(r);", + ] { + // Each case starts from a fresh frame, so the hidden cases test a frame that is only hidden. + let (mut s, id) = doc_with("abc"); + let before = state(&s, id); + let e = failure( + &mut s, + &format!("var t = app.activeDocument.textFrames[0], r = t.textRange, red = new RGBColor(); red.red = 255; {hide} {edit}"), + ); + assert!(e.contains("Cannot edit TextFrame"), "{hide} {edit}: {e}"); + assert_eq!(state(&s, id), before, "{hide} {edit}"); + } + } +} + +#[test] +fn text_added_after_a_range_ending_inside_a_character_goes_after_that_character() { + let (mut s, id) = doc_with("abc"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; t.contents = '\\uD83D\\uDE00X'; var r = t.textRange; r.length = 1;\ + var x = t.characters.add('!', r); vc.log([x.contents, r.contents]);", + ); + assert_eq!(plain(&s, id), "\u{1F600}!X"); + // Setting `length` to 1 moves the end out to the end of the emoji, and text added at a range's + // end joins the range. + assert_eq!(out, vec![json!(["!", "\u{1F600}!"])]); + // An empty range there sits after the character too, and styling it changes nothing. + let runs = paints(&s, id); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; var r = t.textRange; r.length = 1;\ + var e = t.characters.add('', r), red = new RGBColor(); red.red = 255; e.fillColor = red; vc.log(e.length);", + ); + assert_eq!(out, vec![json!(0)]); + assert_eq!(paints(&s, id), runs); +} + #[test] fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { let (mut s, id) = doc_with("abc"); @@ -331,8 +504,13 @@ fn auto_leading_reads_the_paragraph_of_the_range_inside_one_run() { 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) { + // Both faces ship in assets/fonts: with the bundled fonts the test fails when either one is + // missing, and without them it is skipped. A lookup that falls back to another face counts + // as missing. + let regular = |family: &str| db.face(family, "Regular").filter(|f| f.family == family && f.style == "Regular"); + let faces = regular(from).zip(regular(to)); + assert!(faces.is_some() || !cfg!(feature = "bundled-fonts"), "{from} Regular or {to} Regular is not available"); + if !faces.is_some_and(|(source, dest)| source.covers(c) && !dest.covers(c)) { return; // Installed fonts of these names cover other characters. } let mut s = Session::new(); @@ -465,7 +643,7 @@ fn text_fonts_list_and_assign_fonts_by_name() { &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);\ + 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);" @@ -547,7 +725,7 @@ fn collections_of_text_add_words_characters_and_paragraphs() { } // 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 other = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap()["id"].as_u64().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]);"); @@ -558,12 +736,86 @@ fn collections_of_text_add_words_characters_and_paragraphs() { ("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"), + // A range of a frame that is gone stays stale rather than of the wrong type. + ( + "var o = app.activeDocument.textFrames[1].characters[0]; app.activeDocument.textFrames[1].remove(); t.words.add('x', o)", + "Stale text range", + ), ] { 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, other), "other"); assert_eq!(plain(&s, id), "ab"); + // A range of a frame that was removed is stale, not of the wrong class. + let e = failure(&mut s, "var f = app.activeDocument.textFrames, b = f[0], a = f[1], r = b.textRange; b.remove(); a.characters.add('x', r);"); + assert!(e.contains("Stale text range"), "{e}"); + assert_eq!(plain(&s, id), "ab"); +} + +/// Type on a locked artboard, and a hidden or locked path given to `areaText` or `pathText`, are +/// not changed. +#[test] +fn protected_type_and_paths_are_not_converted_or_edited() { + let (mut s, id) = doc_with("abc"); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + for edit in ["t.contents = 'xyz';", "t.textRange.size = 30;", "t.createOutline();", "t.convertPointObjectToAreaObject();"] { + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {edit}")); + assert!(e.contains("Cannot edit TextFrame") && e.contains("locked artboard"), "{edit}: {e}"); + } + assert_eq!(plain(&s, id), "abc"); + assert_eq!(undo_steps(&s), steps); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap(); + for (hide, call) in [("p.locked = true;", "areaText(p)"), ("p.hidden = true;", "pathText(p)")] { + let e = failure(&mut s, &format!("var d = app.activeDocument, p = d.pathItems[0]; {hide} d.textFrames.{call};")); + assert!(e.contains("Cannot edit PathItem"), "{call}: {e}"); + assert_eq!(log(&mut s, "var d = app.activeDocument; vc.log([d.pathItems.length, d.textFrames.length]);"), vec![json!([1, 0])]); + } +} + +/// Type on a locked artboard stays: `removeAll()` throws and deletes nothing, as +/// `pathItems.removeAll()` does. +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let (mut s, id) = doc_with("ab"); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&id.0.to_string()), "{e}"); + assert_eq!(plain(&s, id), "ab"); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + log(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.textFrames.length);"), vec![json!(0)]); +} + +/// Text added after a range that ends inside a character goes after the whole character, and the +/// range returned holds the added text. +#[test] +fn text_added_after_half_a_character_goes_after_it() { + let (mut s, id) = doc_with("a\u{1F600}b"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.characters[0]; r.length = 2;\ + var x = t.characters.add('X', r, ElementPlacement.PLACEAFTER); vc.log([x.start, x.contents]);", + ); + assert_eq!(out, vec![json!([3, "X"])]); + assert_eq!(plain(&s, id), "a\u{1F600}Xb"); } #[test] @@ -640,6 +892,120 @@ fn type_made_with_a_large_id_is_the_new_type() { assert_eq!(plain(&s, NodeId(big)), ""); } +/// A script that builds a layer `base` holding type `back`, a group `g` (type `g-text` and a +/// group `gg` holding type `gg-text`) and type `front`, a sublayer `sub` of it holding type +/// `sub-text`, and a layer `other` holding type `other-text`, which it leaves current. +const NESTED_TYPE: &str = "var d = app.activeDocument, L0 = d.layers[0]; L0.name = 'base';\ + function put(c, name, y) { var t = c.textFrames.pointText([20, y]); t.contents = name; t.name = name; return t; }\ + put(L0, 'back', 20); var g = L0.groupItems.add(); g.name = 'g'; put(g, 'g-text', 40);\ + var gg = g.groupItems.add(); gg.name = 'gg'; put(gg, 'gg-text', 60); put(L0, 'front', 80);\ + var sub = L0.layers.add(); sub.name = 'sub'; put(sub, 'sub-text', 100);\ + var L1 = d.layers.add(); L1.name = 'other'; put(L1, 'other-text', 120); d.activeLayer = L1;\ + function names(c) { var a = []; for (var i = 0; i < c.length; i++) a.push(c[i].name); return a.join(','); }"; + +#[test] +fn a_layers_and_a_groups_text_frames_list_only_their_own_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + &format!( + "{NESTED_TYPE} vc.log([names(L0.textFrames), names(g.textFrames), names(sub.textFrames), names(L1.textFrames)]);\ + vc.log([L0.textFrames.typename, L0.textFrames.parent.name, g.textFrames.parent.typename, g.textFrames.parent.name]);\ + vc.log([L0.textFrames.getByName('front').name, L0.textFrames.index(1).name, L0.textFrames[2] === undefined]);\ + vc.log(d.textFrames.length);" + ), + ); + assert_eq!(out[0], json!(["front,back", "g-text", "sub-text", "other-text"])); + assert_eq!(out[1], json!(["TextFrames", "base", "GroupItem", "g"])); + assert_eq!(out[2], json!(["front", "back", true])); + assert_eq!(out[3], json!(6)); + // Type inside the layer's group or sublayer is not the layer's own. + let e = failure(&mut s, &format!("{NESTED_TYPE} L0.textFrames.getByName('gg-text');")); + assert!(e.contains("Not found"), "{e}"); +} + +#[test] +fn text_frames_of_a_layer_or_group_put_new_type_in_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 50})).unwrap(); + let before = undo_steps(&s); + // The rectangle is in the first layer, which becomes `base`; `other` is current while the + // collections of `base` and `g` add type. + let out = log( + &mut s, + &format!( + "var rect = app.activeDocument.pageItems[0]; {NESTED_TYPE}\ + var t = L0.textFrames.add(); t.name = 'added';\ + vc.log([t.layer.name, L0.pageItems[0].name, t.kind, d.activeLayer.name]);\ + var gt = g.textFrames.add(); gt.name = 'g-added'; vc.log([gt.parent.name, g.pageItems[0].name]);\ + var at = g.textFrames.areaText(rect); at.name = 'area'; vc.log([at.parent.name, g.pageItems[0].name, at.kind]);\ + g.textFrames.removeAll(); vc.log([names(g.pageItems), names(L0.textFrames)]);" + ), + ); + assert_eq!(out[0], json!(["base", "added", "TextType.POINTTEXT", "other"])); + assert_eq!(out[1], json!(["g", "g-added"])); + assert_eq!(out[2], json!(["g", "area", "TextType.AREATEXT"])); + // removeAll takes the group's own type and leaves the type inside its group. + assert_eq!(out[3], json!(["gg", "added,front,back"])); + assert_eq!(undo_steps(&s), before + 1); + // A locked layer and a hidden group take no new type, and the run changes nothing. + let before = undo_steps(&s); + let e = failure(&mut s, &format!("{NESTED_TYPE} L0.locked = true; L0.textFrames.add();")); + assert!(e.contains("hidden or locked"), "{e}"); + let e = failure(&mut s, &format!("{NESTED_TYPE} g.hidden = true; g.textFrames.pointText([5, 5]);")); + assert!(e.contains("hidden or locked"), "{e}"); + assert_eq!(undo_steps(&s), before); +} + +/// `textFrames.removeAll()` on type that clips a group releases the mask, so the object above the +/// type stays an ordinary member and is not made the clipping path. +#[test] +fn text_frames_remove_all_releases_a_mask_the_type_clips() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let t = s.execute("text.create", &json!({"x": 20, "y": 100, "text": "clip", "size": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b, t]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let first = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().first().map(|c| c.id); + assert_eq!(first(&s), Some(NodeId(t)), "the type is the clipping path"); + let steps = undo_steps(&s); + let out = log(&mut s, "app.activeDocument.textFrames.removeAll(); vc.log(app.activeDocument.groupItems[0].clipped);"); + assert_eq!(out, [json!(false)]); + let st = s.active().unwrap(); + assert!(!st.doc.node(g).unwrap().clips()); + assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2); + // The run is one undo step, and undoing it puts back both the type and its mask. + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.active().unwrap().doc.node(g).unwrap().clips()); + assert_eq!(first(&s), Some(NodeId(t))); +} + +#[test] +fn text_create_puts_type_in_the_layer_or_group_it_names() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let group = s.execute("object.newGroup", &json!({})).unwrap()["id"].as_u64().unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + // A new layer is current, and a locked one takes no type. + let locked = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().map(NodeId).unwrap(); + s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); + let before = undo_steps(&s); + for bad in [json!("1"), json!(rect), json!(9999), json!(locked.0)] { + assert!(s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": bad})).is_err(), "{bad}"); + } + assert_eq!(undo_steps(&s), before); + let id = s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": group})).unwrap()["id"].as_u64().unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(NodeId(id)), Some(NodeId(group))); + assert_eq!(undo_steps(&s), before + 1); +} + #[test] fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); diff --git a/crates/engine/src/tests/swatches.rs b/crates/engine/src/tests/swatches.rs index 20144d4411..ab379c2f6c 100644 --- a/crates/engine/src/tests/swatches.rs +++ b/crates/engine/src/tests/swatches.rs @@ -989,6 +989,64 @@ fn linked(hex: &str, name: &str) -> Paint { Paint::Solid { color: Color::from_hex(hex).unwrap(), swatch: Some(name.into()), tint: 1.0 } } +#[test] +fn swatch_edits_record_only_renames_and_taking_empties_the_record() { + let mut s = session(); + let uid = s.active().unwrap().uid; + run(&mut s, "swatch.new", json!({"name": "Teal", "color": "#008080"})); + run(&mut s, "swatch.edit", json!({"name": "Teal", "color": "#009090"})); + assert!(s.take_swatch_renames().is_empty()); + run(&mut s, "swatch.edit", json!({"name": "Teal", "newName": "Renamed teal"})); + assert_eq!(s.take_swatch_renames(), vec![(uid, "Teal".to_owned(), "Renamed teal".to_owned())]); + assert!(s.take_swatch_renames().is_empty()); +} + +#[test] +fn failed_batches_restore_pending_swatch_renames_after_eviction() { + let mut s = session(); + let uid = s.active().unwrap().uid; + run(&mut s, "swatch.new", json!({"name": "Teal", "color": "#008080"})); + run(&mut s, "swatch.edit", json!({"name": "Teal", "newName": "Ink 0 letter"})); + let mut commands = Vec::new(); + for i in 0..=MAX_SWATCH_RENAMES { + commands.push(json!({"command": "swatch.edit", "params": {"name": format!("Ink {i} letter"), "newName": format!("Ink {} letter", i + 1)}})); + } + commands.push(json!({"command": "command.batch", "params": {"commands": []}})); + assert!(s.execute("command.batch", &json!({"commands": commands})).is_err()); + assert!(doc(&s).swatch("Ink 0 letter").is_some()); + assert_eq!(s.take_swatch_renames(), vec![(uid, "Teal".to_owned(), "Ink 0 letter".to_owned())]); + commands.pop(); + run(&mut s, "command.batch", json!({"commands": commands})); + let renames = s.take_swatch_renames(); + let expected: Vec<_> = (1..=MAX_SWATCH_RENAMES).map(|i| (uid, format!("Ink {i} letter"), format!("Ink {} letter", i + 1))).collect(); + assert_eq!(renames, expected, "only the newest renames remain, in order"); +} + +#[test] +fn swatch_rename_previews_leave_no_record_and_confirmation_records_once() { + let mut s = session(); + let uid = s.active().unwrap().uid; + run(&mut s, "swatch.new", json!({"name": "Teal", "color": "#008080"})); + s.begin_interaction("Swatch Options").unwrap(); + for name in ["Preview teal", "Replacement teal"] { + s.preview("swatch.edit", &json!({"name": "Teal", "newName": name})).unwrap(); + assert!(doc(&s).swatch(name).is_some()); + assert!(s.take_swatch_renames().is_empty()); + } + s.cancel_interaction().unwrap(); + assert!(doc(&s).swatch("Teal").is_some()); + assert!(s.take_swatch_renames().is_empty()); + + // Swatch Options cancels its preview and runs the confirmed edit again. + s.begin_interaction("Swatch Options").unwrap(); + s.preview("swatch.edit", &json!({"name": "Teal", "newName": "Renamed teal"})).unwrap(); + assert!(s.take_swatch_renames().is_empty()); + s.cancel_interaction().unwrap(); + run(&mut s, "swatch.edit", json!({"name": "Teal", "newName": "Renamed teal"})); + assert_eq!(s.take_swatch_renames(), vec![(uid, "Teal".to_owned(), "Renamed teal".to_owned())]); + assert!(s.take_swatch_renames().is_empty()); +} + #[test] fn editing_a_global_swatch_recolours_linked_art_in_one_step() { let mut s = session(); diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index 891e7a6ba0..7af09c95e8 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -489,6 +489,9 @@ fn malformed_docx_fails_cleanly() { let store = |files: &[(&str, &[u8])]| cmd::fileio::zip::store(files).unwrap(); let document = |body: &str| format!(r#"{body}"#); assert!(place(&mut s, "a.docx", b"Plain words, not a package").is_err(), "a .docx file that isn't a ZIP archive"); + // A .docx file that starts with a local file header and has no end record. + let e = place(&mut s, "a.docx", b"PK\x03\x04 and nothing after the first header").unwrap_err(); + assert!(e.contains("isn't a ZIP package"), "{e}"); let e = place(&mut s, "a.docx", &store(&[("readme.txt", b"x")])).unwrap_err(); assert!(e.contains("no main document part"), "{e}"); let e = place(&mut s, "a.zip", &store(&[("readme.txt", b"x")])).unwrap_err(); @@ -531,6 +534,29 @@ fn malformed_docx_fails_cleanly() { longer[central + 20..central + 24].copy_from_slice(&packed.to_le_bytes()); let e = place(&mut s, "a.docx", &longer).unwrap_err(); assert!(e.contains("damaged"), "{e}"); + // A file whose directory record sets the encryption flag (bit 0) or names a compression method other than stored + // or deflated, and an end record with the values that mean a ZIP64 record holds the real ones. + let words = || store(&[("word/document.xml", document("words").as_bytes())]); + let record = |zip: &[u8]| zip.windows(4).position(|w| w == 0x0201_4b50u32.to_le_bytes()).unwrap(); + let mut encrypted = words(); + let at = record(&encrypted); + encrypted[at + 8] |= 1; + let e = place(&mut s, "a.docx", &encrypted).unwrap_err(); + assert!(e.contains("`word/document.xml` in the Word document is encrypted"), "{e}"); + let mut method = words(); + let at = record(&method); + method[at + 10..at + 12].copy_from_slice(&99u16.to_le_bytes()); + let e = place(&mut s, "a.docx", &method).unwrap_err(); + assert!(e.contains("uses compression method 99"), "{e}"); + let mut zip64 = words(); + let end = zip64.len() - 22; + zip64[end + 10..end + 12].copy_from_slice(&0xFFFFu16.to_le_bytes()); + let e = place(&mut s, "a.docx", &zip64).unwrap_err(); + assert!(e.contains("uses ZIP64 records"), "{e}"); + // One paragraph more than placed type takes: a paragraph is written when the next one starts, so 100,002 + // paragraphs write 100,001. + let e = place(&mut s, "a.docx", &store(&[("word/document.xml", document(&"".repeat(100_002)).as_bytes())])).unwrap_err(); + assert!(e.contains("too much text or formatting"), "{e}"); // Containers nested past the depth read are skipped, and a part nested deeper still is refused. let nested = |n: usize| { let deep = format!("{}deep{}", "".repeat(n), "".repeat(n)); @@ -549,6 +575,60 @@ fn malformed_docx_fails_cleanly() { assert_eq!(s.doc().unwrap().history.undo.len(), 2, "failed places leave no undo step"); } +#[test] +fn docx_parts_in_utf16_with_a_byte_order_mark_place_their_text() { + let mut s = session(); + let xml = format!(r#"Grüße 東京"#); + for (bom, le) in [([0xFF, 0xFE], true), ([0xFE, 0xFF], false)] { + let part = [&bom[..], &utf16(&xml, le)].concat(); + let zip = cmd::fileio::zip::store(&[("word/document.xml", &part[..])]).unwrap(); + let r = s.execute("file.place", &json!({"name": "a.docx", "dataBase64": vectorcraft_format::base64_encode(&zip)})).unwrap(); + assert_eq!(placed(&s, &r).0, "Grüße 東京", "little-endian: {le}"); + } +} + +/// A style's `w:basedOn` chain stops at a style already in it, and takes in at most 32 styles. +#[test] +fn docx_based_on_chains_stop_at_a_cycle_and_after_32_styles() { + let mut styles = String::from(concat!( + r#""#, + r#""#, + )); + // S0 is based on S1, S1 on S2, and so on to S32, the only one that sets a size. + for i in 0..32 { + styles += &format!(r#""#, i + 1); + } + styles += r#""#; + let para = |style: &str, text: &str| format!(r#"{text}"#); + let body = [para("A", "cycle"), para("S1", "thirty-two"), para("S0", "thirty-three"), "plain".into()].concat(); + let mut s = session(); + let r = s.execute("file.place", &json!({"name": "styles.docx", "dataBase64": vectorcraft_format::base64_encode(&docx(&body, &styles))})).unwrap(); + let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("not type") }; + let size = |word: &str| t.runs.iter().find(|r| r.text.contains(word)).map(|r| r.style.size); + assert_eq!(t.paragraph_styles()[0].justify, vectorcraft_doc::Justify::Center, "A takes its own alignment"); + assert_eq!(size("cycle"), Some(20.0), "A takes the size of B, which is based on A"); + assert_eq!(size("thirty-two"), Some(20.0), "a chain of 32 styles takes in the last one"); + assert_ne!(size("thirty-three"), Some(20.0), "a chain of 33 styles leaves the last one out"); + assert_eq!(size("thirty-three"), size("plain")); +} + +/// Run containers and table rows nested more than 64 deep are left out; ones nested 60 deep are placed. +#[test] +fn docx_run_containers_and_table_rows_nested_past_the_depth_read_are_left_out() { + let wrap = |n: usize, open: &str, close: &str, inner: &str| format!("{}{inner}{}", open.repeat(n), close.repeat(n)); + let run = |text: &str| format!("{text}"); + let tagged = |n: usize, text: &str| wrap(n, "", "", &run(text)); + let row = |n: usize, text: &str| { + let tr = format!("{}", run(text)); + format!("{}", wrap(n, "", "", &tr)) + }; + let body = format!("{}{}{}{}{}", tagged(70, "deep "), tagged(60, "kept "), run("shallow"), row(70, "deep row"), row(60, "kept row")); + let mut s = session(); + let r = s.execute("file.place", &json!({"name": "nested.docx", "dataBase64": vectorcraft_format::base64_encode(&docx(&body, ""))})).unwrap(); + assert_eq!(placed(&s, &r).0, "kept shallow\nkept row"); +} + /// The bytes of the Prls `prls`: each sprm and its operand. fn prls(prls: &[(u16, &[u8])]) -> Vec { prls.iter().flat_map(|(sprm, op)| sprm.to_le_bytes().into_iter().chain(op.iter().copied())).collect() @@ -927,6 +1007,14 @@ fn malformed_doc_fails_cleanly() { assert!(e.contains("compound file structure is damaged"), "{e}"); let e = place(&mut s, "a.doc", &compound_file(&[("WordDocument", &[0; 900])])).unwrap_err(); assert!(e.contains("doesn't start with a file information block"), "{e}"); + // A WordDocument stream whose directory entry gives one byte more than 64 MB is refused from that length, before + // any of it is read. The stream length is at byte 120 of the entry, which starts with the stream's name. + let mut large = compound_file(&[("WordDocument", &[0; 4096])]); + let name = utf16("WordDocument", true); + let entry = large.windows(name.len()).position(|w| w == name).unwrap(); + large[entry + 120..entry + 128].copy_from_slice(&((64u64 << 20) + 1).to_le_bytes()); + let e = place(&mut s, "a.doc", &large).unwrap_err(); + assert!(e.contains("too large to place (its WordDocument stream holds more than 64 MB)"), "{e}"); let e = place(&mut s, "a.doc", &Word97 { nfib: 0x0065, ..words() }.build()).unwrap_err(); assert!(e.contains("Word 6.0 or Word 95"), "{e}"); let e = place(&mut s, "a.doc", &Word97 { flags: 0x0100, ..words() }.build()).unwrap_err(); diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 656a5689f8..746537db05 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -356,6 +356,13 @@ fn slices_give_one_image_each_and_a_page() { assert_eq!(f.len(), n); let html = String::from_utf8(f[0].1.clone()).unwrap(); assert!(html.contains("Hi") && html.contains("background: #ffffff;") && html.contains("justify-content: center")); + // Over the matte, at the bottom right. + run(&mut s, "object.slice.options", json!({"background": "matte", "hAlign": "right", "vAlign": "bottom"})); + let f = files(&run(&mut s, "document.exportForWeb", json!({"output": "html", "matte": "#ffff00"}))); + let html = String::from_utf8(f[0].1.clone()).unwrap(); + let cell = html.lines().find(|l| l.contains("Hi")).unwrap_or_else(|| panic!("the No Image cell in {html}")); + assert!(cell.contains("background: #ffff00;"), "{cell}"); + assert!(cell.contains("justify-content: flex-end;") && cell.contains("align-items: flex-end;"), "{cell}"); // Selected slices only. run(&mut s, "object.slice.select", json!({"slices": [a]})); let f = files(&run(&mut s, "document.exportForWeb", json!({"slices": "selected"}))); @@ -367,6 +374,14 @@ fn slices_give_one_image_each_and_a_page() { assert_eq!(run(&mut s, "document.exportForWeb.preview", json!({}))["slices"], n - 1); let one_slice = run(&mut s, "document.exportForWeb.preview", json!({"slice": layout[0]["number"]})); assert_eq!((one_slice["width"].as_f64(), one_slice["height"].as_f64()), (layout[0]["width"].as_f64(), layout[0]["height"].as_f64())); + // An HTML Text slice: the type's text, escaped, with its lines joined by
. + let t = run(&mut s, "text.create", json!({"x": 20, "y": 150, "text": "A&B\nC"}))["id"].as_u64().unwrap(); + run(&mut s, "object.slice.make", json!({"ids": [t]})); + run(&mut s, "select.set", json!({"ids": [t]})); + run(&mut s, "object.slice.options", json!({"kind": "htmlText"})); + let f = files(&run(&mut s, "document.exportForWeb", json!({"output": "html"}))); + let html = String::from_utf8(f[0].1.clone()).unwrap(); + assert!(html.contains(">A&B
C"), "{html}"); } /// Save for Web writes the image of a slice named after a Windows device (`aux`, `NUL`, `COM1`…) diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 94f72f6441..37d1282f26 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -409,11 +409,14 @@ impl Session { /// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when /// the Selection tool keeps a Cmd press on a selected object to select the object behind it /// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd - /// press armed ([`Self::behind_armed`]). + /// press armed ([`Self::behind_armed`]); none either when the active tool keeps the press + /// ([`vectorcraft_tools::Tool::keeps_cmd_press`]), as Direct Selection keeps one on a shown + /// direction handle to mirror the opposite handle. fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> { let id = self.lent_tool(self.tool.id(), mods)?; let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p)); - (!behind).then_some(id) + let kept = !behind && self.with_tool_cx(view, |t, cx| t.keeps_cmd_press(cx, p, *mods)); + (!behind && !kept).then_some(id) } /// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks @@ -1360,6 +1363,11 @@ impl Session { self.tool.busy() } + /// Whether a tool began or joined the active document's interaction. + pub fn interaction_joined_by_tool(&self) -> bool { + self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.tool_joined) + } + /// Is the pointer button held: was the last pointer event a press or a drag, not a release or a /// move? A tool that is busy while the button is not held is waiting between its clicks (the /// Dimension tool after its first point). @@ -1823,6 +1831,7 @@ impl Session { } /// Apply tool actions. Errors from previews are reported but keep the interaction alive. + /// Headless sessions deliver plug-in events after the outer actions finish. pub fn apply_actions(&mut self, acts: Vec) -> Result> { // The tool acts on its own interaction, which a command from outside it may have set aside. if !acts.is_empty() { @@ -1851,6 +1860,7 @@ impl Session { self.back_to_painter = outer_painter; if !outer && self.depth == 0 { self.trim_histories(); + self.plugin_events_after_command(); } r } @@ -1863,10 +1873,11 @@ impl Session { // The snapshot of the interaction open before, which the tool's drag then joins. let open = self.active().and_then(|st| st.interaction.as_ref()).map(|it| std::sync::Arc::as_ptr(&it.doc)); self.begin_interaction(&label)?; - if let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut()) - && open != Some(std::sync::Arc::as_ptr(&it.doc)) - { - it.tool = true; + if let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut()) { + it.tool_joined = true; + if open != Some(std::sync::Arc::as_ptr(&it.doc)) { + it.tool = true; + } } } Action::Preview(cmd, p) => { diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index bcc712e844..646e586400 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1072,6 +1072,9 @@ fn structured_junk() { ("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})), ("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})), ("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})), + ("addon.document.floodFillArtboards", json!({"artboards": [1e308, -1, null, u64::MAX], "color": [1e308]})), + ("addon.document.floodFillArtboards", json!({"all": true, "artboards": "x", "layer": {"name": 3}})), + ("addon.document.floodFillArtboards", json!({"color": {"c": f64::MAX, "m": -1e308, "y": 0, "k": 0}, "layer": "\u{0}"})), // Packaging Tools add-on. ("addon.packaging.setRole", json!({"role": "cut", "ids": [u64::MAX], "overprint": "no"})), ("addon.packaging.setRole", json!({"role": ["crease"], "ids": "all"})), diff --git a/crates/engine/tests/it/direct_handle_mirror.rs b/crates/engine/tests/it/direct_handle_mirror.rs index bfe8db75a0..732319f675 100644 --- a/crates/engine/tests/it/direct_handle_mirror.rs +++ b/crates/engine/tests/it/direct_handle_mirror.rs @@ -332,6 +332,70 @@ fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() { assert_eq!(s.doc().unwrap().history.undo.len(), before.undo); } +#[test] +fn direct_handle_cmd_held_before_pressing_a_handle_mirrors_instead_of_moving_the_path() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + let end = Point::new(180.0, 100.0); + pointer(&mut s, PointerKind::Down, end, cmd()); + assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a shown handle is not lent to the Selection tool"); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(s.tool_id(), "directSelection"); +} + +#[test] +fn direct_handle_cmd_shift_held_before_pressing_a_handle_constrains_and_mirrors() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + let p = anchor(&s, id).p; + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), shifted); + assert_eq!(s.tool_id(), "directSelection"); + let raw = Point::new(180.0, 150.0); + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(anchor(&s, id), constrained(p, raw), AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, raw, shifted); +} + +#[test] +fn direct_handle_cmd_press_on_a_handle_under_a_bounding_box_handle_still_lends_selection() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + // A second object widens the selection's bounding box so its top-middle handle lands on the + // curve's outgoing handle end at (180, 100). + let rect = run(&mut s, "path.create", json!({"anchors": [{"x": 330, "y": 150}, {"x": 340, "y": 150}, {"x": 340, "y": 200}], "closed": true})); + run(&mut s, "select.set", json!({"ids": [id.0, rect["id"]]})); + let boxed = ViewInfo { show_bbox: true, ..view() }; + let end = Point::new(180.0, 100.0); + s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y).with_mods(cmd()), boxed).unwrap(); + assert_eq!(s.tool_id(), "selection", "the bounding box handle keeps the press for the lent Selection tool"); + s.pointer(&PointerEvent::new(PointerKind::Up, end.x, end.y).with_mods(cmd()), boxed).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); +} + +#[test] +fn direct_handle_cmd_alt_before_pressing_a_handle_still_lends_group_selection() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let a = anchor(&s, id); + let both = Mods { alt: true, ..cmd() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), both); + assert_eq!(s.tool_id(), "groupSelection", "Cmd+Alt keeps its Group Selection loan on a handle"); + pointer(&mut s, PointerKind::Up, Point::new(180.0, 100.0), both); + assert_eq!(s.tool_id(), "directSelection"); + assert_eq!(anchor(&s, id), a); +} + #[test] fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() { let mut s = session(); @@ -490,6 +554,22 @@ fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() { assert_content(&s, &after); } +#[test] +fn direct_handle_cmd_held_before_pressing_a_blend_spine_handle_mirrors() { + let mut s = session(); + let id = blend(&mut s); + let (a, keys, _) = blend_state(&s, id); + pointer(&mut s, PointerKind::Down, a.h_out, cmd()); + assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a spine handle is not lent to the Selection tool"); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + pointer(&mut s, PointerKind::Up, q, cmd()); + let (after, after_keys, _) = blend_state(&s, id); + near(after.p, a.p); + assert_mirrored(after, q, AnchorKind::Smooth); + assert_eq!(after_keys, keys, "the key objects did not move"); +} + #[test] fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() { let mut s = session(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 6b8965dd7f..1b959de54d 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,11 +37,17 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("Preferences.prototype.setBooleanPreference", "app.preferences.setBooleanPreference(k, true);", "preferences"), + ("Preferences.prototype.setIntegerPreference", "app.preferences.setIntegerPreference(k, 1);", "preferences"), + ("Preferences.prototype.setRealPreference", "app.preferences.setRealPreference(k, 0.5);", "preferences"), + ("Preferences.prototype.setStringPreference", "app.preferences.setStringPreference(k, s);", "preferences"), + ("Preferences.prototype.removePreference", "app.preferences.removePreference(k);", "preferences"), ("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"), ("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"), ("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"), ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), + ("Document.prototype.imageCapture", "app.activeDocument.imageCapture(f);", "filesWritten"), ("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"), ]; @@ -50,11 +56,16 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// change anything outside it. The document model (`app`, its classes and the enumerations) acts on /// the open documents; `Document.close` closes a document, and saves it to its own file only when it /// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and -/// `Document.path` only name its file and folder. `app.open` reads the file it is given. +/// `Document.path` only name its file and folder. `app.open` reads the file it is given, and +/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. Reading a +/// preference changes nothing, and the matrix functions return new records. `app.copy` and `app.cut` +/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit › +/// Copy does. const INSIDE: &[(&str, &str)] = &[ - ("", "$ 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"), + ("", "$ %vcPaletteEvent File Folder UnitValue Window alert confirm localize prompt toSource"), + ("Window.", "__vcPaletteEvent alert confirm length prompt prototype"), + ("%vcPaletteEvent.", "length"), + ("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show update"), ("Object.prototype.", "reflect toSource"), ("UnitValue.", "baseUnit baseUnit= length prototype"), ("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="), @@ -87,20 +98,26 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ - DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ - Documents ElementPlacement Layer PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PointType \ - PolarityValues RulerUnits ScreenMode selection selection= StrokeCap StrokeJoin Tag Tags Transformation View Views \ - ZOrderMethod", + "activeDocument activeDocument= app Application Artboard Artboards BlendModes CompoundPathItem CompoundPathItems \ + CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ + DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \ + GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints \ + PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \ + selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod", ), ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \ - executeMenuCommand getIsFileOpen loadAction loadAction= open PPDFileList printPresetsList printerList redo redraw \ - selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= userInteractionLevel \ + "activeDocument activeDocument= beep beep= concatenateMatrix concatenateRotationMatrix concatenateScaleMatrix \ + concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \ + executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \ + invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \ + printerList redo redraw selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= \ + userInteractionLevel \ userInteractionLevel=", ), + ("Preferences.", "prototype"), + ("Preferences.prototype.", "constructor getBooleanPreference getIntegerPreference getRealPreference getStringPreference typename"), ("DocumentPreset.", "prototype"), ( "DocumentPreset.prototype.", @@ -114,13 +131,13 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= characterStyles close constructor convertCoordinate \ + "activeLayer activeLayer= artboards characterStyles close compoundPathItems constructor convertCoordinate \ defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \ defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \ defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \ defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \ defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \ - groupItems= height layers layers= name pageItems paragraphStyles parent path pathItems rulerOrigin \ + height layers name pageItems paragraphStyles parent path pathItems placedItems rasterItems rulerOrigin \ rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \ symbols symbols= tags textFrames toString typename views width", ), @@ -129,29 +146,96 @@ const INSIDE: &[(&str, &str)] = &[ ("View.", "prototype"), ("View.prototype.", "bounds centerPoint centerPoint= constructor parent screenMode screenMode= toString typename zoom zoom="), ("Layer.", "prototype"), - ("Layer.prototype.", "constructor name toString typename"), + ( + "Layer.prototype.", + "artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \ + dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ + locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ + preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ + toString typename visible visible= zOrder zOrderPosition", + ), + ("Layers.", "prototype"), + ("Layers.prototype.", "add constructor getByName index length parent removeAll toString typename"), + ("GroupItem.", "prototype"), + ( + "GroupItem.prototype.", + "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ + rasterItems rasterItems= symbolItems symbolItems= textFrames", + ), + ("GroupItems.", "prototype"), + ("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll toString typename"), + ("CompoundPathItem.", "prototype"), + ("CompoundPathItem.prototype.", "constructor pathItems"), + ("CompoundPathItems.", "prototype"), + ("CompoundPathItems.prototype.", "add constructor getByName index length parent removeAll toString typename"), + ("Artboard.", "prototype"), + ( + "Artboard.prototype.", + "artboardRect artboardRect= constructor name name= parent remove rulerOrigin rulerOrigin= rulerPAR rulerPAR= \ + showCenter showCenter= showCrossHairs showCrossHairs= showSafeAreas showSafeAreas= toString typename", + ), + ("Artboards.", "prototype"), + ( + "Artboards.prototype.", + "add constructor getActiveArtboardIndex getByName index insert length parent remove setActiveArtboardIndex \ + toString typename", + ), ("PageItems.", "prototype"), ("PageItems.prototype.", "constructor getByName index length parent removeAll toString typename"), ("PageItem.", "prototype"), ( "PageItem.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ - controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ - left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ - position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags toString top top= transform \ - transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ + controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer left \ + left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ + position= remove resize rotate selected selected= sliced sliced= tags toString top top= transform translate \ + typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ("PlacedItems.", "prototype"), + ("PlacedItems.prototype.", "add constructor getByName index length parent removeAll typename"), + ("PlacedItem.", "prototype"), + ("PlacedItem.prototype.", "boundingBox constructor contentVariable contentVariable= embed file file= matrix matrix= relink trace"), + ("PluginItem.", "prototype"), + ("PluginItem.prototype.", "constructor isTracing tracing"), + ("RasterItems.", "prototype"), + ("RasterItems.prototype.", "constructor getByName index length parent removeAll typename"), + ("RasterItem.", "prototype"), + ( + "RasterItem.prototype.", + "bitsPerChannel boundingBox channels colorants colorants= colorize colorize= colorizedGrayscale constructor \ + contentVariable contentVariable= embedded embedded= file imageColorSpace matrix matrix= overprint overprint= status \ + trace transparent", + ), + ("TracingObject.", "prototype"), + ( + "TracingObject.prototype.", + "anchorCount areaCount areaCount= constructor expandTracing imageResolution parent pathCount releaseTracing sourceArt \ + tracingOptions typename usedColorCount", + ), + ("TracingOptions.", "prototype"), + ( + "TracingOptions.prototype.", + "constructor cornerAngle cornerAngle= fills fills= ignoreWhite ignoreWhite= livePaintOutput livePaintOutput= \ + loadFromPreset maxColors maxColors= maxStrokeWeight maxStrokeWeight= minArea minArea= minStrokeLength \ + minStrokeLength= outputToSwatches outputToSwatches= palette palette= parent pathFitting pathFitting= \ + preprocessBlur preprocessBlur= preset resample resample= resampleResolution resampleResolution= storeToPreset \ + strokes strokes= threshold threshold= tracingMode tracingMode= typename viewRaster viewRaster= viewVector \ + viewVector=", + ), ("PathItems.", "prototype"), - ("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"), + ( + "PathItems.prototype.", + "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename", + ), ("PathItem.", "prototype"), ( "PathItem.prototype.", "area clipping closed closed= constructor evenodd evenodd= fillColor fillColor= fillOverprint fillOverprint= filled \ - filled= guides guides= length pathPoints polarity polarity= resize resolution resolution= rotate selectedPathPoints \ + filled= guides guides= length pathPoints polarity polarity= resolution resolution= selectedPathPoints \ setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \ strokeDashes strokeDashes= strokeJoin strokeJoin= strokeMiterLimit strokeMiterLimit= strokeOverprint strokeOverprint= \ - strokeWidth strokeWidth= stroked stroked= translate", + strokeWidth strokeWidth= stroked stroked=", ), ("PathPoints.", "prototype"), ("PathPoints.prototype.", "add constructor index length parent removeAll typename"), @@ -199,6 +283,13 @@ const INSIDE: &[(&str, &str)] = &[ PDFOverprint PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes SVGCSSPropertyLocation SVGDTDVersion \ SVGDocumentEncoding SVGFontSubsetting SVGFontType SaveOptions UserInteractionLevel", ), + ("", "AutoCADColors AutoCADCompatibility AutoCADExportFileFormat AutoCADExportOption AutoCADRasterFormat AutoCADUnit"), + ("AutoCADColors.", "Max16Colors Max256Colors Max8Colors TrueColors"), + ("AutoCADCompatibility.", "AutoCADRelease13 AutoCADRelease14 AutoCADRelease15 AutoCADRelease18 AutoCADRelease21 AutoCADRelease24"), + ("AutoCADExportFileFormat.", "DWG DXF"), + ("AutoCADExportOption.", "MaximizeEditability PreserveAppearance"), + ("AutoCADRasterFormat.", "JPEG PNG"), + ("AutoCADUnit.", "Centimeters Inches Millimeters Picas Pixels Points"), ("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"), ( "ColorDestination.", @@ -237,12 +328,30 @@ const INSIDE: &[(&str, &str)] = &[ ), ("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"), ("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"), - ("ExportType.", "AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"), + ("ExportType.", "AUTOCAD AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"), ("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"), ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The enumerations of rasterizing and the document's rasterize and window capture methods. + ("", "AntiAliasingMethod RasterizationColorModel"), + ("Document.prototype.", "rasterize windowCapture windowCapture="), + ("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"), + ("RasterizationColorModel.", "BITMAP DEFAULTCOLORMODEL GRAYSCALE"), + // The enumerations of placed and raster items. + ("", "ImageColorSpace RasterLinkState"), + ("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"), + ("RasterLinkState.", "DATAFROMFILE DATAMODIFIED NODATA"), + // The enumerations of tracings. + ("", "TracingModeType ViewRasterType ViewVectorType"), + ("TracingModeType.", "TRACINGMODEBLACKANDWHITE TRACINGMODECOLOR TRACINGMODEGRAY"), + ("ViewRasterType.", "TRACINGVIEWRASTERADJUSTEDIMAGE TRACINGVIEWRASTERNOIMAGE TRACINGVIEWRASTERORIGINALIMAGE TRACINGVIEWRASTERTRANSPARENTIMAGE"), + ( + "ViewVectorType.", + "TRACINGVIEWVECTORNOTRACINGRESULT TRACINGVIEWVECTOROUTLINES TRACINGVIEWVECTOROUTLINESWITHTRACING \ + TRACINGVIEWVECTORTRACINGRESULT", + ), // The print option classes and the enumerations of printing. ( "", @@ -348,12 +457,14 @@ const INSIDE: &[(&str, &str)] = &[ "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= \ + duplicate duplicate= end end= fillColor fillColor= 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 \ + spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= strokeColor strokeColor= \ + strokeWeight strokeWeight= textFont textFont= textRanges \ textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ verticalScale= words", ), @@ -366,9 +477,9 @@ const INSIDE: &[(&str, &str)] = &[ ("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=", + "autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \ + leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \ + strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=", ), ("ParagraphAttributes.", "prototype"), ( @@ -383,9 +494,9 @@ const INSIDE: &[(&str, &str)] = &[ ("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=", + "autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \ + leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \ + strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=", ), ("ParagraphStyles.", "prototype"), ("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"), @@ -421,12 +532,12 @@ const INSIDE: &[(&str, &str)] = &[ "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 \ + contents contents= deSelect deSelect= duplicate duplicate= end end= fillColor fillColor= 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 \ + strikeThrough= strokeColor strokeColor= strokeWeight strokeWeight= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ underline underline= verticalScale verticalScale= words", ), ("StoryCharacters.", "prototype"), @@ -455,11 +566,12 @@ const INSIDE: &[(&str, &str)] = &[ ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types -/// other than `PathItem`, the color classes, and the save and export option classes. -const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \ - IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \ - SymbolItem cmykColor EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions \ - PDFSaveOptions"; +/// that have no members of their own, the color classes, and the save, export, rasterize and image +/// capture option classes. +const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \ + MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \ + EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions \ + ImageCaptureOptions RasterizeOptions"; /// 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/several_handles.rs b/crates/engine/tests/it/several_handles.rs index 7b5469c278..45b2e39f19 100644 --- a/crates/engine/tests/it/several_handles.rs +++ b/crates/engine/tests/it/several_handles.rs @@ -119,6 +119,78 @@ fn picked_handles_stay_picked_after_they_are_dragged() { near(anchor(&s, id, 2).h_in, Point::new(310.0, 170.0)); } +/// With two handles picked, Cmd/Ctrl held before the press on one of them drags that handle alone +/// and mirrors its opposite handle; the other picked handle stays where it is. +#[test] +fn a_cmd_drag_of_one_of_two_picked_handles_mirrors_its_opposite_handle() { + 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()); + let cmd = Mods { cmd: true, ..Mods::default() }; + drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd); + assert_eq!(s.tool_id(), "directSelection"); + let a = anchor(&s, id, 1); + near(a.h_out, Point::new(180.0, 160.0)); + near(a.h_in, Point::new(20.0, 40.0)); + assert_eq!(a.kind, AnchorKind::Smooth); + near(anchor(&s, id, 2).h_in, Point::new(300.0, 140.0)); +} + +/// Both handles stay picked after a Cmd/Ctrl drag of one of them: a drag of the other without +/// Cmd/Ctrl then moves both. +#[test] +fn picked_handles_stay_picked_after_a_cmd_drag_of_one_of_them() { + 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()); + let cmd = Mods { cmd: true, ..Mods::default() }; + drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd); + drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default()); + near(anchor(&s, id, 1).h_out, Point::new(190.0, 160.0)); + near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0)); +} + +/// Both handles stay picked after a Cmd/Ctrl+Shift drag of one of them, and after Escape during +/// one. +#[test] +fn picked_handles_stay_picked_after_a_cmd_shift_drag_of_one_of_them() { + 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()); + let cmd_shift = Mods { cmd: true, shift: true, ..Mods::default() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd_shift); + pointer(&mut s, PointerKind::Drag, Point::new(220.0, 100.0), cmd_shift); + if escape { + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + } + pointer(&mut s, PointerKind::Up, Point::new(220.0, 100.0), cmd_shift); + let x = if escape { 180.0 } else { 220.0 }; + near(anchor(&s, id, 1).h_out, Point::new(x, 100.0)); + drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default()); + near(anchor(&s, id, 1).h_out, Point::new(x + 10.0, 100.0)); + near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0)); + } +} + +/// Escape during a Cmd/Ctrl drag of one of two picked handles puts the handle back and leaves both +/// picked. +#[test] +fn escape_during_a_cmd_drag_of_a_picked_handle_keeps_both_picked() { + 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()); + let cmd = Mods { cmd: true, ..Mods::default() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd); + pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + pointer(&mut s, PointerKind::Up, Point::new(180.0, 160.0), cmd); + near(anchor(&s, id, 1).h_out, Point::new(180.0, 100.0)); + drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default()); + near(anchor(&s, id, 1).h_out, Point::new(190.0, 100.0)); + near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.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] diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 8c3b4ad12d..aaeb97ccf4 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -16261,6 +16261,281 @@ fn dynamic_symbols_and_their_instance_changes_survive_a_round_trip() { assert!(got[2].is_empty()); } +/// A document with one instance of dynamic symbol "Leaf", whose art is `art`, with changes `overrides`. +fn dynamic_instance_doc(art: impl FnOnce(&mut Document) -> Node, overrides: Vec) -> Document { + let mut doc = Document::new(200.0, 100.0); + let art = art(&mut doc); + doc.symbols.push(Symbol { dynamic: true, name: "Leaf".into(), art: Arc::new(art) }); + let layer = doc.layers[0].id; + let mut i = instance(&mut doc, "Leaf", Affine::translate((10.0, 10.0))); + i.extras_mut().symbol_overrides = overrides; + doc.insert(Some(layer), usize::MAX, i).unwrap(); + doc +} + +/// Exports `doc`, checks that its one instance is written as its art with [`writer::SYMBOL_ART`], and +/// returns the fills of the paths it reads back as and the opacities of all its objects. +fn dynamic_instance_as_art(doc: &Document) -> (Vec, Vec) { + let out = export_ai_editing(doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::SYMBOL_CHANGES), "{:?}", out.warnings); + let back = read_back(doc); + let kids = back.layers[0].children().unwrap(); + assert!(!kids.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })), "the instance stays live"); + let (mut fills, mut opacities) = (vec![], vec![]); + for k in kids { + vectorcraft_doc::swatches::walk_with_masks(k, &mut |n| { + opacities.push(n.opacity); + if matches!(n.kind, NodeKind::Path { .. }) { + fills.extend(n.appearance.items.iter().filter_map(|i| match i { + AppearanceItem::Fill(f) => Some(f.paint.clone()), + _ => None, + })); + } + }); + } + (fills, opacities) +} + +#[test] +fn a_dynamic_instance_whose_changed_part_follows_an_empty_path_is_written_as_its_art() { + let red = Color::rgb(1.0, 0.0, 0.0); + let doc = dynamic_instance_doc( + |doc| { + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + let sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + Node::group(doc.alloc_id(), vec![Arc::new(empty), Arc::new(sq)]) + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![1], fill: Some(solid(red)), ..Default::default() }], + ); + let (fills, _) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); +} + +#[test] +fn a_dynamic_instance_whose_art_loses_an_empty_path_after_the_changed_part_is_written_as_its_art() { + let red = Color::rgb(1.0, 0.0, 0.0); + let doc = dynamic_instance_doc( + |doc| { + let sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + Node::group(doc.alloc_id(), vec![Arc::new(sq), Arc::new(empty)]) + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(solid(red)), ..Default::default() }], + ); + let (fills, _) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); +} + +#[test] +fn a_dynamic_instance_stays_live_when_an_empty_path_after_its_changed_part_moves_nothing() { + let red = Color::rgb(1.0, 0.0, 0.0); + let doc = dynamic_instance_doc( + |doc| { + let a = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let b = square(doc, Rect::new(20.0, 0.0, 30.0, 10.0), LEAF); + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + Node::group(doc.alloc_id(), vec![Arc::new(a), Arc::new(b), Arc::new(empty)]) + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(solid(red)), ..Default::default() }], + ); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SYMBOL_CHANGES]); + let back = read_back(&doc); + let kids = back.layers[0].children().unwrap(); + assert!(matches!(kids[0].kind, NodeKind::SymbolInstance { .. })); + assert_eq!(kids[0].extras().symbol_overrides, doc.layers[0].children().unwrap()[0].extras().symbol_overrides); +} + +#[test] +fn a_dynamic_instance_with_a_named_or_transparent_root_and_one_kept_child_is_written_as_its_art() { + for named in [true, false] { + let doc = dynamic_instance_doc( + |doc| { + let sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + let mut root = Node::group(doc.alloc_id(), vec![Arc::new(sq), Arc::new(empty)]); + if named { + root.name = Some("Branch".into()); + } else { + root.opacity = 0.5; + } + root + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), ..Default::default() }], + ); + let (fills, opacities) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); + if !named { + assert!(opacities.iter().any(|o| (o - 0.5).abs() < 1e-3), "{opacities:?}"); + } + } +} + +#[test] +fn a_dynamic_instance_with_a_root_override_and_one_kept_child_is_written_as_its_art() { + let doc = dynamic_instance_doc( + |doc| { + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::default()); + let mut sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + sq.opacity = 0.5; + Node::group(doc.alloc_id(), vec![Arc::new(empty), Arc::new(sq)]) + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![], opacity: Some(0.5), ..Default::default() }], + ); + dynamic_instance_as_art(&doc); + let back = read_back(&doc); + fn path_opacities(n: &Node, parent: f32, out: &mut Vec) { + let opacity = parent * n.opacity; + if matches!(n.kind, NodeKind::Path { .. }) { + out.push(opacity); + } + for child in n.children().into_iter().flatten() { + path_opacities(child, opacity, out); + } + } + let mut opacities = vec![]; + for child in back.layers[0].children().unwrap() { + path_opacities(child, 1.0, &mut opacities); + } + assert_eq!(opacities.len(), 1, "{opacities:?}"); + assert!((opacities[0] - 0.25).abs() < 1e-3, "{opacities:?}"); +} + +#[test] +fn a_dynamic_instance_whose_override_targets_an_omitted_child_is_written_as_its_art() { + for nested in [false, true] { + let doc = dynamic_instance_doc( + |doc| { + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::default()); + let a = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let b = square(doc, Rect::new(20.0, 0.0, 30.0, 10.0), LEAF); + let root = Node::group(doc.alloc_id(), vec![Arc::new(empty), Arc::new(a), Arc::new(b)]); + if nested { Node::group(doc.alloc_id(), vec![Arc::new(root)]) } else { root } + }, + vec![vectorcraft_doc::SymbolOverride { + path: if nested { vec![0, 0] } else { vec![0] }, + fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), + ..Default::default() + }], + ); + let (fills, _) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 2, "{fills:?}"); + assert!(fills.iter().all(|f| *f == solid(LEAF)), "the squares keep their original fills: {fills:?}"); + } +} + +#[test] +fn a_dynamic_instance_with_a_root_note_and_one_kept_child_is_written_as_its_art() { + let doc = dynamic_instance_doc( + |doc| { + let sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::default()); + let mut root = Node::group(doc.alloc_id(), vec![Arc::new(sq), Arc::new(empty)]); + root.extras_mut().attrs = Some(Box::new(vectorcraft_doc::ObjectAttributes { note: "Branch note".into(), ..Default::default() })); + root + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), ..Default::default() }], + ); + let (fills, _) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); +} + +#[test] +fn dynamic_instances_on_a_large_canvas_or_in_clipped_art_do_not_serialize_overrides() { + for clipped in [false, true] { + let o = vectorcraft_doc::SymbolOverride { fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), ..Default::default() }; + let mut doc = dynamic_instance_doc(|doc| square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF), vec![o; 40_000]); + if clipped { + let layer = doc.layers[0].id; + let id = doc.layers[0].children().unwrap()[0].id; + let art = doc.remove(id).unwrap(); + let outline = square(&mut doc, Rect::new(0.0, 0.0, 15.0, 15.0), LEAF); + let clip = group(&mut doc, vec![outline], false); + let g = group(&mut doc, vec![clip, (*art).clone()], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + } else { + doc = on_large_canvas(doc); + } + writer::OVERRIDE_SERIALIZATIONS.with(|count| count.set(0)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + writer::OVERRIDE_SERIALIZATIONS.with(|count| assert_eq!(count.get(), 0)); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::SYMBOL_CHANGES), "{:?}", out.warnings); + } +} + +#[test] +fn a_live_dynamic_instance_serializes_its_overrides_once() { + let doc = dynamic_instance_doc( + |doc| square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF), + vec![vectorcraft_doc::SymbolOverride { opacity: Some(0.5), ..Default::default() }], + ); + writer::OVERRIDE_SERIALIZATIONS.with(|count| count.set(0)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + writer::OVERRIDE_SERIALIZATIONS.with(|count| assert_eq!(count.get(), 1)); + assert_eq!(out.warnings, [writer::SYMBOL_CHANGES]); + let back = read_back(&doc); + let got = &back.layers[0].children().unwrap()[0]; + assert!(matches!(got.kind, NodeKind::SymbolInstance { .. })); + assert_eq!(got.extras().symbol_overrides, doc.layers[0].children().unwrap()[0].extras().symbol_overrides); +} + +#[test] +fn a_dynamic_instance_stays_live_with_an_out_of_range_override_after_an_empty_path() { + let doc = dynamic_instance_doc( + |doc| { + let a = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let b = square(doc, Rect::new(20.0, 0.0, 30.0, 10.0), LEAF); + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + Node::group(doc.alloc_id(), vec![Arc::new(a), Arc::new(b), Arc::new(empty)]) + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![5], fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), ..Default::default() }], + ); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SYMBOL_CHANGES]); + let back = read_back(&doc); + let got = &back.layers[0].children().unwrap()[0]; + assert!(matches!(got.kind, NodeKind::SymbolInstance { .. })); + assert_eq!(got.extras().symbol_overrides, doc.layers[0].children().unwrap()[0].extras().symbol_overrides); + assert!(vectorcraft_doc::symbol_overrides::part(&doc.symbols[0].art, &[5]).is_none()); + assert!(vectorcraft_doc::symbol_overrides::part(&back.symbols[0].art, &[5]).is_none()); +} + +#[test] +fn a_dynamic_instance_whose_changed_part_follows_an_empty_compound_path_is_written_as_its_art() { + let doc = dynamic_instance_doc( + |doc| { + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + let compound = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(empty)], rule: FillRule::EvenOdd }); + let sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let mut root = Node::group(doc.alloc_id(), vec![Arc::new(compound), Arc::new(sq)]); + root.name = Some("Branch".into()); + root + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![1], fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), ..Default::default() }], + ); + let (fills, _) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); +} + +#[test] +fn a_dynamic_instance_whose_changes_pass_the_size_limit_is_written_as_its_art() { + let red = Color::rgb(1.0, 0.0, 0.0); + let o = vectorcraft_doc::SymbolOverride { fill: Some(solid(red)), opacity: Some(0.5), ..Default::default() }; + let doc = dynamic_instance_doc(|doc| square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF), vec![o; 40_000]); + assert!(serde_json::to_vec(&doc.layers[0].children().unwrap()[0].extras().symbol_overrides).unwrap().len() > 1 << 20); + let (fills, opacities) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); + assert!(opacities.iter().any(|o| (o - 0.5).abs() < 1e-3), "{opacities:?}"); +} + #[test] fn static_symbols_write_no_dynamic_entries() { let mut doc = dynamic_doc(); diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index b8ea88a1fd..020b7bd901 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -50,7 +50,7 @@ pub(super) use paints::{ }; pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode}; #[cfg(test)] -pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS}; +pub(super) use symbols::{MISSING_SYMBOL, OVERRIDE_SERIALIZATIONS, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS}; #[cfg(test)] pub(super) use texts::{FONT_RESOLVES, RESOLVE_EACH_RUN, TYPE_ATTRIBUTES}; #[cfg(test)] @@ -269,6 +269,7 @@ pub(super) struct Writer<'a> { /// Whether each symbol's art paints with a pattern, nested symbols included /// ([`Self::symbol_paints_pattern`]). patterned_symbols: HashMap, + symbol_omissions: HashMap<*const Node, symbols::OmissionFacts>, /// Pattern tiles were written in the art being written ([`Self::define_symbol`] starts it over /// for each symbol's art). wrote_pattern: bool, @@ -289,6 +290,7 @@ pub(super) struct Writer<'a> { symbol_scales: HashMap, /// The entries a symbol's dictionary adds to its art's dictionary, and the art's id. root_entries: Option<(vectorcraft_doc::NodeId, String)>, + /// The override dictionary entries prepared by [`Self::live_instance`], and the instance's id. instance_entries: Option<(vectorcraft_doc::NodeId, String)>, /// The objects that may be written with an art style, as they were before baking, by id /// ([`styles::styled_objects`]). @@ -402,6 +404,7 @@ impl<'a> Writer<'a> { defining_symbols: vec![], pattern_symbols: HashMap::new(), patterned_symbols: HashMap::new(), + symbol_omissions: HashMap::new(), wrote_pattern: false, pattern_written: HashSet::new(), wrote_fixed: false, diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index 72966faf81..c3249ed756 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -497,3 +497,60 @@ impl Writer<'_> { s.push_str("/End X!\n"); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A closed outline through `points`, each side a straight segment. + fn outline(points: &[(f64, f64)]) -> PathData { + let mut bp = kurbo::BezPath::new(); + for (i, &(x, y)) in points.iter().enumerate() { + if i == 0 { + bp.move_to((x, y)); + } else { + bp.line_to((x, y)); + } + } + bp.close_path(); + PathData::from_bezpath(&bp) + } + + fn assert_near(got: Option, want: (f64, f64)) { + let Some(got) = got else { panic!("no grid point") }; + assert!(got.distance(Point::new(want.0, want.1)) < 1e-9, "{got:?} is not {want:?}"); + } + + /// A top object with two segments on each side is written as a 2 × 2 grid whose middle point + /// blends the four sides' middles less the four corners. + #[test] + fn a_top_object_with_two_segments_a_side_gets_its_middle_point_from_the_sides() { + let path = outline(&[(30.0, 10.0), (100.0, 0.0), (170.0, 10.0), (180.0, 50.0), (170.0, 90.0), (100.0, 90.0), (30.0, 90.0), (30.0, 50.0)]); + let Some((rows, cols, pts)) = top_object_grid(&path, Some([0, 2, 4, 6])) else { panic!("the outline is written as a grid") }; + assert_eq!((rows, cols), (2, 2)); + // (100, 0) and (100, 90) halved, (30, 50) and (180, 50) halved, less the corners' mean. + assert_near(pts.get(4).map(|q| q.0), (105.0, 45.0)); + } + + /// Three segments across and two down: each middle point is weighted by its column across and + /// its row down, not the other way around. + #[test] + fn a_top_object_wider_than_it_is_tall_blends_by_column_across_and_row_down() { + let path = outline(&[ + (0.0, 0.0), + (40.0, -6.0), + (80.0, 4.0), + (120.0, 0.0), + (126.0, 40.0), + (120.0, 80.0), + (80.0, 86.0), + (40.0, 84.0), + (0.0, 80.0), + (-4.0, 40.0), + ]); + let Some((rows, cols, pts)) = top_object_grid(&path, Some([0, 3, 5, 8])) else { panic!("the outline is written as a grid") }; + assert_eq!((rows, cols), (2, 3)); + assert_near(pts.get(5).map(|q| q.0), (39.0 + 1.0 / 3.0, 39.0)); + assert_near(pts.get(6).map(|q| q.0), (82.0 + 2.0 / 3.0, 45.0)); + } +} diff --git a/crates/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs index a616d748d1..41f9f0e7e2 100644 --- a/crates/eps/src/ai_editing/writer/symbols.rs +++ b/crates/eps/src/ai_editing/writer/symbols.rs @@ -1,7 +1,7 @@ //! Symbols: their definitions, the symbol list and their instances (see [`crate::ai_editing`] for //! the form). -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::fmt::Write; use vectorcraft_color::Paint; @@ -21,6 +21,11 @@ pub(crate) const DYNAMIC_KEY: &str = "VectorCraftDynamicSymbol"; pub(crate) const OVERRIDES_KEY: &str = "VectorCraftSymbolOverrides"; const MAX_OVERRIDES_BYTES: usize = 1 << 20; +#[cfg(test)] +thread_local! { + pub(in crate::ai_editing) static OVERRIDE_SERIALIZATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + pub(crate) fn hex_decode(s: &str) -> Option> { if !s.len().is_multiple_of(2) || s.len() / 2 > MAX_OVERRIDES_BYTES { return None; @@ -64,10 +69,73 @@ pub(super) fn redrawn(n: &Node) -> bool { } } +/// What leaving out a group's paths and compound paths without anchors ([`Writer::shape`]) does to +/// it in the editing data, worked out once for each group of a symbol's art. +pub(super) struct OmissionFacts { + /// The first omitted child's index. Overrides targeting this child or later children are unsafe. + first: Option, + /// A symbol root group with an omitted child and one kept child is treated as collapsing, + /// regardless of its state. + root_collapses: bool, +} + +impl OmissionFacts { + fn of(n: &Node) -> Self { + fn omitted(c: &Node) -> bool { + match &c.kind { + NodeKind::Path { path, .. } => path.is_empty(), + NodeKind::Compound { .. } => c.children().is_none_or(|k| k.iter().filter_map(|m| m.path_data()).all(|p| p.is_empty())), + _ => false, + } + } + let mut first = None; + let mut kept_count = 0; + for (i, c) in n.children().into_iter().flatten().enumerate() { + if omitted(c) { + first.get_or_insert(i); + } else { + kept_count += 1; + } + } + let root_collapses = first.is_some() && kept_count == 1 && matches!(n.kind, NodeKind::Group { .. }); + Self { first, root_collapses } + } +} + +/// Returns serialized changes within the reader's limit when their targets remain safe after import. +fn changes_kept(art: &Node, overrides: &[vectorcraft_doc::SymbolOverride], omissions: &mut HashMap<*const Node, OmissionFacts>) -> Option> { + fn group_kids(n: &Node) -> Option<&Vec>> { + n.children().filter(|_| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) + } + #[cfg(test)] + OVERRIDE_SERIALIZATIONS.with(|count| count.set(count.get() + 1)); + let json = serde_json::to_vec(overrides).ok()?; + if json.len() > MAX_OVERRIDES_BYTES { + return None; + } + for o in overrides { + if omissions.entry(std::ptr::from_ref(art)).or_insert_with(|| OmissionFacts::of(art)).root_collapses { + return None; + } + let mut n = art; + for &i in o.path.iter().take(vectorcraft_doc::symbol_overrides::MAX_PATH_DEPTH) { + let Some(kids) = group_kids(n) else { break }; + let Some(c) = kids.get(i as usize) else { break }; + let facts = omissions.entry(std::ptr::from_ref(n)).or_insert_with(|| OmissionFacts::of(n)); + if facts.first.is_some_and(|f| f <= i as usize) { + return None; + } + n = c; + } + } + Some(json) +} + impl Writer<'_> { /// Whether instance `n` of symbol `symbol`, placed by `xf`, is written as an instance: not on the /// layers of a large canvas, in a pattern's tile or in art cut to a clipping object, without a - /// fill or appearance changes of its own (which stain or change the art it draws) and without + /// fill or appearance changes of its own (which stain or change the art it draws; a dynamic + /// symbol's instance keeps its changes only when [`changes_kept`] returns their bytes) and without /// isolation, knockout or knockout shape of its own (which an instance's transparency doesn't /// hold), of a symbol without 9-slice guides and without pattern paint in its art (the canvas /// keeps an instance's pattern tiles where the document puts them, and a definition's art moves @@ -75,8 +143,11 @@ impl Writer<'_> { /// that keeps the art's area as it is written and scales it as the definition allows /// ([`Self::keeps_scale`]). pub(super) fn live_instance(&mut self, n: &Node, symbol: &str, xf: Affine) -> bool { - let dynamic = self.symbol_doc.symbols.iter().any(|s| s.name == symbol && s.dynamic); - let own = vectorcraft_brush::stain(n).is_some() || (!dynamic && !n.extras().symbol_overrides.is_empty()); + let doc = self.symbol_doc; + let sym = doc.symbols.iter().find(|s| s.name == symbol); + let dynamic = sym.is_some_and(|s| s.dynamic); + let overrides = &n.extras().symbol_overrides; + let own = vectorcraft_brush::stain(n).is_some() || (!dynamic && !overrides.is_empty()); let group_state = n.isolate || n.knockout != Knockout::Neutral || n.knockout_shape; // The matrix as written (to ten decimals) must still keep the art's area. let m = Affine::new((self.instance_space * xf).as_coeffs().map(|v| (v * 1e10).round() / 1e10)); @@ -91,6 +162,13 @@ impl Writer<'_> { && self.define_symbol(symbol) && !self.symbol_paints_pattern(symbol) && self.keeps_scale(symbol, xf) + && (overrides.is_empty() + || sym.is_some_and(|s| { + let Some(json) = changes_kept(&s.art, overrides, &mut self.symbol_omissions) else { return false }; + let e = format!("%_{} /String ({OVERRIDES_KEY}) ,\n", ps::bytes(hex_encode(&json).as_bytes())); + self.instance_entries = Some((n.id, e)); + true + })) } /// Whether instance matrix `xf` places symbol `symbol`'s definition as the canvas draws the @@ -175,13 +253,7 @@ impl Writer<'_> { /// /RTransformMatrix` (to ten decimals), `;`, then its state block as a group's: `Xy`, `0 0 Xd` /// and `6 () XW` when it has transparency, else `9 () XW`. Its dictionary goes between the two. pub(super) fn symbol_instance(&mut self, n: &Node, symbol: &str, xf: Affine, xy: Xy) { - let o = &n.extras().symbol_overrides; - if !o.is_empty() - && let Ok(json) = serde_json::to_vec(o) - && json.len() <= MAX_OVERRIDES_BYTES - { - let e = format!("%_{} /String ({OVERRIDES_KEY}) ,\n", ps::bytes(hex_encode(&json).as_bytes())); - self.instance_entries = Some((n.id, e)); + if self.instance_entries.as_ref().is_some_and(|(id, _)| *id == n.id) { self.warn(SYMBOL_CHANGES); } let m = self.instance_space * xf; diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 6c85414463..db310e0f01 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -135,6 +135,12 @@ pub struct Imported { pub preview: bool, } +/// `img` as a PNG with fast compression, which keeps opening a file with large images quick. +pub(crate) fn png(img: &craft_image_codecs::Image) -> Option> { + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + craft_image_codecs::encode(img, craft_image_codecs::Format::Png, &opts).ok() +} + /// The DSC comments the reader uses. #[derive(Debug, Default, PartialEq)] struct Dsc { diff --git a/crates/eps/src/import/ai/mesh.rs b/crates/eps/src/import/ai/mesh.rs index 8e2a46c852..1fcdc67266 100644 --- a/crates/eps/src/import/ai/mesh.rs +++ b/crates/eps/src/import/ai/mesh.rs @@ -785,6 +785,17 @@ mod tests { } } + /// A row of patches with as many columns as a mesh keeps is stitched into one mesh; one more + /// column is not. + #[test] + fn a_mesh_with_more_lines_than_are_kept_is_not_stitched() { + for (n, kept) in [(MAX_LINES, true), (MAX_LINES + 1, false)] { + let r = Grid::new(n, 1).read([n as f64, 1.0]); + let at: Vec<(usize, usize)> = (0..n).map(|i| (0, i)).collect(); + assert_eq!(stitch(&r.cells, &at, 1, n).is_some(), kept, "{n} columns"); + } + } + /// A 2 × 2 mesh comes in as one mesh of 9 shared points, each where the patches put it, with /// the colours the separate patches had at every place. #[test] diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 95606c9ebb..e0a46fccb0 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -648,7 +648,7 @@ impl<'a> Reader<'a> { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let Ok(png) = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { + let Some(png) = crate::import::png(&img) else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; @@ -678,7 +678,7 @@ impl<'a> Reader<'a> { } let written = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray) .ok() - .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()); + .and_then(|img| crate::import::png(&img)); let Some(png) = written else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); @@ -778,7 +778,7 @@ impl<'a> Reader<'a> { }; craft_image_codecs::Image::from_raw(ow, oh, layout, craft_image_codecs::SampleType::U8, pixels) .ok() - .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()) + .and_then(|img| crate::import::png(&img)) .map(|png| ImageBlob::new("image/png", png)) }; // One that can't be encoded is left to the page's art, as one past the hard limits. @@ -870,7 +870,7 @@ impl<'a> Reader<'a> { let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); @@ -1224,7 +1224,7 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec, u32, u32)> { } let raw = craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; Some((png, width, height)) } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 9ef4cbc840..57c7e21442 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2799,6 +2799,43 @@ fn ai_variable_library_without_the_layers() { assert_eq!(variables(stream(&square).as_bytes()), read::VariableRead::default()); } +/// A library whose `variableSets` node writes its children and attributes before its name is +/// still found on its own when reading stops before it. +#[test] +fn a_variable_library_named_after_its_children_is_read_when_reading_stops_early() { + use vectorcraft_doc::DataValue; + use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_text}; + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let value = xml_element("Team", &[], &[xml_element("p", &[], &[xml_text(XmlValue::Unicode("Home Team"))])]); + let set = xml_element( + "variableSet", + &[("locked", "none"), ("varSetName", "binding1")], + &[ + xml_element("variables", &[], &[xml_element("variable", &[("trait", "textcontent"), ("varName", "Team")], &[])]), + xml_element( + "v:sampleDataSets", + &[("xmlns", "&ns_custom;"), ("xmlns:v", "&ns_vars;")], + &[xml_element("v:sampleDataSet", &[("dataSetName", "Home")], &[value])], + ), + ], + ); + let named_first = xml_element("variableSets", &[("xmlns", "&ns_vars;")], &[set]); + // Move the name line from the top of the node to just before the line that closes it. + let name = "%_(variableSets) /String (xmlnode-nodename) ,\n"; + let body = named_first.strip_prefix(&format!("%_/XMLNode :\n{name}")).and_then(|b| b.strip_suffix("%_;\n")).unwrap_or_default(); + assert!(!body.is_empty(), "{named_first}"); + let named_last = format!("%_/XMLNode :\n{body}{name}%_;\n"); + let early = stream(&format!("LB\n{}{square}", variable_library_data(&named_last))); + assert!(read(early.as_bytes()).is_err()); + let found = variables(early.as_bytes(), &mut Names::default()); + assert!(found.present); + let names: Vec<&str> = found.variables.variables.iter().map(|v| v.name.as_str()).collect(); + assert_eq!(names, ["Team"]); + assert_eq!(found.variables.datasets.len(), 1); + assert_eq!(found.variables.datasets[0].name, "Home"); + assert_eq!(found.variables.datasets[0].values.get("Team"), Some(&DataValue::Text("Home Team".into()))); +} + #[test] fn a_drawn_look_stands_for_its_object() { // The look (a group, with a part on `%_` lines for newer readers), then the object on `%_` @@ -3154,6 +3191,35 @@ fn a_reduced_separation_image_keeps_its_ink_and_its_alpha_as_a_mask() { assert!(r.doc.images[&im.key].gray_source().is_some_and(|g| !g.alpha), "no alpha in the pixels"); } +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image with an alpha channel, and a Separation image with its opacity +/// mask, at full size and reduced to fit the limits. +#[test] +fn images_and_their_masks_are_stored_with_fast_compression() { + let pngs = |doc: &Document| { + let fast = |n: &Node| { + let NodeKind::Image(im) = &n.kind else { panic!("{:?}", n.kind) }; + let blob = &doc.images[&im.key]; + assert_eq!(blob.mime, "image/png"); + crate::import::tests::fastest_png(&blob.bytes) + }; + let a = art(doc); + let mut out = vec![fast(&a[0])]; + out.extend(a[0].extras().mask.as_ref().map(|m| fast(&m.art))); + out + }; + let rgb = image("[ 10 0 0 10 50 90 ]", (2, 1), ("DeviceRGB", 3, 1), &[255, 0, 0, 0, 255, 0, 255, 128], 10); + assert_eq!(pngs(&read(&rgb).unwrap().doc), [true], "the RGB image"); + let black = "1 [0 0 0 1 /DeviceCMYK (Black Ink) /Separation]"; + let ink = ink_image(black, 8, 1, 2, &[0, 255, 255, 64]); + assert_eq!(pngs(&read(&ink).unwrap().doc), [true, true], "the Separation image and its mask"); + let samples = [255u8; 16].iter().chain([0u8; 16].iter()).copied().collect::>(); + let ink = ink_image(black, 8, 1, 16, &samples); + let r = super::with_image_limits(4, 1 << 31, 512 << 20, || read(&ink).unwrap()); + assert!(r.warnings.iter().any(|w| w.contains("was reduced")), "{:?}", r.warnings); + assert_eq!(pngs(&r.doc), [true, true], "the reduced Separation image and its mask"); +} + #[test] fn images_with_alpha_channels() { // RGB samples, then the alpha channel (not counted in the data's size). diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 3fb4393b19..43cb3b35d2 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -2361,6 +2361,12 @@ mod tests { } let deep = format!("/0 {}", "[".repeat(200)); assert!(read(deep.as_bytes()).is_none()); + // Balanced nesting: 65 levels are read, and a 66th ends the parse. + let nest = |open: &str, close: &str, n: usize| format!("/0 {}1{}", open.repeat(n), close.repeat(n)); + for (open, close) in [("<< /0 ", " >>"), ("[ ", " ]")] { + assert!(read(nest(open, close, MAX_DEPTH + 1).as_bytes()).is_some(), "{open}nested {} levels", MAX_DEPTH + 1); + assert!(read(nest(open, close, MAX_DEPTH + 2).as_bytes()).is_none(), "{open}nested {} levels", MAX_DEPTH + 2); + } } /// A text document's frame on a path of `segments` (each `x0 y0 x1 y1 x2 y2 x3 y3`) with the diff --git a/crates/eps/src/import/data.rs b/crates/eps/src/import/data.rs index 09f7531ff1..26a4dd9522 100644 --- a/crates/eps/src/import/data.rs +++ b/crates/eps/src/import/data.rs @@ -22,4 +22,4 @@ mod pixels; pub(crate) use filters::Stream; #[cfg(test)] -pub(crate) use ops::measured; +pub(crate) use ops::{max_data, measured, with_data_limit}; diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index cada27219a..7f3d37e043 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -1,4 +1,4 @@ -use super::ops::MAX_DATA; +use super::ops::max_data; use super::{DictRef, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, jpeg_components, ps, ps_err}; use craft_stream_codecs::CcittParams; @@ -44,7 +44,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec, usize)> { out.extend(std::iter::repeat_n(b, 257 - usize::from(n))); } } - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } } @@ -54,7 +54,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec, usize)> { /// zlib data inflated, and how many bytes of `raw` it took. fn flate(raw: &[u8]) -> Res<(Vec, usize)> { let mut z = flate2::Decompress::new(true); - let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(MAX_DATA)); + let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(max_data())); loop { let before = (z.total_in(), z.total_out()); if out.capacity() - out.len() < 64 * 1024 { @@ -62,7 +62,7 @@ fn flate(raw: &[u8]) -> Res<(Vec, usize)> { } let input = raw.get(z.total_in() as usize..).unwrap_or_default(); let status = z.decompress_vec(input, &mut out, flate2::FlushDecompress::None).map_err(|_| PsError::Ps("ioerror", "FlateDecode".into()))?; - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } match status { @@ -79,7 +79,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { let mut out = vec![]; let used = lzw_into(raw, &mut |bytes| { out.extend_from_slice(bytes); - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } Ok(()) @@ -238,10 +238,10 @@ fn dct(raw: &[u8]) -> Res<(Vec, usize, u8)> { /// `EndOfBlock` the rows end at the end-of-block code (EOFB, or RTC in Group 3) regardless of /// `Rows`; without it they end after `Rows` rows, or at the end of the data when `Rows` is 0. /// Damaged data ends the rows: those decoded before it are kept, and damage in the first row is an -/// `ioerror`. Rows that would take more than `MAX_DATA` bytes are refused. +/// `ioerror`. Rows that would take more than [`max_data`] bytes are refused. fn fax(raw: &[u8], settings: CcittParams) -> Res<(Vec, usize)> { let row = (settings.columns as usize).div_ceil(8).max(1); - let most = u32::try_from(MAX_DATA / row).unwrap_or(u32::MAX); + let most = u32::try_from(max_data() / row).unwrap_or(u32::MAX); if !settings.end_of_block && settings.rows > i64::from(most) { return Err(PsError::Limit("decoded data is too large")); } diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index e9bf596eb3..8e8036a373 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -6,7 +6,38 @@ use super::{ }; /// Most bytes one filter or image reads. -pub(super) const MAX_DATA: usize = 1 << 28; +const MAX_DATA: usize = 1 << 28; + +#[cfg(test)] +thread_local! { + /// The most bytes one filter or image reads on this thread ([`MAX_DATA`] unless a test lowered it). + static DATA_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_DATA) }; +} + +/// The most bytes one filter or image reads: [`MAX_DATA`]. +#[cfg(not(test))] +pub(super) const fn max_data() -> usize { + MAX_DATA +} + +/// The most bytes one filter or image reads: [`DATA_LIMIT`] of this thread. +#[cfg(test)] +pub(crate) fn max_data() -> usize { + DATA_LIMIT.get() +} + +/// Runs `f` with [`max_data`] set to `limit` on this thread, and restores it afterwards. +#[cfg(test)] +pub(crate) fn with_data_limit(limit: usize, f: impl FnOnce() -> R) -> R { + struct Restore(usize); + impl Drop for Restore { + fn drop(&mut self) { + DATA_LIMIT.set(self.0); + } + } + let _restore = Restore(DATA_LIMIT.replace(limit)); + f() +} /// Decoded bytes the measuring of an image's data left out charges one operation for. A program's /// budget grows by 64 operations for each byte of it, so the data of one image compressed up to @@ -410,7 +441,7 @@ impl Interp<'_> { Stream::Buf { data, pos: 0, rgb } } p @ Obj::Array { .. } => { - let raw = self.gather(&p, MAX_DATA)?; + let raw = self.gather(&p, max_data())?; let (data, _, rgb) = decode(&spec, &raw)?; self.charge_decoded(data.len())?; Stream::Buf { data, pos: 0, rgb } @@ -600,7 +631,7 @@ impl Interp<'_> { if last.predictor.is_some() || !matches!(&*last.name, "FlateDecode" | "LZWDecode") { return Ok(None); } - let Some(kept) = row.checked_mul(oh).filter(|k| *k <= MAX_DATA) else { return Ok(None) }; + let Some(kept) = row.checked_mul(oh).filter(|k| *k <= max_data()) else { return Ok(None) }; self.alloc(kept)?; // The compressed data: what the filters before the last one decode, or the file itself. let compressed = if head.is_empty() { @@ -618,7 +649,7 @@ impl Interp<'_> { }; let (mut rows, mut seen) = (Vec::with_capacity(kept), 0usize); // Past the image's data and as much again the data is not an image's: it stops there. - let most = row.saturating_mul(s.h).saturating_add(MAX_DATA); + let most = row.saturating_mul(s.h).saturating_add(max_data()); let mut sink = |mut chunk: &[u8]| -> Res { while !chunk.is_empty() { let (r, off) = (seen / row.max(1), seen % row.max(1)); @@ -829,7 +860,7 @@ impl Interp<'_> { let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n)); let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h)); // What is read: an image past the pixel cap is reduced from the samples read. - charged = total.min(MAX_DATA); + charged = total.min(max_data()); self.alloc(charged)?; let raw = self.source_bytes(&src, charged)?; by_rows(&raw, (mrow, stencil.h), (drow, image.h)) @@ -838,7 +869,7 @@ impl Interp<'_> { stencil.bpc = image.bpc; (stencil.w, stencil.h) = (image.w, image.h); let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8); - charged = row.saturating_mul(image.h).min(MAX_DATA); + charged = row.saturating_mul(image.h).min(max_data()); self.alloc(charged)?; let raw = self.source_bytes(&src, charged)?; by_samples(&raw, image.w, image.h, n, image.bpc) @@ -1020,7 +1051,7 @@ impl Interp<'_> { // skipped), while one within the pixel cap whose samples are still too much data // (16-bit CMYK, say) stops the read with the limit, as before (#3568: such a plane // is refused). - let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else { + let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= max_data()) else { if step > 1 { return Ok(self.leave_out(&s)); } @@ -1157,7 +1188,7 @@ impl Interp<'_> { else { return Ok(()); }; - let Ok(png) = craft_image_codecs::encode(&rgba, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { + let Some(png) = crate::import::png(&rgba) else { self.out.warn("an image that couldn't be read was left out"); return Ok(()); }; @@ -1184,7 +1215,7 @@ impl Interp<'_> { let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.out.doc.images.entry(key.clone()).or_insert(blob); diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 8d883a0bff..396afc7d69 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -17,6 +17,39 @@ use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err}; /// Most operations one file may run, whatever its length. const MAX_OPS: u64 = 50_000_000; + +#[cfg(test)] +thread_local! { + /// The most operations one file may run on this thread, whatever its length ([`MAX_OPS`] unless + /// a test lowered it). + static OPS_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_OPS) }; +} + +/// The most operations one file may run, whatever its length: [`MAX_OPS`]. +#[cfg(not(test))] +const fn max_ops() -> u64 { + MAX_OPS +} + +/// The most operations one file may run, whatever its length: [`OPS_LIMIT`] of this thread. +#[cfg(test)] +pub(crate) fn max_ops() -> u64 { + OPS_LIMIT.get() +} + +/// Runs `f` with [`max_ops`] set to `limit` on this thread, and restores it afterwards. +#[cfg(test)] +pub(crate) fn with_ops_limit(limit: u64, f: impl FnOnce() -> R) -> R { + struct Restore(u64); + impl Drop for Restore { + fn drop(&mut self) { + OPS_LIMIT.set(self.0); + } + } + let _restore = Restore(OPS_LIMIT.replace(limit)); + f() +} + /// More operations a file may run for each byte of its program: a large file that draws a lot /// runs proportionally more, and stays bounded by its length. const OPS_PER_BYTE: u64 = 64; @@ -228,7 +261,7 @@ impl<'a> Interp<'a> { resources, depth: 0, ops: 0, - max_ops: MAX_OPS.saturating_add((src.len() as u64).saturating_mul(OPS_PER_BYTE)), + max_ops: max_ops().saturating_add((src.len() as u64).saturating_mul(OPS_PER_BYTE)), allocated: 0, seed: 1, saves: vec![], diff --git a/crates/eps/src/import/preview.rs b/crates/eps/src/import/preview.rs index 36c0e5662c..87037fcd1a 100644 --- a/crates/eps/src/import/preview.rs +++ b/crates/eps/src/import/preview.rs @@ -46,7 +46,7 @@ fn image_doc(img: image::RgbaImage, frame: Rect) -> Option { } let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.into_raw()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = super::png(&raw)?; let mut doc = Document::new(frame.width(), frame.height()); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 011cb86ce3..e77aa421c5 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -7,9 +7,9 @@ use vectorcraft_color::{Color, GradientKind, Paint}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, LineCap, LineJoin, Node, NodeKind}; use vectorcraft_geom::{Point, Rect}; -use crate::import::data::measured; +use crate::import::data::{max_data, measured, with_data_limit}; use crate::import::graphics::{GState, Out, tilings_compared}; -use crate::import::interp::Interp; +use crate::import::interp::{Interp, max_ops, with_ops_limit}; use crate::import::obj::Obj; use crate::import::{Dsc, import}; use crate::{EpsOptions, Level, Preview, Raster}; @@ -208,6 +208,19 @@ fn arrays_and_dictionaries_holding_themselves_are_freed() { } } +/// Whether PNG `png` stores its pixels at the fastest level a zlib header names (RFC 1950 §2.2, +/// FLEVEL 0). +pub(super) fn fastest_png(png: &[u8]) -> bool { + let mut at = 8; + while let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) { + if kind == b"IDAT" { + return png.get(at + 9).is_some_and(|flg| flg >> 6 == 0); + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + } + panic!("a PNG with image data: {png:?}"); +} + /// The objects of the document's layer. pub(super) fn objects(d: &Document) -> Vec> { d.layers[0].children().unwrap().clone() @@ -1048,6 +1061,20 @@ fn clipsave_and_cliprestore_bring_the_clip_back() { assert!(matches!(o[0].kind, NodeKind::Path { .. }), "{:?}", o[0].kind); } +/// `clipsave` and `gsave` each keep up to 1,000 saved states. One more is a limit error: the +/// square drawn before it stays, and the one after it is left out. +#[test] +fn clipsave_and_gsave_stop_at_a_thousand_saved_states() { + for (op, why) in [("clipsave", "too many saved clips"), ("gsave", "too many saved graphics states")] { + let r = read(&format!("0 0 10 10 rectfill 1000 {{ {op} }} repeat 20 20 10 10 rectfill")); + assert_eq!(objects(&r.document).len(), 2, "{op}: {:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains(why)), "{op}: {:?}", r.warnings); + let r = read(&format!("0 0 10 10 rectfill 1001 {{ {op} }} repeat 20 20 10 10 rectfill")); + assert_eq!(objects(&r.document).len(), 1, "{op}: {:?}", r.warnings); + assert!(r.warnings.first().is_some_and(|w| w.contains(why)), "{op}: {:?}", r.warnings); + } +} + #[test] fn languagelevel_is_an_integer_and_runs() { // #234. @@ -1086,6 +1113,25 @@ fn intervals_share_their_arrays_and_strings() { ); } +/// `cvs` writes the text of each kind of object (PLRM 3rd ed., `cvs`): a real keeps a decimal +/// point, booleans, names and operators their names, other objects `--nostringval--`. `cvrs` +/// writes a number in a radix from 2 to 36 with uppercase digits, a negative one as its 32-bit +/// two's complement, and refuses any other radix. +#[test] +fn cvs_and_cvrs_write_the_text_of_each_kind() { + check("/s 16 string def 3.0 s cvs (3.0) eq"); + check("/s 16 string def 2.5 s cvs (2.5) eq"); + check("/s 16 string def true s cvs (true) eq"); + check("/s 16 string def /abc s cvs (abc) eq"); + check("/s 16 string def /add load s cvs (add) eq"); + check("/s 16 string def [1] s cvs (--nostringval--) eq"); + check("/s 16 string def 255 16 s cvrs (FF) eq"); + check("/s 16 string def 10 2 s cvrs (1010) eq"); + check("/s 16 string def 0 2 s cvrs (0) eq"); + check("/s 16 string def -1 16 s cvrs (FFFFFFFF) eq"); + check("/s 16 string def { 10 1 s cvrs } stopped { 10 37 s cvrs } stopped and"); +} + #[test] fn resourceforall_enumerates_matching_names() { // #234. @@ -1236,11 +1282,16 @@ fn read_counting_tilings(body: &str) -> (crate::Imported, u64) { } /// [`read_within`], with how many patterns the tiling pattern lookups compared while reading, and -/// how many decoded bytes the measuring of images' data left out decoded. +/// how many decoded bytes the measuring of images' data left out decoded. The reading thread +/// reads with this thread's data and operation limits ([`with_data_limit`], [`with_ops_limit`]). fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64, u64) { let (tx, rx) = std::sync::mpsc::channel(); let ps = eps(body); - std::thread::spawn(move || tx.send((import(&ps), tilings_compared(), measured())).ok()); + let (data, ops) = (max_data(), max_ops()); + std::thread::spawn(move || { + let read = with_ops_limit(ops, || with_data_limit(data, || import(&ps))); + tx.send((read, tilings_compared(), measured())).ok() + }); let (read, compared, measured) = rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish")); (read.unwrap(), compared, measured) diff --git a/crates/eps/src/import/tests_cid.rs b/crates/eps/src/import/tests_cid.rs index b44a5410ee..e79dc37dd2 100644 --- a/crates/eps/src/import/tests_cid.rs +++ b/crates/eps/src/import/tests_cid.rs @@ -50,10 +50,7 @@ fn hex(b: &[u8]) -> String { /// triangle (500 across, 400 high) 500 wide drawn by a subroutine, encrypted (dictionary 1, /// `lenIV` 4). The binary data section, written in hexadecimal when `hex_data`. fn cid_font(hex_data: bool) -> Vec { - let empty = cs(&[(&[0, 500], 13), (&[], 14)]); - let square = cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)]); - let triangle = encrypt(&cs(&[(&[0, 500], 13), (&[0], 10), (&[], 14)])); - let subr = encrypt(&cs(&[(&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 11)])); + let [empty, square, triangle] = cid_glyphs(); // The offset table: FDArray index (1 byte) and offset (2 bytes) of CIDs 0 to 2 and the end. let table = 4 * 3; let offsets = [table, table + empty.len(), table + empty.len() + square.len(), table + empty.len() + square.len() + triangle.len()]; @@ -65,16 +62,7 @@ fn cid_font(hex_data: bool) -> Vec { data.extend(empty); data.extend(square); data.extend(triangle); - let mut out = format!( - "/CIDInit /ProcSet findresource begin\n20 dict begin\n/CIDFontName /TestCID def /CIDFontType 0 def\n\ - /CIDSystemInfo 3 dict dup begin /Registry (Test) def /Ordering (Shapes) def /Supplement 0 def end def\n\ - /FontBBox [0 0 1000 1000] def\n/FDArray [\n\ - 4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV -1 def end def currentdict end\n\ - 4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV 4 def /Subrs [<{}>] def end def currentdict end\n\ - ] def\n/CIDMapOffset 0 def /FDBytes 1 def /GDBytes 2 def /CIDCount 3 def\n", - hex(&subr) - ) - .into_bytes(); + let mut out = cid_font_head().into_bytes(); if hex_data { out.extend(format!("(Hex) {} StartData\n{}>\n", data.len(), hex(&data)).into_bytes()); } else { @@ -85,6 +73,46 @@ fn cid_font(hex_data: bool) -> Vec { out } +/// The charstrings of [`cid_font`]'s CIDs 0 to 2, as its data holds them. +fn cid_glyphs() -> [Vec; 3] { + let empty = cs(&[(&[0, 500], 13), (&[], 14)]); + let square = cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)]); + let triangle = encrypt(&cs(&[(&[0, 500], 13), (&[0], 10), (&[], 14)])); + [empty, square, triangle] +} + +/// [`cid_font`] up to its glyph data: the CIDFont dictionary, its FDArray and its offset table's +/// layout. +fn cid_font_head() -> String { + let subr = encrypt(&cs(&[(&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 11)])); + format!( + "/CIDInit /ProcSet findresource begin\n20 dict begin\n/CIDFontName /TestCID def /CIDFontType 0 def\n\ + /CIDSystemInfo 3 dict dup begin /Registry (Test) def /Ordering (Shapes) def /Supplement 0 def end def\n\ + /FontBBox [0 0 1000 1000] def\n/FDArray [\n\ + 4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV -1 def end def currentdict end\n\ + 4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV 4 def /Subrs [<{}>] def end def currentdict end\n\ + ] def\n/CIDMapOffset 0 def /FDBytes 1 def /GDBytes 2 def /CIDCount 3 def\n", + hex(&subr) + ) +} + +/// [`cid_font`] with its glyphs in a `GlyphDirectory` (each entry the FDArray index byte and the +/// charstring: PLRM 3rd ed., §5.11.3) instead of a binary data section, as an array +/// indexed by CID or as a dictionary keyed by CID, defined with `defineresource`. Its own matrix +/// is the identity, as its FDArray matrices give glyph space. +fn cid_font_in_a_directory(dict: bool) -> String { + let entries: Vec = cid_glyphs().iter().zip([0u8, 0, 1]).map(|(g, fd)| format!("<{:02x}{}>", fd, hex(g))).collect(); + let directory = if dict { + format!("<< {} >>", entries.iter().enumerate().map(|(cid, e)| format!("{cid} {e}")).collect::>().join(" ")) + } else { + format!("[ {} ]", entries.join(" ")) + }; + format!( + "{}/FontMatrix [1 0 0 1 0 0] def /GlyphDirectory {directory} def\nCIDFontName currentdict end /CIDFont defineresource pop end\n", + cid_font_head() + ) +} + /// CMap `/Test-H`: one-byte codes 00–7F and two-byte codes 8000–FFFF; A and B are CIDs 1 and 2, /// <8001> CID 2, and codes 00–1F without a character take CID 1 as their notdef. const CMAP: &str = "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n\ @@ -121,6 +149,63 @@ fn type0_cidfonts_draw_their_charstrings_through_the_cmap() { } } +/// `font` and the CMap, then `body`, as an EPS file. +fn program_with(font: &str, body: &str) -> Vec { + format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n{font}{CMAP}{body}\nshowpage\n%%EOF\n").into_bytes() +} + +/// Widths in a CIDFont's `Metrics` dictionary replace its glyphs' own (PLRM 3rd ed., §5.9.2): a +/// number is the width, a 2-element entry `[sbx wx]` gives its second element and a 4-element +/// entry `[sbx sby wx wy]` its third. An entry of another length keeps the glyph's width. +#[test] +fn cidfont_metrics_replace_the_glyph_widths() { + let with = |metrics: &str| { + String::from_utf8(cid_font(true)).unwrap().replace("/CIDCount 3 def", &format!("/CIDCount 3 def /Metrics << {metrics} >> def")) + }; + let width = |font: &str, s: &str, w: f64| check(&format!("{font}{CMAP} /TestFont 50 selectfont {s} stringwidth pop {w} sub abs 0.01 lt")); + let font = with("0 250 1 [0 700] 2 [0 0 800 0]"); + // At 50 points an em: 700 units for A (CID 1), 800 for B (CID 2), 250 for CID 0. + width(&font, "(A)", 35.0); + width(&font, "(B)", 40.0); + width(&font, "<9041>", 12.5); + // A 3-element entry keeps the square's 600 units. + width(&with("1 [0 700 0]"), "(A)", 30.0); + // The triangle is drawn where the square's new width ends, 700 units on, not 600. + let r = import(&program_with(&font, "/TestFont 50 selectfont 10 20 moveto (AB) show")).unwrap(); + let p = paths(&r); + assert_eq!(p.len(), 2, "{p:?} {:?}", r.warnings); + assert!((p[1].x0 - 45.0).abs() < 0.01 && (p[1].width() - 25.0).abs() < 0.01, "{p:?}"); +} + +/// A Type 0 CIDFont whose glyphs are in a `GlyphDirectory`, an array or a dictionary, draws the +/// same glyphs as the same font with its glyphs in a binary data section. +#[test] +fn glyph_directories_draw_the_glyphs_a_data_section_does() { + let show = "/TestFont 50 selectfont 10 20 moveto (AB) show"; + let want = paths(&import(&program(false, show)).unwrap()); + assert_eq!(want.len(), 2, "{want:?}"); + for dict in [false, true] { + let r = import(&program_with(&cid_font_in_a_directory(dict), show)).unwrap(); + assert!(r.warnings.is_empty(), "{dict}: {:?}", r.warnings); + let p = paths(&r); + assert_eq!(p.len(), 2, "{dict}: {p:?}"); + assert!(p.iter().zip(&want).all(|(a, b)| super::tests::near(*a, *b)), "{dict}: {p:?} {want:?}"); + } +} + +/// A binary data section longer than a font's data may be (64 MiB) is refused before it is read. +#[test] +fn start_data_over_the_glyph_data_limit_is_refused() { + let font = String::from_utf8(cid_font(true)).unwrap(); + let font = format!("{}(Binary) 70000000 StartData abc\n", &font[..font.find("(Hex)").unwrap()]); + let r = import(&program_with(&font, "/TestFont 50 selectfont 10 20 moveto (AB) show")); + let said = match &r { + Ok(r) => r.warnings.join("\n"), + Err(e) => e.clone(), + }; + assert!(said.contains("a font's data is too large"), "{said}"); +} + /// Codes take as many bytes as their codespace range says; codes without a character take their /// notdef mapping's CID, else CID 0 (PLRM 3rd ed., §5.11.5). #[test] diff --git a/crates/eps/src/import/tests_generators.rs b/crates/eps/src/import/tests_generators.rs index 63859b3e52..260a6c0fe6 100644 --- a/crates/eps/src/import/tests_generators.rs +++ b/crates/eps/src/import/tests_generators.rs @@ -861,6 +861,11 @@ fn probing_operators_answer() { "/n 0 def 0 0 moveto 10 0 lineto { pop pop /n n 1 add def } { pop pop /n n 2 add def } { 6 { pop } repeat } {} pathforall n 3 eq", ); super::tests::check("1 0 0 setrgbcolor currenthsbcolor 1 eq exch 1 eq and exch 0 eq and"); + // Green largest: hue (2 + (b - r) / d) / 6 = 5/12; blue largest: (4 + (r - g) / d) / 6 = 9/12; + // each with saturation 0.8 and brightness 1. Gray has no hue and no saturation. + super::tests::check("0.2 1 0.6 setrgbcolor currenthsbcolor 1 eq exch 0.8 sub abs 1e-6 lt and exch 12 mul 5 sub abs 1e-5 lt and"); + super::tests::check("0.6 0.2 1 setrgbcolor currenthsbcolor 1 eq exch 0.8 sub abs 1e-6 lt and exch 12 mul 9 sub abs 1e-5 lt and"); + super::tests::check("0.5 setgray currenthsbcolor 0.5 sub abs 1e-6 lt exch 0 eq and exch 0 eq and"); super::tests::check("currentcacheparams counttomark 2 eq exch pop exch pop exch pop"); super::tests::check("cachestatus 7 { pop } repeat true"); super::tests::check("currentcolorrendering /ColorRenderingType known"); @@ -997,6 +1002,17 @@ fn hostile_patterns_glyphs_and_shadings_end() { /Function << /FunctionType 0 /Domain [0 1] /Range [0 1] /Size [99999999] /BitsPerSample 8 /DataSource () >> >> shfill", ); assert!(r.warnings[0].contains("rangecheck in `shfill`: a sampled function"), "{:?}", r.warnings); + // A sampled function of two inputs may hold 2^24 samples (4096 × 4096), and no more. + let sized = |size: &str| { + read(&format!( + "0 0 1 1 rectfill << /ShadingType 1 /ColorSpace /DeviceGray \ + /Function << /FunctionType 0 /Domain [0 1 0 1] /Range [0 1] /Size [{size}] /BitsPerSample 8 /DataSource () >> >> shfill" + )) + }; + let r = sized("4096 4096"); + assert!(!r.warnings.iter().any(|w| w.contains("error")), "{:?}", r.warnings); + let r = sized("4096 4097"); + assert!(r.warnings[0].contains("limitcheck in `shfill`: Size"), "{:?}", r.warnings); // Procedures nesting through operators that run them end at the nesting limit. for body in ["/f { { f } exec } def f", "/f { true { f } if } def f", "/f { 1 { f } repeat } def f", "/f { { f } stopped } def f"] { assert!(import(&super::tests::eps(body)).is_err(), "{body}"); diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index e7fd734240..897c126302 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -14,7 +14,7 @@ use vectorcraft_doc::cmyk::Inks; use vectorcraft_doc::{ImageBlob, Node, NodeKind}; use super::import; -use super::tests::{all, eps, read}; +use super::tests::{all, eps, fastest_png, read}; use super::tests_generators::pixel; /// Each pixel of the first image, row by row. @@ -148,6 +148,35 @@ fn filters_read_the_file_they_were_made_over() { ); } +/// LZW data (`LZWDecode`, `EarlyChange` 1, PDF 32000 §7.4.4.2) decodes: the specification's +/// example, whose third code is the entry that code adds; data long enough that the table grows +/// past 511, 1023 and 2047 entries (9-, 10-, 11- and 12-bit codes) and is cleared and grown again; +/// and a code past the end of the table is an `ioerror`, the art after it left out. +#[test] +fn lzw_data_decodes_at_every_code_width() { + super::tests::check("<800B6050220C0C8501> /LZWDecode filter 20 string readstring pop (-----A---B) eq"); + let mut x = 0x2545_F491_u32; + let data: Vec = (0..12_000) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + (x >> 24) as u8 + }) + .collect(); + let lzw = craft_stream_codecs::lzw::encode(&data, true); + super::tests::check(&format!( + "/f <{}> /LZWDecode filter def f {} string readstring exch <{}> eq and f read {{ pop false }} {{ true }} ifelse and", + hex(&lzw), + data.len(), + hex(&data) + )); + // A clear-table code, then code 300 while the table ends at 257. + let r = read("0 0 10 10 rectfill <804B00> /LZWDecode filter 4 string readstring 20 20 10 10 rectfill"); + assert_eq!(super::tests::objects(&r.document).len(), 1, "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("ioerror") && w.contains("LZWDecode")), "{:?}", r.warnings); +} + /// CMYK samples keep their ink amounts in a CMYK TIFF: in the operand and dictionary forms, from /// hex and binary data, from one source or one a component, at 4, 8 and 16 bits, read through /// the Decode array. Gray and RGB images stay PNGs. @@ -223,6 +252,24 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() { assert!(first_image(&r).extras().mask.is_none()); } +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image, and the opacity mask of a masked CMYK image. +#[test] +fn images_and_their_masks_are_stored_with_fast_compression() { + let r = read("30 20 scale 3 2 8 [3 0 0 -2 0 2] <00ff00405060> <0000ff708090> true 3 colorimage"); + let b = blob(&r, &first_image(&r)); + assert_eq!(b.mime, "image/png"); + assert!(fastest_png(&b.bytes), "the RGB image"); + let r = read( + "/DeviceCMYK setcolorspace 30 20 scale << /ImageType 4 /Width 2 /Height 1 /BitsPerComponent 8 /Decode [0 1 0 1 0 1 0 1] \ + /ImageMatrix [2 0 0 -1 0 1] /DataSource <0a141e28 00667f08> /MaskColor [10 20 30 40] >> image", + ); + let n = first_image(&r); + let mask = blob(&r, &n.extras().mask.as_ref().expect("an opacity mask").art); + assert_eq!(mask.mime, "image/png"); + assert!(fastest_png(&mask.bytes), "the opacity mask"); +} + /// A CMYK JPEG gives its samples as stored, for the Decode array to read: Adobe's inverted /// samples with `[1 0 1 0 1 0 1 0]`, the ink amounts themselves with `[0 1 0 1 0 1 0 1]`. #[test] @@ -638,29 +685,55 @@ fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() { /// An image too large to read even at a lower resolution (its samples are more data than the /// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure /// is called until the data ends; when its first filter decompresses to more than the reader -/// holds (and can't be read a row at a time), the compressed data is measured without keeping it. +/// holds (and can't be read a row at a time), the compressed data (Flate, LZW or run-length) is +/// measured without keeping it. The reader holds 1 MiB here, and each filter's data decompresses +/// to 2 MiB: Flate and LZW data is measured in full (run-length data is measured by its run +/// lengths, without decoding it). #[test] fn the_data_of_an_image_too_large_to_hold_is_skipped() { + const LIMIT: usize = 1 << 20; + const DECODED: usize = 2 * LIMIT; let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; - let zeros = crate::ps::deflate(&vec![0u8; 300 << 20]); + let zeros = crate::ps::deflate(&vec![0u8; DECODED]); // Predicted rows aren't decoded a row at a time: such an image is left out. let mut flate = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); flate.extend(&zeros); flate.extend(format!("\n{after}").as_bytes()); - for program in [ - format!( - "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ - 10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}" - ) - .into_bytes(), - flate, + // The same through LZW, which counts the codes up to its end-of-data code. + let mut lzw = + b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /LZWDecode filter false 3 colorimage\n".to_vec(); + lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; DECODED], true)); + lzw.extend(format!("\n{after}").as_bytes()); + // Run-length data isn't decoded a row at a time either: a literal run of three bytes, runs of + // 128 bytes, and the end-of-data byte (128) after which the art follows. The literal ends in + // 200 and every run repeats 200, so a count that lands on a wrong byte reads each 200 as a + // run's length and stays off by one. + let mut run_length = b"10000 10000 8 [1 0 0 1 0 0] currentfile /RunLengthDecode filter false 3 colorimage\n".to_vec(); + run_length.extend([2, 200, 200, 200]); + run_length.extend([129u8, 200].repeat(DECODED / 128)); + run_length.push(128); + run_length.extend(format!("\n{after}").as_bytes()); + for (program, measured) in [ + ( + format!( + "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ + 10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}" + ) + .into_bytes(), + 0, + ), + (flate, DECODED as u64), + (lzw, DECODED as u64), + (run_length, 0), ] { let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned(); let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); file.extend(&program); file.extend(b"\nshowpage\n%%EOF\n"); - let r = import(&file).unwrap(); + let before = crate::import::data::measured(); + let r = crate::import::data::with_data_limit(LIMIT, || import(&file)).unwrap(); + assert_eq!(crate::import::data::measured() - before, measured, "{text}"); assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{text}: {:?}", r.warnings); let o = super::tests::objects(&r.document); assert_eq!(o.len(), 1, "{text}: {:?}", r.warnings); @@ -669,18 +742,24 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { } /// Measuring the data of an image too large to hold decompresses it, and that is charged to the -/// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed -/// zeros is left out and measured again each time a loop runs the stream from its start, runs out -/// of the budget after it measured the data in full more than once and at most five times. +/// operation budget: a program kept in a reusable stream, whose image over compressed zeros is +/// left out and measured again each time a loop runs the stream from its start, runs out of the +/// budget after it measured the data in full more than once and at most five times. The reader +/// holds 1 MiB here, the zeros decompress to 4 MiB, and the budget a file has whatever its length +/// pays for measuring them twice. #[test] fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() { + const LIMIT: usize = 1 << 20; + const DECODED: usize = 4 * LIMIT; let mut program = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); - program.extend(crate::ps::deflate(&vec![0u8; 300 << 20])); + program.extend(crate::ps::deflate(&vec![0u8; DECODED])); let hex: String = program.iter().map(|b| format!("{b:02x}")).collect(); - let measured = - super::tests::runs_out_of_budget_measuring(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop")); - assert!(((300 << 20) + 1..=5 * (300 << 20)).contains(&measured), "{measured} bytes measured"); + let body = format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop"); + let measured = super::interp::with_ops_limit(DECODED as u64 / 8, || { + crate::import::data::with_data_limit(LIMIT, || super::tests::runs_out_of_budget_measuring(&body)) + }); + assert!((DECODED as u64 + 1..=5 * DECODED as u64).contains(&measured), "{measured} bytes measured"); } /// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is diff --git a/crates/eps/src/import/tests_type1.rs b/crates/eps/src/import/tests_type1.rs index 21ff20abec..6221da60f3 100644 --- a/crates/eps/src/import/tests_type1.rs +++ b/crates/eps/src/import/tests_type1.rs @@ -47,6 +47,11 @@ fn font(encoding: &str, hex: bool) -> Vec { /// [`font`] with subroutines `subrs` and, when given, charstring `a` for A. fn font_with(encoding: &str, hex: bool, subrs: &[Vec], a: Option>) -> Vec { + font_private(encoding, hex, subrs, a, b"") +} + +/// [`font_with`] with `extra` in the encrypted part, after `Subrs` and before `CharStrings`. +fn font_private(encoding: &str, hex: bool, subrs: &[Vec], a: Option>, extra: &[u8]) -> Vec { let square = a.unwrap_or_else(|| cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)])); let triangle = cs(&[(&[0, 500], 13), (&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 14)]); let notdef = cs(&[(&[0, 250], 13), (&[], 14)]); @@ -61,7 +66,9 @@ fn font_with(encoding: &str, hex: bool, subrs: &[Vec], a: Option>) - private.extend(e); private.extend(b" NP\n"); } - private.extend(b"readonly def\n2 index /CharStrings 4 dict dup begin\n"); + private.extend(b"readonly def\n"); + private.extend(extra); + private.extend(b"2 index /CharStrings 4 dict dup begin\n"); for (name, glyph) in [(".notdef", ¬def), ("A", &square), ("B", &triangle), ("g1", &triangle)] { let e = encrypt(glyph, 4330); private.extend(format!("/{name} {} RD ", e.len()).into_bytes()); @@ -163,8 +170,13 @@ fn laid_out(t: &TextObject) -> Vec<(vectorcraft_geom::Rect, f64, bool)> { /// font's own advances (no tracking makes up for a stand-in's), not in the fallback font. #[test] fn embedded_type1_type_draws_with_the_files_glyphs() { - let r = program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show"); - let t = &texts(&r)[0]; + draws_the_files_glyphs(&program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show")); +} + +/// "AB" in `/TestOne` drawn with the file's glyphs: the square and the triangle, B starting where +/// A's 600 units end. +fn draws_the_files_glyphs(r: &crate::Imported) { + let t = &texts(r)[0]; assert!(t.file_fonts.is_some(), "{:?}", r.warnings); let glyphs = laid_out(t); assert_eq!(glyphs.len(), 2); @@ -178,6 +190,24 @@ fn embedded_type1_type_draws_with_the_files_glyphs() { assert!(t.runs.iter().all(|r| r.style.tracking == 0.0), "{:?}", t.runs); } +/// The encrypted part's other definitions are stepped over whole when looking for its +/// `CharStrings`: strings with escaped and nested parentheses, nested procedures holding comments +/// and strings, comments, hexadecimal strings and dictionaries. `CharStrings` written inside a +/// string or a comment, with a charstring of its own, isn't taken for the font's. +#[test] +fn the_encrypted_parts_other_definitions_are_stepped_over() { + let extra: &[u8] = b"/OtherSubrs [ { (a\\) } (b) {c) { % } ( {\n} } ] ND\n\ + /p { {} (}) /CharStrings 2 dict dup begin /A 1 RD x ND end } def\n\ + /x <0A 0b\n 1F> def\n\ + /d << /k (() /CharStrings 2 dict) /m << >> >> def\n\ + % /CharStrings 2 dict dup begin /A 1 RD x ND end\n\ + (/CharStrings 2 \\( dict dup begin /A 1 RD x ND end) pop\n"; + let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + let body = b"/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show\nshowpage\n%%EOF\n".to_vec(); + let r = import(&[head, font_private(OWN, false, &[], None, extra), body].concat()).unwrap(); + draws_the_files_glyphs(&r); +} + /// A family whose regular style the file carries but whose bold it only names: the regular is /// drawn in the kept font and the bold in the fallback font, and the warning says both. #[test] diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index e43f2a1227..7a0685d80a 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -722,6 +722,21 @@ fn a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_place assert_eq!(text.lines().filter(|l| l.ends_with(" XI")).count(), 1, "the one image"); } +/// A distorted image on a layer, which the format has no form for, is written as the pieces it is +/// drawn as, with a warning. +#[test] +fn a_distorted_image_on_a_layer_is_written_as_its_pieces() { + let mut doc = Document::new(200.0, 100.0); + let mut art = picture(&mut doc, Rect::new(10.0, 10.0, 90.0, 90.0)); + art.set_image_corners([(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y))).unwrap(); + doc.insert(doc.default_layer(), usize::MAX, art).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == LIVE), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == DEEP_DISTORTED), "{:?}", out.warnings); + let text = String::from_utf8(out.bytes).unwrap(); + assert!(text.lines().filter(|l| l.ends_with(" XI")).count() > 1, "the pieces, not one image"); +} + /// A layer `Below` holding a clipping group (a circle clipping an image, as in #2692), a group /// holding an image and an image; a layer `Above` holding an orange square. Without `images`, /// `Below` is empty. diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index d8b9a96295..6813b300aa 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -34,6 +34,7 @@ //! - `ai_graph`: the records of a live graph those two write around its group. //! - `gradient_key`: the key those two find gradient definitions by. //! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing. +#![doc(test(attr(deny(unsafe_code))))] mod ai_editing; mod ai_graph; diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index dc40025954..aa14fcde37 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -426,6 +426,61 @@ fn strokes_keep_their_caps_joins_and_dashes() { assert!(page.contains("0 0 0 rg\n20 20 m\n80 20 l\n80 80 l\n20 80 l\n20 20 l\nh\nS\n"), "{page}"); } +/// The page for a square stroked 4 pt with `paint`, aligned `align`. +fn aligned_stroke_page(align: vectorcraft_doc::StrokeAlign, paint: impl FnOnce(&mut Document) -> Paint) -> String { + let d = doc_with(|d| { + let paint = paint(d); + let mut n = path(d, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)), Paint::None, paint, 4.0); + for i in &mut n.appearance.items { + if let AppearanceItem::Stroke(s) = i { + s.align = align; + } + } + vec![n] + }); + page_of(&d, &opts(&d)) +} + +/// Where the first line of `page` that `matches` is. +fn line_at(page: &str, matches: impl Fn(&str) -> bool) -> Option { + page.lines().position(matches) +} + +/// A stroke inside or outside a closed path is drawn at twice its width, clipped first: inside to +/// the path, outside to everything but the path (even-odd), so only its own half shows. +#[test] +fn inside_and_outside_strokes_are_clipped_to_their_side_and_drawn_twice_as_wide() { + use vectorcraft_doc::StrokeAlign; + let black = |_: &mut Document| Paint::solid(Color::BLACK); + for (align, clip) in [(StrokeAlign::Inside, "W"), (StrokeAlign::Outside, "W*")] { + let page = aligned_stroke_page(align, black); + let clip_at = line_at(&page, |l| l == clip); + let width_at = line_at(&page, |l| l.starts_with("8 w ")); + let stroke_at = line_at(&page, |l| l == "S"); + assert!(clip_at.is_some() && clip_at < width_at && width_at < stroke_at, "{align:?}: {page}"); + let other = if clip == "W" { "W*" } else { "W" }; + assert_eq!(line_at(&page, |l| l == other), None, "{align:?}: {page}"); + } + // Centered: the width as set, with no clip. + let page = aligned_stroke_page(StrokeAlign::Center, black); + assert!(line_at(&page, |l| l.starts_with("4 w ")).is_some(), "{page}"); + assert_eq!(line_at(&page, |l| l == "W" || l == "W*"), None, "{page}"); +} + +/// A stroke painted with a pattern is written as the area it covers, filled with the pattern's +/// tiles, not as a stroke. +#[test] +fn a_pattern_stroke_is_written_as_its_filled_outline() { + let pattern = |d: &mut Document| { + let square = path(d, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + d.patterns.push(vectorcraft_doc::PatternDef::new("tile", vec![Arc::new(square)])); + Paint::Pattern { pattern: "tile".into(), xf: Affine::IDENTITY } + }; + let page = aligned_stroke_page(vectorcraft_doc::StrokeAlign::Center, pattern); + assert!(page.contains("0 0 1 rg"), "the tile is painted: {page}"); + assert_eq!(line_at(&page, |l| l == "S" || l.contains("strokepath") || l.contains(" w ")), None, "{page}"); +} + #[test] fn transparency_is_written_opaque_with_a_warning() { let d = doc_with(|d| { diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index d759ff6d9f..1e353f309f 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -89,13 +89,15 @@ fn create_new(path: &Path) -> io::Result { /// and none of them looks its path up again. A folder replaced (or swapped for a link) before it is /// opened fails `allowed`. A folder replaced after it is opened does not receive the file. A link at /// the final name is followed once before the folder is opened, as [`write_atomic_with`] follows it; -/// a link put there later is replaced, never followed. Elsewhere this is `allowed(path)` followed by +/// a link put there later is replaced, never followed. A folder that moved after it was opened is +/// checked with `allowed` again at its new path right before the file is put in place, and a folder +/// whose new path the system does not report fails. Elsewhere this is `allowed(path)` followed by /// [`write_atomic_with`]. #[cfg(unix)] pub fn write_atomic_checked( path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>, - allowed: impl FnOnce(&Path) -> io::Result<()>, + allowed: impl Fn(&Path) -> io::Result<()>, ) -> io::Result<()> { use rustix::fs::{AtFlags, Mode, OFlags}; // A path written as a folder (`draft.svg/`, `draft.svg/.`) is not a file path: `file_name` @@ -126,6 +128,24 @@ pub fn write_atomic_checked( }; // The folder may have moved since it was opened: messages name it where it is now. let now = |file: &std::ffi::OsStr| folder_now(&dir, &real).join(file); + // Right before the file is put in place: a folder that moved since it was opened is checked + // again where it is now, so a move out of the allowed folders does not receive the file. + let still_allowed = || -> io::Result<()> { + let here = folder_now(&dir, &real); + let open = rustix::fs::fstat(&dir)?; + // The path itself, not a link that leads to the folder from elsewhere. + let same = |p: &Path| { + std::fs::canonicalize(p).is_ok_and(|c| c == p) && rustix::fs::stat(p).is_ok_and(|s| (s.st_dev, s.st_ino) == (open.st_dev, open.st_ino)) + }; + if here == real && same(&real) { + return Ok(()); + } + if here == real || !same(&here) { + return Err(io::Error::other(format!("{}: the folder moved while the file was written", target.display()))); + } + allowed(&here.join(stored_name(&dir, &here, &name))) + .map_err(|_| io::Error::other(format!("{}: the folder moved while the file was written", target.display()))) + }; let synced = || { // Opened for reading here: the folder handle above may allow name lookups only. let flushed = @@ -133,13 +153,21 @@ pub fn write_atomic_checked( flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() })) }; let open_target = |write: bool| -> io::Result { + // A missing target is created by `create_target`, after the last check. An existing one is + // opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it. + if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) { + return Err(io::ErrorKind::NotFound.into()); + } let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY }; Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?)) }; + let create_target = || -> io::Result { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, mode)?)) }; match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) { Ok(mut f) => { let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); - if let Err(e) = filled { + // Checked before the temporary file takes the old file's wider permissions, and again + // right before the rename. + if let Err(e) = filled.and_then(|()| still_allowed()) { drop(f); remove_tmp(); return Err(e); @@ -151,6 +179,10 @@ pub fn write_atomic_checked( let _ = keep_permissions_at(&dir, &name, &old, &f); } drop(f); + if let Err(e) = still_allowed() { + remove_tmp(); + return Err(e); + } #[cfg(test)] let refuse = RENAME_REFUSED.with(std::cell::Cell::get); #[cfg(not(test))] @@ -189,7 +221,9 @@ pub fn write_atomic_checked( }, remove_tmp: &remove_tmp, open_target: &open_target, + create_target: &create_target, synced: &synced, + still_allowed: &still_allowed, }; write_over_in(&over, refused.into()) } @@ -207,7 +241,7 @@ pub fn write_atomic_checked( // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&elsewhere); }; - if let Err(e) = filled { + if let Err(e) = filled.and_then(|()| still_allowed()) { remove(); return Err(e); } @@ -222,22 +256,28 @@ pub fn write_atomic_checked( open_tmp: &|| File::open(&elsewhere), remove_tmp: &remove, open_target: &open_target, + create_target: &create_target, synced: &synced, + still_allowed: &still_allowed, }; write_over_in(&over, refused.into()) } } } -/// See the Unix version. +/// See the Unix version. Here `allowed(path)` runs before the file is written and again after it is +/// filled, right before it is put in place; a refusal then removes the temporary file and leaves +/// `path` unchanged. #[cfg(not(unix))] pub fn write_atomic_checked( path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>, - allowed: impl FnOnce(&Path) -> io::Result<()>, + allowed: impl Fn(&Path) -> io::Result<()>, ) -> io::Result<()> { allowed(path)?; - write_atomic_with(path, fill) + let replacing = path.exists(); + let create = |tmp: &Path| if replacing { create_private(tmp) } else { create_new(tmp) }; + write_atomic_staged(path, fill, create, || allowed(path), |tmp, target| std::fs::rename(tmp, target)) } /// The path folder `dir` has now, which `parent` named when it was opened: `parent` with its links @@ -368,6 +408,18 @@ fn write_atomic_stepping( fill: impl FnOnce(&mut File) -> io::Result<()>, create: impl FnOnce(&Path) -> io::Result, rename: impl FnOnce(&Path, &Path) -> io::Result<()>, +) -> io::Result<()> { + write_atomic_staged(path, fill, create, || Ok(()), rename) +} + +/// [`write_atomic_stepping`], with `check` run after the temporary file is filled and right before +/// it is put in place. An error from `check` removes the temporary file and leaves `path` unchanged. +fn write_atomic_staged( + path: &Path, + fill: impl FnOnce(&mut File) -> io::Result<()>, + create: impl FnOnce(&Path) -> io::Result, + check: impl Fn() -> io::Result<()>, + rename: impl FnOnce(&Path, &Path) -> io::Result<()>, ) -> io::Result<()> { let target = resolve_link(path)?; let beside = temp_path(&target)?; @@ -384,7 +436,7 @@ fn write_atomic_stepping( }; let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); drop(f); - if let Err(e) = filled { + if let Err(e) = filled.and_then(|()| check()) { // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&tmp); return Err(e); @@ -399,7 +451,7 @@ fn write_atomic_stepping( e } }; - write_over(&tmp, &target, refused) + write_over(&tmp, &target, refused, &check) } /// The content of `tmp`, which is whole and flushed, copied into `target` itself, and `tmp` @@ -407,8 +459,8 @@ fn write_atomic_stepping( /// writing it is untouched: `tmp` is removed and `refused` returned. When what it holds can't be /// copied aside first ([`keep_old`]) it is untouched too: `tmp` stays and the error names it. When /// the copy into `target` fails it is damaged: `tmp` and the copy of the old content stay and the -/// error says where they are. -fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { +/// error says where they are. `check` runs again right before `target` is overwritten. +fn write_over(tmp: &Path, target: &Path, refused: io::Error, check: &dyn Fn() -> io::Result<()>) -> io::Result<()> { let old = tmp.with_extension("old"); let over = Over { tmp: &|| tmp.to_path_buf(), @@ -421,8 +473,20 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { remove_tmp: &|| { let _ = std::fs::remove_file(tmp); }, - open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) }, + // A missing target is created by `create_target`, after the last check. An existing one is + // opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it. + open_target: &|write| { + if !write { + return File::open(target); + } + if matches!(std::fs::symlink_metadata(target), Err(e) if e.kind() == io::ErrorKind::NotFound) { + return Err(io::ErrorKind::NotFound.into()); + } + OpenOptions::new().write(true).create(true).truncate(false).open(target) + }, + create_target: &|| create_new(target), synced: &|| sync_written_parent(target), + still_allowed: check, }; write_over_in(&over, refused) } @@ -441,38 +505,84 @@ struct Over<'a> { open_tmp: &'a dyn Fn() -> io::Result, /// Best effort. remove_tmp: &'a dyn Fn(), - /// The target for writing (created when missing, not truncated) when `true`, for reading when - /// `false`. + /// Opens the target without truncating it for writing when `true`, or for reading when `false`. + /// It never creates a missing target: `create_target` does that, after the final check. open_target: &'a dyn Fn(bool) -> io::Result, + /// Creates a missing target after the final check and fails if its name is taken. + create_target: &'a dyn Fn() -> io::Result, /// The target's folder flushed, after the target is written. synced: &'a dyn Fn() -> io::Result<()>, + /// Asked right before the target is overwritten: an error leaves it as it was. + still_allowed: &'a dyn Fn() -> io::Result<()>, } /// [`write_over`] through `over`. fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { - let opened = (over.open_tmp)().and_then(|from| Ok((from, (over.open_target)(true)?))); - let Ok((mut from, mut to)) = opened else { + // A missing target is created only after the final check. + if let Err(e) = (over.still_allowed)() { + (over.remove_tmp)(); + return Err(e); + } + let opened = (over.open_tmp)().and_then(|from| { + let to = match (over.open_target)(true) { + Ok(to) => Some(to), + Err(e) if e.kind() == io::ErrorKind::NotFound => None, + Err(e) => return Err(e), + }; + Ok((from, to)) + }); + let Ok((mut from, to)) = opened else { // Best effort: the temporary file is all there is to clean up. (over.remove_tmp)(); return Err(refused); }; // Nothing to keep of a file that is new or empty. The copy is read from the file `to` writes // into: one put at its name meanwhile is not copied in its place. - let kept = to.metadata().map_or(true, |m| m.len() > 0); + let kept = to.as_ref().is_some_and(|to| to.metadata().map_or(true, |m| m.len() > 0)); if kept && let Err(e) = (over.open_target)(false).and_then(|mut target| { - if !same_file(&target, &to) { + if !to.as_ref().is_some_and(|to| same_file(&target, to)) { return Err(io::Error::other("the file was replaced while it was opened")); } keep_old(&mut target, over) }) { + #[cfg(unix)] + if let Err(e) = (over.still_allowed)() { + drop((from, to)); + (over.remove_tmp)(); + return Err(e); + } let why = format!( "{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", (over.tmp)().display() ); return Err(io::Error::new(refused.kind(), RecoveryError(why))); } + if let Err(e) = (over.still_allowed)() { + // Nothing was overwritten: neither copy is needed. + drop((from, to)); + (over.remove_tmp)(); + if kept { + (over.remove_old)(); + } + return Err(e); + } + let mut to = match to { + Some(to) => to, + None => match (over.create_target)() { + Ok(to) => to, + // A file put at the name meanwhile is left alone, and reported as there. + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { + (over.remove_tmp)(); + return Err(e); + } + Err(_) => { + (over.remove_tmp)(); + return Err(refused); + } + }, + }; let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to)); drop((from, to)); match (copied, kept) { @@ -826,8 +936,18 @@ mod tests { (d, root, outside) } + /// Whether this system says where an open folder is now: macOS always, Linux and Android through + /// `/proc/self/fd`, which a chroot may lack. Decided without `folder_now`. #[cfg(unix)] - fn under(root: &Path) -> impl FnOnce(&Path) -> io::Result<()> + '_ { + fn reports_open_folder_paths() -> bool { + if cfg!(target_vendor = "apple") { + return true; + } + cfg!(any(target_os = "linux", target_os = "android")) && Path::new("/proc/self/fd").is_dir() + } + + #[cfg(unix)] + fn under(root: &Path) -> impl Fn(&Path) -> io::Result<()> + '_ { move |p: &Path| if p.starts_with(root) { Ok(()) } else { Err(io::Error::other(format!("{} is outside", p.display()))) } } @@ -851,22 +971,51 @@ mod tests { #[test] fn a_checked_write_stays_in_the_folder_it_opened() { let (d, root, outside) = checked_folders("checked-after"); - let check = under(&root); let r = write_atomic_checked( &root.join("inside/doc.txt"), - |f| f.write_all(b"new"), - |p| { - check(p)?; + |f| { std::fs::rename(root.join("inside"), root.join("moved"))?; - std::os::unix::fs::symlink(&outside, root.join("inside")) + std::os::unix::fs::symlink(&outside, root.join("inside"))?; + f.write_all(b"new") }, + under(&root), ); + if !reports_open_folder_paths() { + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("the folder moved")), "{r:?}"); + assert!(!outside.join("doc.txt").exists() && !root.join("moved/doc.txt").exists()); + assert!(std::fs::read_dir(root.join("moved")).unwrap().next().is_none()); + let _ = std::fs::remove_dir_all(d); + return; + } r.unwrap(); assert!(!outside.join("doc.txt").exists(), "the write followed the replaced folder"); assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"new"); let _ = std::fs::remove_dir_all(d); } + /// A folder moved out of the allowed root while the file is written receives nothing: the move is + /// caught before the file is put in place, and the temporary file is removed. + #[cfg(unix)] + #[test] + fn a_checked_write_refuses_a_folder_moved_outside_while_it_fills() { + let (d, root, outside) = checked_folders("checked-moved-out"); + let r = write_atomic_checked( + &root.join("inside/doc.txt"), + |f| { + f.write_all(b"new")?; + std::fs::rename(root.join("inside"), outside.join("inside")) + }, + under(&root), + ); + assert!(r.as_ref().is_err_and(|e| !read_only_location(e)), "{r:?}"); + let message = r.unwrap_err().to_string(); + assert!(message.contains(&root.join("inside/doc.txt").display().to_string()), "{message}"); + assert!(message.contains("the folder moved"), "{message}"); + assert!(!message.contains(&outside.display().to_string()), "{message}"); + assert!(std::fs::read_dir(outside.join("inside")).unwrap().next().is_none(), "nothing is left outside"); + let _ = std::fs::remove_dir_all(d); + } + /// A link put at the file's name after the check is replaced by the file, not followed. #[cfg(unix)] #[test] @@ -922,31 +1071,34 @@ mod tests { let _ = std::fs::remove_dir_all(d); } - /// A checked write whose folder moved after it was opened, refused the rename, and failed to - /// copy into the file: the temporary file and the copy of the old content stay in that folder, - /// and the error names them where they are now. (FreeBSD does not say where an open folder is - /// now: there the error names them where the folder was opened.) + /// A failed fallback names the recovery files in the folder's current location when available. + /// A move is refused when the system cannot resolve the open folder's current path. #[cfg(unix)] #[test] fn a_checked_write_names_the_kept_file_where_its_folder_moved() { let (d, root, _) = checked_folders("checked-moved"); std::fs::write(root.join("inside/doc.txt"), b"original").unwrap(); - let check = under(&root); let r = write_atomic_checked( &root.join("inside/doc.txt"), - |f| f.write_all(b"new"), - |p| { - check(p)?; + |f| { std::fs::rename(root.join("inside"), root.join("moved"))?; RENAME_REFUSED.with(|c| c.set(true)); // The temporary file's flush and the copy of the old content work, the next doesn't. FLUSHES_LEFT.with(|c| c.set(Some(2))); - Ok(()) + f.write_all(b"new") }, + under(&root), ); RENAME_REFUSED.with(|c| c.set(false)); FLUSHES_LEFT.with(|c| c.set(None)); let message = r.unwrap_err().to_string(); + if !reports_open_folder_paths() { + assert!(message.contains("the folder moved"), "{message}"); + assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"original"); + assert_eq!(std::fs::read_dir(root.join("moved")).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(d); + return; + } let kept = |ext: &str| -> PathBuf { let found: Vec<_> = std::fs::read_dir(root.join("moved")) .unwrap() @@ -958,15 +1110,219 @@ mod tests { }; let (tmp, old) = (kept("tmp"), kept("old")); assert_eq!((std::fs::read(&tmp).unwrap(), std::fs::read(&old).unwrap()), (b"new".to_vec(), b"original".to_vec())); - let named_in = - if cfg!(any(target_os = "linux", target_os = "android", target_vendor = "apple")) { root.join("moved") } else { root.join("inside") }; for file in [&tmp, &old] { - let named = named_in.join(file.file_name().unwrap()); + let named = root.join("moved").join(file.file_name().unwrap()); assert!(message.contains(&named.display().to_string()), "{} in {message}", named.display()); } let _ = std::fs::remove_dir_all(d); } + /// A refused rename onto a missing file that is no longer allowed at the final check does not + /// create the file. + #[test] + fn a_refused_rename_does_not_create_a_missing_file_once_no_longer_allowed() { + let d = dir("no-rename-missing-disallowed"); + let (path, tmp) = (d.join("doc.txt"), d.join("doc.tmp")); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let check = || { + checks.set(checks.get() + 1); + if checks.get() == 1 { Ok(()) } else { Err(io::Error::other("moved outside")) } + }; + let e = write_over(&tmp, &path, denied::<()>().unwrap_err(), &check).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert!(!path.exists(), "the refused write created {}", path.display()); + assert!(!tmp.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// A refused rename whose folder is no longer allowed by the time the file would be overwritten + /// leaves the file as it was, and neither copy stays behind. + #[test] + fn a_refused_rename_does_not_overwrite_once_no_longer_allowed() { + let d = dir("no-rename-disallowed"); + let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old")); + std::fs::write(&path, b"original").unwrap(); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let over = Over { + tmp: &|| tmp.clone(), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, + open_tmp: &|| File::open(&tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(&tmp); + }, + open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, + create_target: &|| create_new(&path), + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if checks.get() == 1 { + Ok(()) + } else { + assert_eq!(std::fs::read(&old).unwrap(), b"original"); + Err(io::Error::other("moved outside")) + } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + assert!(!tmp.exists() && !old.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// A backup failure after a folder moves outside removes the new content and reports the refusal. + #[cfg(unix)] + #[test] + fn a_refused_rename_rechecks_authorization_after_a_backup_error() { + let (d, root, outside) = checked_folders("no-rename-backup-moved"); + let inside = root.join("inside"); + let moved = outside.join("inside"); + let path = inside.join("doc.txt"); + std::fs::write(&path, b"original").unwrap(); + std::fs::write(inside.join("doc.tmp"), b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let over = Over { + tmp: &|| moved.join("doc.tmp"), + create_old: &|| { + std::fs::rename(&inside, &moved)?; + Err(io::Error::other("backup failed")) + }, + old: &|| moved.join("doc.old"), + remove_old: &|| {}, + open_tmp: &|| File::open(inside.join("doc.tmp")), + remove_tmp: &|| { + let _ = std::fs::remove_file(moved.join("doc.tmp")); + }, + open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, + create_target: &|| create_new(&path), + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if inside.exists() { Ok(()) } else { Err(io::Error::other("moved outside")) } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert!(!e.to_string().contains(&outside.display().to_string()), "{e}"); + assert!(!e.get_ref().is_some_and(|e| e.is::())); + assert_eq!(std::fs::read(moved.join("doc.txt")).unwrap(), b"original"); + assert_eq!(std::fs::read_dir(&moved).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(d); + } + + /// A refused fallback leaves a missing target absent when the final check fails. + #[cfg(unix)] + #[test] + fn a_refused_rename_leaves_a_missing_target_absent_once_no_longer_allowed() { + let d = dir("no-rename-disallowed-new"); + let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old")); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let created = std::cell::Cell::new(false); + let over = Over { + tmp: &|| tmp.clone(), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, + open_tmp: &|| File::open(&tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(&tmp); + }, + open_target: &|write| { + if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) } + }, + create_target: &|| { + created.set(true); + create_new(&path) + }, + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if checks.get() == 1 { + assert!(!path.exists()); + Ok(()) + } else { + assert!(!created.get() && !path.exists()); + Err(io::Error::other("moved outside")) + } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert!(!created.get()); + assert!(!path.exists()); + assert!(!tmp.exists() && !old.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// A checked fallback creates a missing target after authorization succeeds. + #[cfg(unix)] + #[test] + fn a_checked_write_creates_a_missing_target_when_the_rename_is_refused() { + let (d, root, _) = checked_folders("checked-new-no-rename"); + let path = root.join("inside/doc.txt"); + RENAME_REFUSED.with(|c| c.set(true)); + let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + RENAME_REFUSED.with(|c| c.set(false)); + r.unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + assert_eq!(std::fs::read_dir(root.join("inside")).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(d); + } + + /// A file created by another writer at the final check is preserved whether that check succeeds or fails. + #[cfg(unix)] + #[test] + fn a_refused_rename_preserves_a_target_created_at_the_final_check() { + for allowed in [false, true] { + let d = dir("no-rename-new-target-taken"); + let (path, tmp) = (d.join("doc.txt"), d.join("doc.tmp")); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let over = Over { + tmp: &|| tmp.clone(), + create_old: &|| Err(io::Error::other("no backup expected")), + old: &|| d.join("doc.old"), + remove_old: &|| {}, + open_tmp: &|| File::open(&tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(&tmp); + }, + open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, + create_target: &|| create_new(&path), + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if checks.get() == 1 { + return Ok(()); + } + std::fs::write(&path, b"someone else's")?; + if allowed { Ok(()) } else { Err(io::Error::other("moved outside")) } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + if !allowed { + assert!(e.to_string().contains("moved outside"), "{e}"); + } + assert_eq!(std::fs::read(&path).unwrap(), b"someone else's"); + assert!(!tmp.exists() && !d.join("doc.old").exists()); + let _ = std::fs::remove_dir_all(d); + } + } + /// A refused rename copies the old content through the file handle it then overwrites: when a /// different file is at the name by the time it is opened for reading, nothing is overwritten and /// the new content stays in the temporary file. @@ -991,7 +1347,9 @@ mod tests { let _ = std::fs::remove_file(&tmp); }, open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&other) }, + create_target: &|| create_new(&path), synced: &|| Ok(()), + still_allowed: &|| Ok(()), }; let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); assert!(e.to_string().contains("the file was replaced while it was opened"), "{e}"); @@ -1091,6 +1449,156 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// A checked write whose fill fails puts nothing in place: the error is returned, the file + /// keeps its old content, and the temporary file is removed. + #[cfg(unix)] + #[test] + fn a_checked_write_keeps_the_original_when_its_fill_fails() { + let (d, root, _) = checked_folders("checked-fill-fails"); + let folder = root.join("inside"); + std::fs::write(folder.join("doc.txt"), b"original").unwrap(); + let r = write_atomic_checked( + &folder.join("doc.txt"), + |f| { + f.write_all(b"half a fi")?; + Err(io::Error::other("disk full")) + }, + under(&root), + ); + assert_eq!(r.map_err(|e| e.to_string()), Err("disk full".to_string())); + assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"original"); + assert!(leftovers(&folder, "doc.txt").is_empty(), "{:?}", leftovers(&folder, "doc.txt")); + let _ = std::fs::remove_dir_all(d); + } + + /// A checked write canceled while it fills puts nothing in place: the error is the + /// cancellation, the file keeps its old content, and the temporary file is removed. + #[cfg(unix)] + #[test] + fn a_checked_write_canceled_while_it_fills_keeps_the_original() { + use vectorcraft_doc::cancel::{CancelToken, Cancelled, scope}; + let (d, root, _) = checked_folders("checked-cancel"); + let folder = root.join("inside"); + std::fs::write(folder.join("doc.txt"), b"original").unwrap(); + let token = CancelToken::new(); + let r = scope(&token, None, || { + write_atomic_checked( + &folder.join("doc.txt"), + |f| { + f.write_all(b"new")?; + token.cancel(); + Ok(()) + }, + under(&root), + ) + }); + assert!(r.as_ref().is_err_and(|e| e.get_ref().is_some_and(|e| e.is::())), "{r:?}"); + assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"original"); + assert!(leftovers(&folder, "doc.txt").is_empty(), "{:?}", leftovers(&folder, "doc.txt")); + let _ = std::fs::remove_dir_all(d); + } + + /// Makes `folder` refuse new files (mode 0o555). `false`, with the folder writable again, when + /// a new file can still be created there (root ignores the mode). + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + fn refuse_new_files(folder: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o555)).unwrap(); + let probe = folder.join("probe"); + if std::fs::write(&probe, b"").is_ok() { + let _ = std::fs::remove_file(&probe); + std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + return false; + } + true + } + + /// Files in the system's temporary folder whose names start with the temporary names a write + /// to a file named `name` uses. + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + fn system_temp_files(name: &str) -> Vec { + let prefix = format!(".{name}.{}-", std::process::id()); + std::fs::read_dir(std::env::temp_dir()) + .unwrap() + .filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().to_string())) + .filter(|n| n.starts_with(&prefix)) + .collect() + } + + /// A checked write over a file whose folder refuses the rename and then any new file: the copy + /// of the file as it was goes to the system's temporary folder, the new content is copied into + /// the file, and that copy is removed afterwards. (Skipped for root.) + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + #[test] + fn a_checked_write_keeps_the_old_copy_outside_a_folder_that_takes_no_new_file() { + use std::os::unix::fs::PermissionsExt; + let name = "checked-old-elsewhere.txt"; + let (d, root, _) = checked_folders("checked-old-elsewhere"); + let folder = root.join("inside"); + std::fs::write(folder.join(name), b"original, and longer").unwrap(); + let refused = std::cell::Cell::new(true); + let r = write_atomic_checked( + &folder.join(name), + |f| { + f.write_all(b"new")?; + RENAME_REFUSED.with(|c| c.set(true)); + refused.set(refuse_new_files(&folder)); + Ok(()) + }, + under(&root), + ); + RENAME_REFUSED.with(|c| c.set(false)); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + if !refused.get() { + let _ = std::fs::remove_dir_all(d); + eprintln!("skipped: the folder takes new files whatever its mode (running as root)"); + return; + } + r.unwrap(); + assert_eq!(std::fs::read(folder.join(name)).unwrap(), b"new"); + assert!(!leftovers(&folder, name).iter().any(|n| n.ends_with(".old")), "{:?}", leftovers(&folder, name)); + assert!(system_temp_files(name).is_empty(), "{:?}", system_temp_files(name)); + let _ = std::fs::remove_dir_all(d); + } + + /// A folder that refuses the temporary file of a checked write but lets the file itself be + /// written: the content is written in the system's temporary folder and copied in, and nothing + /// is left behind. A failed fill there leaves the file as it was. (Skipped for root.) + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + #[test] + fn a_checked_write_saves_through_the_system_folder_when_its_folder_takes_no_temporary_file() { + use std::os::unix::fs::PermissionsExt; + let name = "checked-no-temp.txt"; + let (d, root, _) = checked_folders("checked-no-temp"); + let folder = root.join("inside"); + std::fs::write(folder.join(name), b"original, and longer").unwrap(); + if !refuse_new_files(&folder) { + let _ = std::fs::remove_dir_all(d); + eprintln!("skipped: the folder takes new files whatever its mode (running as root)"); + return; + } + let saved = write_atomic_checked(&folder.join(name), |f| f.write_all(b"new"), under(&root)); + let saved_content = std::fs::read(folder.join(name)).unwrap(); + let saved_temp = system_temp_files(name); + let failed = write_atomic_checked( + &folder.join(name), + |f| { + f.write_all(b"half a fi")?; + Err(io::Error::other("disk full")) + }, + under(&root), + ); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + saved.unwrap(); + assert_eq!(saved_content, b"new"); + assert!(saved_temp.is_empty(), "{saved_temp:?}"); + assert_eq!(failed.map_err(|e| e.to_string()), Err("disk full".to_string())); + assert_eq!(std::fs::read(folder.join(name)).unwrap(), b"new"); + assert!(leftovers(&folder, name).is_empty(), "{:?}", leftovers(&folder, name)); + assert!(system_temp_files(name).is_empty(), "{:?}", system_temp_files(name)); + let _ = std::fs::remove_dir_all(d); + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() @@ -1431,6 +1939,64 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A check that refuses after the file is filled keeps the old file, removes the temporary file + /// and tries no rename, whether the folder takes the temporary file or not. + #[test] + fn a_check_refused_after_the_fill_keeps_the_file() { + let d = dir("staged-check"); + let path = d.join("staged-check.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + let renamed = std::cell::Cell::new(false); + let rename = |_: &Path, _: &Path| { + renamed.set(true); + Ok(()) + }; + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), create_new, || Err(io::Error::other("moved away")), rename); + assert_eq!(r.unwrap_err().to_string(), "moved away"); + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), |_| denied(), || Err(io::Error::other("moved away")), rename); + assert_eq!(r.unwrap_err().to_string(), "moved away"); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(!renamed.get() && leftovers(&d, "staged-check.vectorcraft").is_empty()); + // A folder that refuses the rename: the check runs again before the file is written over. + let calls = std::cell::Cell::new(0); + let check = || { + calls.set(calls.get() + 1); + if calls.get() > 1 { Err(io::Error::other("moved away")) } else { Ok(()) } + }; + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), create_new, check, |_, _| denied()); + assert!(r.is_err_and(|e| e.to_string().contains("moved away"))); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(leftovers(&d, "staged-check.vectorcraft").is_empty()); + let staged = format!(".staged-check.vectorcraft.{}-", std::process::id()); + let in_system = std::fs::read_dir(std::env::temp_dir()).unwrap().filter_map(Result::ok); + assert!(!in_system.into_iter().any(|e| e.file_name().to_string_lossy().starts_with(&staged)), "the system's folder keeps no staging file"); + let _ = std::fs::remove_dir_all(&d); + } + + /// Off Unix the check runs again after the file is filled: a refusal at that point keeps the + /// old file and leaves no temporary file. + #[cfg(not(unix))] + #[test] + fn a_checked_write_checks_again_before_the_file_is_put_in_place() { + let d = dir("checked-twice"); + let path = d.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + let calls = std::cell::Cell::new(0); + let r = write_atomic_checked( + &path, + |f| f.write_all(b"new"), + |_| { + calls.set(calls.get() + 1); + if calls.get() > 1 { Err(io::Error::other("no longer allowed")) } else { Ok(()) } + }, + ); + assert_eq!(r.unwrap_err().to_string(), "no longer allowed"); + assert_eq!(calls.get(), 2); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(leftovers(&d, "doc.vectorcraft").is_empty()); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn write_new_never_replaces_what_is_there() { let d = dir("new"); diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 9975527f78..c7157df94d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -37,6 +37,7 @@ //! already; [`save_with`] writes a version 1 document with them negated back for an older file //! version ([`vectorcraft_doc::twist`]). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #[cfg(not(target_arch = "wasm32"))] mod atomic; diff --git a/crates/format/src/unpack.rs b/crates/format/src/unpack.rs index ec9623118c..e636aadf74 100644 --- a/crates/format/src/unpack.rs +++ b/crates/format/src/unpack.rs @@ -374,6 +374,36 @@ mod tests { assert!(matches!(Unpacked::within(&gz, json.len() as u64 - 1), Err(FormatError::TooBig))); } + /// A compressed file with data after its JSON is refused past its budget on both paths: the + /// JSON before the marker where the writer puts it, and the whole file when the marker is + /// elsewhere and the file is unpacked whole. + #[test] + fn a_compressed_file_with_data_is_capped_on_both_paths() { + let with_data = |json: &[u8]| { + let mut file = json.to_vec(); + file.extend(crate::BLOB_MAGIC); + file.extend([1u8; 64]); + file + }; + let mut json = br#"{"pad":""#.to_vec(); + json.extend(std::iter::repeat_n(b'x', 4096)); + json.extend(br#""}"#); + let streamed = gzip(&with_data(&json)); + let max_json = json.len() as u64; + let opened = Unpacked::within(&streamed, max_json).unwrap(); + assert!(matches!(opened.tail, Tail::Stream { .. }), "read as a stream"); + assert_eq!(opened.json(), json.as_slice()); + assert!(matches!(Unpacked::within(&streamed, max_json - 1), Err(FormatError::TooBig))); + // No `}` before the marker: unpacked whole, within the whole-file cap and not one byte past it. + let plain = with_data(b"1"); + let whole = gzip(&plain); + let max_whole = plain.len() as u64; + let opened = Unpacked::within_capped(&whole, 64, max_whole, MAX_BLOBS).unwrap(); + assert!(matches!(opened.tail, Tail::Whole(_)), "unpacked whole"); + assert_eq!(opened.json(), b"1"); + assert!(matches!(Unpacked::within_capped(&whole, 64, max_whole - 1, MAX_BLOBS), Err(FormatError::TooBig))); + } + #[test] fn entries_sharing_bytes_obey_the_limits_in_memory_too() { // Each entry within MAX_BLOB, together past MAX_BLOBS: many references to the same bytes. diff --git a/crates/geom/src/anchors.rs b/crates/geom/src/anchors.rs index 3b9f4aa9bd..186c4b53c0 100644 --- a/crates/geom/src/anchors.rs +++ b/crates/geom/src/anchors.rs @@ -892,4 +892,27 @@ mod tests { moved.remove(0); assert_eq!(before.pairs_not_shared(&moved).count(), 10_000); } + + /// The table bytes are what the chunk table and the running totals have reserved, which is at + /// least what they hold. A short list has no running totals; a list split unevenly by an insert + /// has both, and spare capacity in either table counts. + #[test] + fn table_bytes_count_the_chunk_table_and_the_running_totals() { + let (chunk, total) = (size_of::>>(), size_of::()); + let reserved = |a: &Anchors| { + let held = a.chunks.len() * chunk + a.ends.len() * total; + let reserved = a.chunks.capacity() * chunk + a.ends.capacity() * total; + assert!(held <= reserved); + a.table_bytes() == reserved + }; + let short = Anchors::from(line(5)); + assert!(short.ends.is_empty() && reserved(&short), "{}", short.table_bytes()); + let mut uneven = Anchors::from(line(CHUNK)); + uneven.insert(10, Anchor::corner(Point::ZERO)); + assert!(uneven.chunks.len() == 2 && uneven.ends.len() == 2, "{:?}", uneven.ends); + uneven.chunks.reserve(8); + uneven.ends.reserve(8); + assert!(uneven.chunks.capacity() > uneven.chunks.len() && uneven.ends.capacity() > uneven.ends.len()); + assert!(reserved(&uneven), "{}", uneven.table_bytes()); + } } diff --git a/crates/geom/src/bez.rs b/crates/geom/src/bez.rs index 8f6b3c4a0a..6565c7d68e 100644 --- a/crates/geom/src/bez.rs +++ b/crates/geom/src/bez.rs @@ -106,4 +106,15 @@ mod tests { assert_eq!(tangent(&c[0], 1.0), Vec2::new(0.0, 1.0)); assert_eq!(unit(Vec2::ZERO), Vec2::new(1.0, 0.0)); } + + /// A quadratic whose three points coincide has no length; one whose middle point lies off its + /// coinciding ends has length. + #[test] + fn a_quad_has_length_unless_its_points_coincide() { + use kurbo::{Point, QuadBez}; + let (p, q) = (Point::new(3.0, 4.0), Point::new(9.0, -2.0)); + assert!(!has_length(&PathSeg::Quad(QuadBez::new(p, p, p)))); + assert!(has_length(&PathSeg::Quad(QuadBez::new(p, q, p)))); + assert!(has_length(&PathSeg::Quad(QuadBez::new(p, p, q)))); + } } diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index aea7afde1d..ac6f721b85 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -219,12 +219,333 @@ pub fn circular_arc(c: CubicBez) -> Option<(Point, f64)> { ((l0 - handle).abs() <= HANDLE_TOL * handle && (l3 - handle).abs() <= HANDLE_TOL * handle).then_some((center, radius)) } +/// One tooth of a curvature comb: it starts on the curve at `at` and ends at `tip`, along the +/// curve's normal on the side away from its center of curvature, `scale` times the curvature long. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CombTooth { + pub at: Point, + pub tip: Point, + /// The first tooth of the comb, the first after a point or segment that has no tooth, or the + /// first after the curve turns back on itself (a cusp between two teeth): a line through the + /// tips starts again here. + pub start: bool, + /// The index of the segment the tooth sits on. + pub segment: usize, +} + +/// The most teeth a curvature comb draws in all. +pub const MAX_COMB_TEETH: usize = 20_000; + +/// The curvature comb of `sp`: `samples` teeth on each segment (at least 2), evenly spaced in `t` +/// from 0 to 1, each `scale` times the signed curvature long ([`CombTooth`]). A straight segment +/// gives teeth of no length, its ends included. A point of a curved segment where it has no +/// direction (a handle drawn back onto its anchor) gives no tooth, and neither does a segment +/// with no length, a segment whose points are not finite, or a `scale` that is not finite. When +/// `samples` teeth on every segment would pass `max_teeth`, every segment gets 2 teeth, and when +/// that would still pass it, only every k-th segment gets teeth, spread along the whole subpath. +pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize) -> Vec { + let n = sp.segment_count(); + if n == 0 || !scale.is_finite() || max_teeth < 2 { + return vec![]; + } + let per = if samples.max(2).saturating_mul(n) <= max_teeth { samples.max(2) } else { 2 }; + let stride = (per * n).div_ceil(max_teeth).max(1); + let mut teeth = Vec::with_capacity((per * n / stride).min(max_teeth)); + let mut start = true; + // The direction of the last curved tooth, carried across segments so that a cusp at an + // anchor also starts a new line through the tips. + let mut previous_direction: Option = None; + for seg in (0..n).step_by(stride) { + if stride > 1 { + start = true; + previous_direction = None; + } + let c = sp.segment(seg); + if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) { + start = true; + previous_direction = None; + continue; + } + let (d1, d2) = (c.deriv(), c.deriv().deriv()); + // The control polygon's length sets what counts as no speed. + let size = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + let chord = c.p3 - c.p0; + let line = sp.segment_is_line(seg) && chord.hypot() > 0.0; + for i in 0..per { + if teeth.len() >= max_teeth { + return teeth; + } + let t = i as f64 / (per - 1) as f64; + if line { + // A line stored with its handles on its anchors has no speed at its ends, but a + // direction and no curvature all along. + let at = c.eval(t); + previous_direction = None; + if !at.is_finite() { + start = true; + continue; + } + teeth.push(CombTooth { at, tip: at, start, segment: seg }); + start = false; + continue; + } + let (v, a) = (d1.eval(t).to_vec2(), d2.eval(t).to_vec2()); + let speed = v.hypot(); + if speed <= CUSP_SHARE * size || !speed.is_finite() { + start = true; + previous_direction = None; + continue; + } + let k = v.cross(a) / (speed * speed * speed); + let direction = v / speed; + start |= previous_direction.is_some_and(|previous| previous.dot(direction) < 0.0); + previous_direction = Some(direction); + let normal = Vec2::new(-direction.y, direction.x); + let at = c.eval(t); + let tip = at - normal * (k * scale); + if !at.is_finite() || !tip.is_finite() { + start = true; + previous_direction = None; + continue; + } + teeth.push(CombTooth { at, tip, start, segment: seg }); + start = false; + } + } + teeth +} + +/// Does the line through the tips of `teeth`, the comb of `sp` ([`curvature_comb`]), close where +/// it starts: `sp` is closed, only segments with no length lie between its last tooth and its +/// first across the seam, the two sit on the same point, and the curve does not turn back on itself at its +/// first anchor. A comb that skips segments to keep to its budget does not close across the ones +/// it skipped at the end. +pub fn comb_closes(sp: &SubPath, teeth: &[CombTooth]) -> bool { + let (Some(first), Some(last)) = (teeth.first(), teeth.last()) else { + return false; + }; + let n = sp.segment_count(); + if !sp.closed || teeth.len() < 2 || first.at.distance(last.at) >= 1e-9 { + return false; + } + // Only segments with no length may lie between the last tooth and the first across the seam. + let no_length = |i: usize| start_direction(sp.segment(i)) == Vec2::ZERO; + if !(last.segment + 1..n).chain(0..first.segment).all(no_length) { + return false; + } + match (neighbor(sp, 0, false), neighbor(sp, n.saturating_sub(1), true)) { + (Some((into, _)), Some((out, _))) => end_direction(into).dot(start_direction(out)) >= 0.0, + _ => false, + } +} + #[cfg(test)] mod tests { use super::*; use crate::{Anchor, shapes}; use kurbo::Rect; + fn tooth_len(t: &CombTooth) -> f64 { + t.at.distance(t.tip) + } + + /// A circle's comb points away from the center, each tooth `scale` times the cubic's own + /// curvature at its point ([`curvature_circle_with`] without arcs), all within 3% of + /// `scale / r` (the usual cubic of a quarter turn strays that little from its circle). + #[test] + fn the_comb_of_a_circle_has_teeth_of_one_length() { + let pd = shapes::ellipse(Rect::new(50.0, 50.0, 250.0, 250.0)); + let sp = &pd.subpaths[0]; + let teeth = curvature_comb(sp, 9, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 9 * sp.segment_count()); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 1, "one unbroken comb"); + let center = Point::new(150.0, 150.0); + for (i, t) in teeth.iter().enumerate() { + let (seg, at) = (i / 9, (i % 9) as f64 / 8.0); + let r = curvature_circle_with(sp.segment(seg), at, false, false).unwrap().radius; + assert!((tooth_len(t) * r - 1000.0).abs() < 1e-6, "{t:?} {r}"); + assert!((tooth_len(t) - 10.0).abs() < 0.3, "{t:?}"); + assert!(t.tip.distance(center) > t.at.distance(center), "outward: {t:?}"); + } + } + + /// A straight line has teeth of no length, its two ends included. + #[test] + fn the_comb_of_a_line_is_flat() { + let sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 40.0), Point::new(200.0, 0.0)], false); + let teeth = curvature_comb(&sp, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 10); + assert!(teeth.iter().all(|t| tooth_len(t) < 1e-9), "{teeth:?}"); + assert_eq!(teeth[4].at, Point::new(100.0, 40.0), "the corner has a tooth on each side"); + } + + /// Two quarter circles of radius 100 and 50 that meet in one direction: the teeth double in + /// length at the anchor they share. + #[test] + fn the_comb_jumps_where_the_curvature_does() { + let k = 4.0 / 3.0 * (std::f64::consts::FRAC_PI_8).tan(); + let a0 = Anchor { h_out: Point::new(100.0 * k, 0.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { + h_in: Point::new(100.0, 100.0 - 100.0 * k), + h_out: Point::new(100.0, 100.0 + 50.0 * k), + ..Anchor::corner(Point::new(100.0, 100.0)) + }; + let a2 = Anchor { h_in: Point::new(50.0 + 50.0 * k, 150.0), ..Anchor::corner(Point::new(50.0, 150.0)) }; + let sp = SubPath::new(vec![a0, a1, a2], false); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6); + let (before, after) = (tooth_len(&teeth[2]), tooth_len(&teeth[3])); + assert!((after / before - 2.0).abs() < 1e-9, "{before} {after}"); + assert!((before - 10.0).abs() < 0.3, "{before}"); + assert!(teeth[2].at.distance(teeth[3].at) < 1e-9, "both teeth start on the shared anchor"); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 1, "a smooth anchor keeps one unbroken comb"); + } + + /// Two segments that meet at a cusp on their shared anchor: the first segment ends heading + /// down and the second starts heading up, so the line through the tips starts again there. + #[test] + fn the_comb_breaks_at_a_cusp_on_an_anchor() { + let a0 = Anchor { h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { h_in: Point::new(100.0, -50.0), h_out: Point::new(100.0, -25.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let a2 = Anchor { h_in: Point::new(200.0, -25.0), ..Anchor::corner(Point::new(200.0, 0.0)) }; + let sp = SubPath::new(vec![a0, a1, a2], false); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, true, false, false]); + assert!(!comb_closes(&sp, &teeth), "an open subpath does not close"); + } + + /// A closed comb closes at its first anchor when the curve goes on smoothly there, even with a + /// cusp elsewhere, and stays open when the first anchor is the cusp. + #[test] + fn the_comb_closes_unless_its_first_anchor_is_a_cusp() { + let closed = |h_in: Point| { + let a0 = Anchor { h_in, h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { h_in: Point::new(100.0, -50.0), h_out: Point::new(100.0, -25.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let a2 = Anchor { h_in: Point::new(200.0, -25.0), h_out: Point::new(200.0, 50.0), ..Anchor::corner(Point::new(200.0, 0.0)) }; + SubPath::new(vec![a0, a1, a2], true) + }; + let smooth = closed(Point::new(0.0, 50.0)); + let teeth = curvature_comb(&smooth, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 2, "the cusp at the second anchor breaks the comb"); + assert!(comb_closes(&smooth, &teeth)); + let cusp = closed(Point::new(0.0, -50.0)); + assert!(!comb_closes(&cusp, &curvature_comb(&cusp, 3, 1000.0, MAX_COMB_TEETH))); + let circle = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + let sp = &circle.subpaths[0]; + assert!(comb_closes(sp, &curvature_comb(sp, 5, 1000.0, MAX_COMB_TEETH))); + } + + /// A segment with no length and a handle drawn back onto its anchor do not panic and give no + /// tooth where the curve has no direction; a scale that is not finite gives no comb. + #[test] + fn the_comb_skips_points_with_no_direction() { + let p = Point::new(10.0, 10.0); + assert!(curvature_comb(&SubPath::polyline(&[p, p], false), 4, 1000.0, MAX_COMB_TEETH).is_empty()); + let curve = SubPath::new( + vec![Anchor { h_out: Point::new(50.0, 0.0), ..Anchor::corner(Point::new(0.0, 0.0)) }, Anchor::corner(Point::new(100.0, 100.0))], + false, + ); + let teeth = curvature_comb(&curve, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the end whose handle sits on its anchor has no tooth: {teeth:?}"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, false]); + let back = SubPath::new( + vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor { h_in: Point::new(50.0, 0.0), ..Anchor::corner(Point::new(100.0, 100.0)) }], + false, + ); + let teeth = curvature_comb(&back, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the start, whose handle sits on its anchor, has no tooth: {teeth:?}"); + assert!(teeth[0].start, "the comb starts after the point with no tooth"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert!(curvature_comb(&curve, 5, f64::NAN, MAX_COMB_TEETH).is_empty()); + } + + /// A cusp between samples starts a new line through the comb's tips after the cusp. + #[test] + fn the_comb_breaks_at_a_cusp_between_samples() { + let bp = kurbo::BezPath::from_svg("M0 0 C100 100 0 100 100 0").unwrap(); + let sp = &crate::PathData::from_bezpath(&bp).subpaths[0]; + let teeth = curvature_comb(sp, 6, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6, "the cusp falls between teeth"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, true, false, false]); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + } + + /// A tooth whose tip overflows is skipped, and the next finite tooth starts a new envelope. + #[test] + fn the_comb_breaks_after_a_nonfinite_tip() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::new(-1.0, 1.0), Point::new(-1.0, 1.0), Point::new(-1.0 / 3.0, -1.0 / 3.0)), + Anchor::with_handles(Point::new(1.0, 1.0), Point::new(1.0 / 3.0, -1.0 / 3.0), Point::new(1.0, 1.0)), + ], + false, + ); + let teeth = curvature_comb(&sp, 5, f64::MAX, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the middle tooth overflows"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, true, false]); + assert!(teeth[1].at.x < 0.0 && teeth[2].at.x > 0.0, "the gap is inside the segment"); + } + + /// A speed whose cube underflows gives no tooth, and the first finite tooth starts the comb. + #[test] + fn the_comb_skips_a_tip_when_speed_cubed_underflows() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::ORIGIN, Point::ORIGIN, Point::new(1e-109, 0.0)), + Anchor::with_handles(Point::ORIGIN, Point::new(1e-101, 1e-101), Point::ORIGIN), + ], + false, + ); + let teeth = curvature_comb(&sp, 5, 1.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the first tooth has a nonfinite tip"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert!(teeth[0].start && teeth[0].at.x > 0.0, "the comb starts after the skipped tooth"); + } + + /// A subpath with more segments than the budget allows keeps to it, with teeth spread to its + /// far end rather than stopping part way. + #[test] + fn the_comb_is_capped_and_spread() { + let points: Vec = (0..30_001).map(|i| Point::new(i as f64, (i % 2) as f64)).collect(); + let sp = SubPath::polyline(&points, false); + let teeth = curvature_comb(&sp, 16, 1.0, 1000); + assert!(teeth.len() <= 1000 && teeth.len() >= 900, "{}", teeth.len()); + assert!(teeth.last().is_some_and(|t| t.at.x > 29_000.0), "{:?}", teeth.last()); + assert_eq!(teeth.iter().filter(|t| t.start).count() * 2, teeth.len(), "each sampled segment starts a new line through the tips"); + let few = curvature_comb(&sp, 16, 1.0, 100_000); + assert_eq!(few.len(), 60_000, "too many for 16 on each, so 2 on each"); + } + + /// A capped comb that skips the last segment does not close, even when the last segment it + /// samples ends on the first anchor: the line through the tips would cross the skipped loop. + #[test] + fn a_capped_comb_does_not_close_across_a_skipped_segment() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(-50.0, -50.0), Point::new(50.0, 50.0)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(80.0, 40.0), Point::new(120.0, 20.0)), + Anchor::with_handles(Point::new(100.0, 100.0), Point::new(140.0, 80.0), Point::new(60.0, 140.0)), + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(30.0, 120.0), Point::new(-60.0, 60.0)), + ], + true, + ); + let teeth = curvature_comb(&sp, 16, 1000.0, 4); + let (first, last) = (&teeth[0], &teeth[teeth.len() - 1]); + assert!(last.segment < 3, "the closing segment is skipped: {teeth:?}"); + assert!(first.at.distance(last.at) < 1e-9, "the last sampled tooth sits on the first anchor"); + assert!(!comb_closes(&sp, &teeth), "the comb does not close across the skipped last segment"); + assert!(comb_closes(&sp, &curvature_comb(&sp, 16, 1000.0, MAX_COMB_TEETH)), "the full comb closes"); + let mut anchors: Vec = sp.anchors.iter().copied().collect(); + anchors[0].h_in = anchors[0].p; + anchors.insert(0, Anchor { h_in: Point::new(-50.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }); + let seam = SubPath::new(anchors, true); + let full = curvature_comb(&seam, 16, 1000.0, MAX_COMB_TEETH); + assert_eq!(full.first().map(|t| t.segment), Some(1), "the segment of no length at the seam has no teeth"); + assert!(comb_closes(&seam, &full), "the comb closes across a segment of no length"); + } + /// Every segment of a circle drawn by [`shapes::ellipse`] is the usual cubic of a quarter /// turn, and the circle at any point of it is the circle itself: radius 100, center (150, 150). #[test] @@ -316,6 +637,33 @@ mod tests { assert!(curvature_circle(s, 0.25, false).is_ok()); } + /// A segment that bends by a billionth of a point over 300 points is straight: the limit grows + /// with the segment's speed, so a fast segment needs a larger bend to count as curved. A bend + /// a million times larger is curved. + #[test] + fn a_fast_segment_that_barely_bends_is_straight() { + let nearly = |dy: f64| CubicBez::new(Point::new(0.0, 0.0), Point::new(100.0, dy), Point::new(200.0, 0.0), Point::new(300.0, 0.0)); + assert_eq!(curvature_circle_with(nearly(1e-9), 0.5, false, false), Err(NoCircle::Straight)); + assert_eq!(osculating(nearly(1e-9), 0.5), Err(NoCircle::Straight)); + assert!(curvature_circle_with(nearly(1e-3), 0.5, false, false).is_ok()); + } + + /// The ends of a 60° cubic at radii 100 and 105 from where their normals cross are not the + /// cubic of a circular arc, even with handles of the right length for the mean radius; the + /// same cubic with both ends at radius 100 is one. + #[test] + fn ends_at_different_radii_are_not_a_circular_arc() { + let turn = 60f64.to_radians(); + let arc = |r3: f64, mean: f64| { + let handle = 4.0 / 3.0 * (turn / 4.0).tan() * mean; + let (p0, p3) = (Point::new(100.0, 0.0), Point::new(r3 * turn.cos(), r3 * turn.sin())); + CubicBez::new(p0, p0 + Vec2::new(0.0, handle), p3 - Vec2::new(-turn.sin(), turn.cos()) * handle, p3) + }; + assert_eq!(circular_arc(arc(105.0, 102.5)), None); + let (center, radius) = circular_arc(arc(100.0, 100.0)).unwrap(); + assert!(center.distance(Point::ORIGIN) < 1e-9 && (radius - 100.0).abs() < 1e-9, "{center:?} {radius}"); + } + /// A cusp, a handle drawn back onto its anchor at that end, a segment with no length, points /// that are not finite and a `t` outside 0 to 1 have no curvature circle. #[test] diff --git a/crates/geom/src/hit.rs b/crates/geom/src/hit.rs index 0358acac90..2624f0a1a9 100644 --- a/crates/geom/src/hit.rs +++ b/crates/geom/src/hit.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; -use kurbo::{BezPath, ParamCurveNearest, PathEl, Point, Rect, Shape}; +use kurbo::{BezPath, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape}; use crate::path::{FillRule, PathData}; @@ -104,13 +104,51 @@ fn closed(path: &BezPath) -> Cow<'_, BezPath> { /// Distance from `p` to the nearest point on the path outline. pub fn distance_to_outline(path: &BezPath, p: Point) -> f64 { - path.segments().map(|s| s.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt() + path.segments().map(|s| nearest_distance_sq(s, p)).fold(f64::INFINITY, f64::min).sqrt() } /// Is `p` within `tol` of the path's stroke of width `width`? pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool { - let quick = path.bounding_box().inflate(width / 2.0 + tol, width / 2.0 + tol); - quick.contains(p) && distance_to_outline(path, p) <= width / 2.0 + tol + let radius = width / 2.0 + tol; + if !path.bounding_box().inflate(radius, radius).contains(p) { + return false; + } + if !radius.is_finite() { + return distance_to_outline(path, p) <= radius; + } + + // Keep candidates whose squared distance could underflow near a zero radius. + let search_radius = radius.max(f64::MIN_POSITIVE.sqrt()); + path.segments().any(|segment| !curve_outside_reach(segment, p, search_radius) && nearest_distance_sq(segment, p).sqrt() <= radius) +} + +// A Bézier stays inside the bounds of its control points. A line projection is +// already cheap, so only check the bounds before running a curve solver. +fn curve_outside_reach(segment: PathSeg, p: Point, radius: f64) -> bool { + let bounds = match segment { + PathSeg::Line(_) => return false, + PathSeg::Quad(q) => Rect::from_points(q.p0, q.p1).union_pt(q.p2), + PathSeg::Cubic(c) => Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3), + }; + outside_axis(p.x, radius, bounds.x0, bounds.x1) || outside_axis(p.y, radius, bounds.y0, bounds.y1) +} + +fn outside_axis(p: f64, radius: f64, low: f64, high: f64) -> bool { + // Leave room for rounding in the curve evaluation and the distance comparison. + let scale = p.abs().max(low.abs()).max(high.abs()).max(radius); + let padded = radius + 8.0 * f64::EPSILON * scale; + p < low - padded || p > high + padded +} + +fn nearest_distance_sq(segment: PathSeg, p: Point) -> f64 { + #[cfg(test)] + OUTLINE_NEAREST_CALLS.with(|count| count.set(count.get() + 1)); + segment.nearest(p, 1e-9).distance_sq +} + +#[cfg(test)] +thread_local! { + static OUTLINE_NEAREST_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Does the path touch the rect: an anchor inside it, or a segment crossing its edges? Used for @@ -118,6 +156,14 @@ pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool { /// filled shape doesn't touch it, so a marquee drawn over a background picks only what is on it /// (#1103). pub fn intersects_rect(path: &PathData, r: Rect) -> bool { + // The control box holds every anchor and segment, and the path keeps it measured, so a path + // whose control box lies wholly apart from the rect misses it without measuring its segments. + // The test is strict: a control box that only touches the rect, or has no area, goes on to the + // exact checks below. + let (Some(c), n) = (path.control_bounds(), r.abs()) else { return false }; + if c.x1 < n.x0 || n.x1 < c.x0 || c.y1 < n.y0 || n.y1 < c.y0 { + return false; + } let Some(b) = path.bounds() else { return false }; let degenerate = |x: Rect| x.width() == 0.0 || x.height() == 0.0; if b.intersect(r).area() <= 0.0 && !degenerate(b) && !degenerate(r) { @@ -177,6 +223,53 @@ mod tests { assert!(!stroke_contains(&p, 2.0, 0.0, Point::new(12.0, 5.0))); } + #[test] + fn stroke_hit_skips_distant_curves_without_changing_results() { + let mut path = BezPath::new(); + for i in 0..96 { + let x = f64::from(i) * 16.0; + path.move_to((x, 0.0)); + path.curve_to((x + 1.0, 4.0), (x + 2.0, -4.0), (x + 3.0, 0.0)); + } + path.move_to((512.0, 0.0)); + path.quad_to((513.0, 4.0), (514.0, 0.0)); + + for (point, expected_hit, expected_calls) in [(Point::new(512.0, 0.0), true, 1), (Point::new(520.0, 0.0), false, 0)] { + assert_eq!(distance_to_outline(&path, point) <= 0.5, expected_hit); + assert!(path.bounding_box().contains(point)); + OUTLINE_NEAREST_CALLS.with(|count| count.set(0)); + assert_eq!(stroke_contains(&path, 0.0, 0.5, point), expected_hit); + assert_eq!(OUTLINE_NEAREST_CALLS.with(std::cell::Cell::get), expected_calls); + } + + assert_stroke_hits_at_cutoff(); + } + + fn assert_stroke_hits_at_cutoff() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((0.0, 0.0)); + path.quad_to((4.0, 8.0), (8.0, 0.0)); + path.curve_to((12.0, 8.0), (16.0, -4.0), (20.0, 0.0)); + path.close_path(); + path.move_to((2.0, -3.0)); + path.line_to((2.0, -3.0)); + + for transform in [kurbo::Affine::IDENTITY, kurbo::Affine::new([-2.0, 1.0, 0.0, 1.0, 10.0, 1e8])] { + let transformed = transform * path.clone(); + for x in -2..23 { + for y in -5..9 { + let point = transform * Point::new(f64::from(x), f64::from(y)); + let distance = distance_to_outline(&transformed, point); + for radius in [distance.next_down(), distance, distance.next_up(), 0.0, 1.5] { + let inside = transformed.bounding_box().inflate(radius, radius).contains(point); + assert_eq!(stroke_contains(&transformed, 0.0, radius, point), inside && distance <= radius, "{point:?}, {radius}"); + } + } + } + } + } + #[test] fn evenodd_hole() { let mut outer = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); @@ -238,6 +331,30 @@ mod tests { // zero-height marquee missing it assert!(!intersects_rect(&p, Rect::new(20.0, 5.0, 30.0, 5.0))); } + + /// A marquee that lies apart from a path's control box misses it without measuring the path's + /// segments. One that reaches the control box but not the curve is still judged on the curve. + #[test] + fn marquee_apart_from_the_control_box_measures_no_segment() { + let p = shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)); + let measured = crate::path::measured_segments; + let before = measured(); + assert!(!intersects_rect(&p, Rect::new(20.0, 20.0, 30.0, 30.0))); + assert!(!intersects_rect(&p, Rect::new(-30.0, 4.0, -20.0, 6.0))); + assert_eq!(measured(), before, "a marquee apart from the control box measures nothing"); + // A curve whose handle reaches into the marquee while the curve stays below it. + use crate::path::{Anchor, SubPath}; + let arch = PathData::new(vec![SubPath::new( + vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, 40.0)), + Anchor::with_handles(Point::new(10.0, 0.0), Point::new(10.0, 40.0), Point::new(10.0, 0.0)), + ], + false, + )]); + assert!(!intersects_rect(&arch, Rect::new(-1.0, 35.0, 11.0, 39.0)), "the curve peaks at y 30"); + assert!(measured() > before, "a marquee inside the control box measures the curve"); + assert!(intersects_rect(&arch, Rect::new(4.0, 25.0, 6.0, 35.0)), "a marquee across the peak"); + } } #[cfg(test)] diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 3f11c71062..8a4cb4f7fb 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -6,6 +6,7 @@ //! //! Coordinates are document points (1/72 in), y pointing down. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod anchors; pub mod arc; diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 2d23c4c3bc..3a3cc606c5 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -1697,4 +1697,99 @@ mod tests { let b3d = box3d(r, 30.0, 35.0, 0.0, true, true, true); assert!(!b3d.subpaths.is_empty() && b3d.subpaths.iter().all(|s| s.closed && s.anchors.len() == 4)); } + + /// Rounded with no Randomize still builds the rounded contour, for stars and polygons alike. + #[test] + fn rounded_shapes_without_randomize_have_handles_on_every_anchor() { + let star = star_configured(Point::ZERO, 50.0, 25.0, 5, 0.0, 0.5, 0.0); + assert_eq!(star.anchor_count(), 10); + assert!(star.subpaths[0].anchors.iter().all(|a| a.has_in() && a.has_out()), "star: {star:?}"); + let poly = polygon_configured(Point::ZERO, 50.0, 6, 0.0, 0.5, 0.0); + assert_eq!(poly.anchor_count(), 6); + assert!(poly.subpaths[0].anchors.iter().all(|a| a.has_in() && a.has_out()), "polygon: {poly:?}"); + } + + /// A rounded square's handles run along the unit tangent at each corner: 0.4 × Rounded of the + /// side long, at right angles to the radius. + #[test] + fn rounding_handles_are_their_share_of_the_side_along_the_tangent() { + let radius = 50.0; + let path = polygon_configured(Point::ZERO, radius, 4, 0.0, 1.0, 0.0); + let side = radius * 2.0_f64.sqrt(); + let want = 0.4 * side; + assert_eq!(path.anchor_count(), 4); + for a in &path.subpaths[0].anchors { + let (h_out, h_in, out_from_center) = (a.h_out - a.p, a.p - a.h_in, a.p.to_vec2()); + assert!((h_out.hypot() - want).abs() < 1e-9, "out handle {} long, want {want}", h_out.hypot()); + assert!((h_in.hypot() - want).abs() < 1e-9, "in handle {} long, want {want}", h_in.hypot()); + assert!(h_out.dot(out_from_center).abs() < 1e-9, "out handle {h_out:?} is not at right angles to {out_from_center:?}"); + assert!(h_in.dot(out_from_center).abs() < 1e-9, "in handle {h_in:?} is not at right angles to {out_from_center:?}"); + } + } + + /// A spiral starts at its center (inner radius 0) and ends a radius away, at the angle its turns + /// reach: an eighth past three whole turns, clockwise on screen, is down and to the right. + #[test] + fn a_spiral_runs_from_its_center_to_the_radius_at_its_last_angle() { + let (center, radius) = (Point::new(50.0, 60.0), 100.0); + let sp = spiral_configured(center, radius, 3.125, 1.0, 0.0, true); + let anchors = &sp.subpaths[0].anchors; + let (first, last) = (anchors[0].p, anchors[anchors.len() - 1].p); + assert!(first.distance(center) < 1e-9, "first anchor {first:?}, center {center:?}"); + let diagonal = radius / 2.0_f64.sqrt(); + let want = Point::new(center.x + diagonal, center.y + diagonal); + assert!(last.distance(want) < 1e-9, "last anchor {last:?}, want {want:?}"); + assert!((last.distance(center) - radius).abs() < 1e-9); + } + + /// Randomize moves each vertex out or in by at most 45% of its radius per unit of Randomize, + /// and does move some. + #[test] + fn randomize_keeps_vertex_radii_within_their_range() { + let distances = |p: &PathData| p.subpaths[0].anchors.iter().map(|a| a.p.distance(Point::ZERO)).collect::>(); + let within = |d: f64, base: f64| d >= base * 0.55 - 1e-9 && d <= base * 1.45 + 1e-9; + + let poly = distances(&polygon_configured(Point::ZERO, 50.0, 8, 0.0, 0.0, 1.0)); + assert_eq!(poly.len(), 8); + assert!(poly.iter().all(|&d| within(d, 50.0)), "polygon radii {poly:?}"); + assert!(poly.iter().any(|&d| (d - 50.0).abs() > 1e-6), "Randomize moved no vertex: {poly:?}"); + + let star = distances(&star_configured(Point::ZERO, 50.0, 25.0, 5, 0.0, 0.0, 1.0)); + assert_eq!(star.len(), 10); + let (tips, inner): (Vec<_>, Vec<_>) = star.iter().enumerate().partition(|(i, _)| i % 2 == 0); + assert!(tips.iter().all(|&(_, &d)| within(d, 50.0)), "star tips {tips:?}"); + assert!(inner.iter().all(|&(_, &d)| within(d, 25.0)), "star inner points {inner:?}"); + assert!(star.iter().zip([50.0, 25.0].iter().cycle()).any(|(d, base)| (d - base).abs() > 1e-6), "{star:?}"); + } + + /// Every face of a box drawn without perspective is a parallelogram with four distinct + /// corners, seen from each side of the box. + #[test] + fn a_parallel_box_draws_its_faces_as_parallelograms() { + let r = Rect::new(0.0, 0.0, 100.0, 80.0); + for (ax, ay) in [(30.0, 35.0), (-30.0, 35.0), (30.0, -35.0), (-30.0, -35.0), (150.0, 215.0)] { + let b = box3d(r, ax, ay, 0.0, true, true, true); + assert!(!b.subpaths.is_empty()); + for sp in &b.subpaths { + let p: Vec = sp.anchors.iter().map(|a| a.p).collect(); + assert_eq!(p.len(), 4); + let gap = (p[0].to_vec2() + p[2].to_vec2() - p[1].to_vec2() - p[3].to_vec2()).hypot(); + assert!(gap < 1e-6, "angles ({ax}, {ay}): face {p:?} is not a parallelogram"); + for i in 0..4 { + for j in i + 1..4 { + assert!(p[i].distance(p[j]) > 1e-6, "angles ({ax}, {ay}): face {p:?} repeats a corner"); + } + } + } + } + } + + /// An end angle a hair short of a full turn opens the whole shape for Arc instead of cutting it. + #[test] + fn a_span_within_rounding_of_a_full_turn_opens_the_whole_shape() { + let r = Rect::new(0.0, 0.0, 100.0, 60.0); + let mut opened = ellipse(r); + opened.subpaths[0].closed = false; + assert_eq!(apply_shape_arc(ellipse(r), r.center(), 0.0, -1e-10, EllipseMode::Arc), opened); + } } diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index a587c74fbb..d4b687f1f0 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -238,6 +238,8 @@ pub enum Expr { /// `...expression` in an array literal or an argument list, and as the last of an arrow /// function's parenthesized parameters while they are read. Spread(ExprId), + /// `await operand`, in an async function's body. + Await(ExprId), /// An optional chain (`a?.b.c`, `a?.[k]`, `f?.()`): its accesses and calls, the /// [`Expr::Optional`] steps among them included. It is `undefined` when one of those steps /// finds `undefined` or `null`, and the rest of the chain is skipped. @@ -502,6 +504,8 @@ pub struct Function { pub strict: bool, /// A generator function (`function*`, or `*name() {…}` in an object literal). pub generator: bool, + /// An async function (ECMAScript 2017): a call returns a promise, and its body may `await`. + pub is_async: 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`. diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs new file mode 100644 index 0000000000..909b191571 --- /dev/null +++ b/crates/js/src/async_tests.rs @@ -0,0 +1,350 @@ +//! Async functions and `await` in realms with [`Options::es2017`]. + +use super::*; + +fn realm() -> Realm { + Realm::with_options(Options { es2017: true, ..Options::default() }, Limits::default()) +} + +/// Runs `src`, which writes to the global `log`, and gives `log` after the jobs ran. +fn log(src: &str) -> String { + let mut r = realm(); + if let Err(e) = r.run(&format!("var log = [];\n{src}")) { + panic!("{src}\n{e:?}"); + } + match r.run("log.join(' ')") { + Ok(JsValue::String(s)) => s, + other => panic!("{src}: {other:?}"), + } +} + +fn syntax_error(r: &mut Realm, src: &str) { + match r.run(src) { + Err(e) if e.kind == RunErrorKind::Syntax => {} + other => panic!("{src}: {other:?}"), + } +} + +#[test] +fn awaits_resume_in_the_job_order_promise_reactions_have() { + let src = "async function f() { log.push('f1'); await null; log.push('f2'); await null; log.push('f3'); }\n\ + f();\n\ + Promise.resolve().then(function () { log.push('t1'); }).then(function () { log.push('t2'); });\n\ + log.push('sync');"; + assert_eq!(log(src), "f1 sync f2 t1 f3 t2"); +} + +#[test] +fn the_function_returns_a_promise_its_return_resolves_and_its_throw_rejects() { + let src = "async function ok(x) { return x + 1; }\n\ + async function bad() { throw new TypeError('no'); }\n\ + var p = ok(1); log.push(p instanceof Promise);\n\ + p.then(function (v) { log.push('ok ' + v); });\n\ + bad().then(null, function (e) { log.push(e instanceof TypeError); });"; + assert_eq!(log(src), "true ok 2 true"); +} + +#[test] +fn a_rejected_await_throws_where_it_stands_and_finally_runs_after_an_await() { + let src = "async function f() {\n\ + try { await Promise.reject('r'); log.push('not here'); }\n\ + catch (e) { log.push('caught ' + e); }\n\ + finally { await 1; log.push('finally'); }\n\ + return 'end';\n\ + }\n\ + f().then(function (v) { log.push(v); });"; + assert_eq!(log(src), "caught r finally end"); + let rethrow = "async function g() { try { await Promise.reject(new Error('x')); } finally { log.push('cleanup'); } }\n\ + g().catch(function (e) { log.push('rejected ' + e.message); });"; + assert_eq!(log(rethrow), "cleanup rejected x"); +} + +#[test] +fn arrows_expressions_and_methods_can_be_async() { + let src = "var a = async x => (await x) * 2;\n\ + var b = async (x, y) => { return await x + y; };\n\ + var c = async function named() { return typeof named; };\n\ + var o = { async m(v) { return this.k + await v; }, k: 'k' };\n\ + Promise.all([a(2), b(Promise.resolve(1), 2), c(), o.m('v')]).then(function (r) { log.push(r.join(',')); });"; + assert_eq!(log(src), "4,3,function,kv"); +} + +#[test] +fn a_comma_may_follow_an_arrow_functions_last_parameter_but_not_a_rest_parameter() { + let src = "var f = async (x,) => x; var g = async (x, ...xs) => xs.length; var h = (a, b,) => a + b;\n\ + var async = function () { return arguments.length; }; log.push(async(...[1, 2],));\n\ + Promise.all([f(1), g(1, 2, 3), h(1, 2), h.length]).then(function (r) { log.push(r.join(',')); });"; + assert_eq!(log(src), "2 1,2,3,2"); + let mut r = realm(); + for src in ["async (...xs,) => xs", "async (a, ...xs,) => xs", "(...xs,) => xs", "(a, ...xs,) => xs", "(a,);", "(a, b,);"] { + syntax_error(&mut r, src); + } +} + +#[test] +fn async_functions_are_not_constructors_and_have_no_prototype() { + let src = "async function f() {}\n\ + log.push(f.hasOwnProperty('prototype'));\n\ + try { new f(); } catch (e) { log.push(e instanceof TypeError); }\n\ + var AF = Object.getPrototypeOf(f).constructor;\n\ + log.push(AF !== Function, typeof AF, Object.getPrototypeOf(AF) === Function);\n\ + log.push(typeof this.AsyncFunction);\n\ + var g = AF('a', 'return await a;');\n\ + log.push(Object.getPrototypeOf(g) === Object.getPrototypeOf(f));\n\ + g(5).then(function (v) { log.push(v); });\n\ + log.push(String(async function h() { await 0; }));"; + assert_eq!(log(src), "false true true function true undefined true async function h() { await 0; } 5"); +} + +#[test] +fn reflect_construct_rejects_an_async_function_as_new_target() { + let src = "async function f() {}\n\ + var ran = false;\n\ + function C() { ran = true; }\n\ + try { Reflect.construct(C, [], f); } catch (e) { log.push(e instanceof TypeError); }\n\ + log.push(ran);\n\ + try { Reflect.construct(C, [], new Proxy(f, {})); } catch (e) { log.push(e instanceof TypeError); }"; + assert_eq!(log(src), "true false true"); +} + +#[test] +fn async_function_inherits_from_the_built_in_function_after_a_script_replaced_its_constructor() { + let mut r = Realm::new(); + assert_eq!(r.run("Function.prototype.constructor = {}; 0"), Ok(JsValue::Number(0.0))); + r.add_es2015(); + r.set_es2017(true); + let src = "var AF = Object.getPrototypeOf(async function () {}).constructor; Object.getPrototypeOf(AF) === Function && typeof AF.call"; + assert_eq!(r.run(src), Ok(JsValue::String("function".into()))); +} + +#[test] +fn with_e4x_async_before_a_double_colon_is_a_qualified_name() { + let options = Options { es2017: true, e4x: true, ..Options::default() }; + assert!(parse("async::b", &options).is_ok()); + let mut r = Realm::with_options(options, Limits::default()); + let src = "var async = new Namespace('u'); var x = 78; String(x.async::b)"; + assert_eq!(r.run(src), Ok(JsValue::String("7".into()))); +} + +#[test] +fn await_is_an_identifier_outside_async_functions() { + let src = "var await = 3; function f(await) { return await; } log.push(f(await));\n\ + var async = function (x) { return x; }; log.push(async(1));\n\ + async\nfunction g() {}\n\ + log.push(typeof g);"; + assert_eq!(log(src), "3 1 function"); + // A function in an async arrow function's parameters reads `await` as its own body does, + // and an async function declared in a script may be named `await`. + let nested = "var g = async (x = function () { return await; }) => x;\n\ + var h = async (x = async function () { await 0; }) => x;\n\ + async function await() { return 1; }\n\ + log.push(typeof g, typeof h, typeof await);"; + assert_eq!(log(nested), "function function function"); + // An arrow function in an async arrow function's parameters reads `await` as its own body does. + let arrow = "var await = 7; var f = async (cb = () => await) => cb(); f().then(function (v) { log.push(v); });"; + assert_eq!(log(arrow), "7"); + let mut r = realm(); + syntax_error(&mut r, "async function f() { var await; }"); + syntax_error(&mut r, "async function f(await) {}"); + syntax_error(&mut r, "async function f(x = await 1) {}"); + syntax_error(&mut r, "function f() { await 1; }"); + syntax_error(&mut r, "if (1) async function f() {}"); + syntax_error(&mut r, "async (x = await 1) => x"); + syntax_error(&mut r, "async\n(x) => x"); + syntax_error(&mut r, "async (a = (...await) => {}) => {}"); +} + +#[test] +fn a_suspended_function_survives_a_collection_and_an_unreachable_one_is_freed() { + let mut r = realm(); + r.run( + "var resume; var gate = new Promise(function (res) { resume = res; });\n\ + var out = [];\n\ + async function f() { var local = { n: 41 }; var v = await gate; out.push(local.n + v); }\n\ + f();", + ) + .unwrap(); + r.interp().collect_garbage(); + r.run("resume(1);").unwrap(); + assert_eq!(r.run("out.join()").unwrap(), JsValue::String("42".into())); + // A function waiting on a promise nothing can settle is collected with it. + r.interp().collect_garbage(); + let before = r.interp().heap.live_cells(); + r.run("(function () { async function w() { var big = []; for (var i = 0; i < 200; i++) big.push({ i: i }); await new Promise(function () {}); } w(); })();") + .unwrap(); + r.interp().collect_garbage(); + let after = r.interp().heap.live_cells(); + assert!(after < before + 50, "{before} {after}"); +} + +#[test] +fn a_run_that_ends_with_awaits_pending_ends_cleanly() { + let mut r = realm(); + let v = r.run("async function f() { await new Promise(function () {}); return 1; } f(); 'done'").unwrap(); + assert_eq!(v, JsValue::String("done".into())); + assert!(!r.is_running()); + assert_eq!(r.run("1 + 1").unwrap(), JsValue::Number(2.0)); +} + +#[test] +fn async_function_prototype_has_its_to_string_tag() { + let src = "var AFP = Object.getPrototypeOf(async function () {});\n\ + var d = Object.getOwnPropertyDescriptor(AFP, Symbol.toStringTag);\n\ + log.push(d.value, d.writable, d.enumerable, d.configurable, Object.prototype.toString.call(async function () {}));"; + assert_eq!(log(src), "AsyncFunction false false true [object AsyncFunction]"); +} + +#[test] +fn a_class_extends_async_function_and_its_instances_inherit_from_the_class() { + // CreateDynamicFunction takes the prototype from `new.target` (ECMA-262 2017 section + // 19.2.1.1.1). + let src = "var AF = Object.getPrototypeOf(async function () {}).constructor;\n\ + class X extends AF { tag() { return 'x'; } }\n\ + var f = new X('a', 'return a + 1');\n\ + log.push(Object.getPrototypeOf(f) === X.prototype, f instanceof AF, f.tag(), Object.prototype.toString.call(f));\n\ + f(1).then(function (v) { log.push(v); });"; + assert_eq!(log(src), "true true x [object AsyncFunction] 2"); + // The source is parsed before `new.target.prototype` is read. + let order = "var AF = Object.getPrototypeOf(async function () {}).constructor;\n\ + var NT = new Proxy(function () {}, { get: function (t, k) { if (k === 'prototype') log.push('read'); return t[k]; } });\n\ + try { Reflect.construct(AF, ['(('], NT); } catch (e) { log.push(e instanceof SyntaxError); }"; + assert_eq!(log(order), "true"); +} + +#[test] +fn an_await_stays_within_the_heap_limit() { + // The activation, its two reactions, the derived promise and the suspended frame's bytes all + // fit in the heap limit, or the run stops at the `await`. The frame waits with 40 operands on + // a promise that never settles, so its bytes stay charged after the run. A suspension that + // went past the limit would be stopped only later, at the end of the run, so the largest + // heap that still stops the run must stop it at the `await`. + let operands: String = (0..40).map(|i| format!("{i}, ")).collect(); + let setup = + format!("var gate = new Promise(function () {{}}); function g() {{ return 0; }} async function f() {{ return g({operands}await gate); }} 0"); + let setup = setup.as_str(); + let await_column = setup.find("await gate").map(|i| i + 1); + let run = "f(); 0"; + let mut measure = realm(); + assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0))); + let base = measure.collect_garbage(); + assert_eq!(measure.run(run), Ok(JsValue::Number(0.0))); + let need = measure.interp().settled_heap_bytes().saturating_sub(base) + 1024; + let mut last_stop = None; + let mut over = Vec::new(); + for spare in (0..=need).step_by(4) { + let mut r = realm(); + assert_eq!(r.run(setup), Ok(JsValue::Number(0.0))); + let heap_bytes = r.collect_garbage() + spare; + r.set_limits(Limits { heap_bytes, ..Limits::default() }); + let out = r.run(run); + match &out { + Ok(JsValue::Number(_)) => {} + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => last_stop = Some((spare, e.line, e.column)), + other => panic!("{spare}: {other:?}"), + } + let bytes = r.interp().settled_heap_bytes(); + if out.is_ok() && bytes > heap_bytes { + over.push((spare, bytes - heap_bytes)); + } + } + assert!(over.is_empty(), "runs that suspended past the limit (spare bytes, bytes over): {over:?}"); + let Some((spare, line, column)) = last_stop else { panic!("no limit stopped the run") }; + assert_eq!((line, usize::try_from(column).ok()), (1, await_column), "the run with {spare} spare bytes stopped away from the await"); +} + +/// The fewest frames with which `src` runs to its end. +fn fewest_frames(src: &str) -> usize { + for frames in 1..64 { + let mut r = Realm::with_options(Options { es2017: true, ..Options::default() }, Limits { frames, ..Limits::default() }); + if r.run(src).is_ok() { + return frames; + } + } + panic!("{src} did not run"); +} + +#[test] +fn a_then_getter_on_a_returned_value_runs_after_the_async_frame_ends() { + let setup = "function rec(n) { return n ? rec(n - 1) : 0; }\n\ + var o = { get then() { rec(5); return undefined; } };\n"; + let direct = fewest_frames(&format!("{setup}o.then; 0")); + let returned = fewest_frames(&format!("{setup}async function f() {{ return o; }} f(); 0")); + assert_eq!(returned, direct); + // Returning the function's own promise rejects it with a TypeError. + let own = "async function f() { await 0; return p; } var p = f(); p.catch(function (e) { log.push(e instanceof TypeError); });"; + assert_eq!(log(own), "true"); +} + +#[test] +fn an_async_arrow_head_reads_patterns_with_defaults_and_rejects_a_shorthand_await() { + let src = "var f = async ({a = 1}) => a; var g = async ({await: x}) => x; var h = async ([b = 2]) => b;\n\ + Promise.all([f({}), g({ await: 3 }), h([])]).then(function (r) { log.push(r.join(',')); });"; + assert_eq!(log(src), "1,3,2"); + let mut r = realm(); + syntax_error(&mut r, "var async = function () {}; async({a = 1});"); + syntax_error(&mut r, "async ({await}) => 0"); + syntax_error(&mut r, "async ({a = await}) => 0"); +} + +#[test] +fn each_resume_takes_fuel() { + let mut r = realm(); + r.set_limits(Limits { fuel: 20_000, ..Limits::default() }); + let e = r.run("async function f() { for (;;) await 0; } f();").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); +} + +#[test] +fn es5_and_extendscript_realms_do_not_read_async_functions() { + let mut es2015 = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default()); + syntax_error(&mut es2015, "async function f() {}"); + assert_eq!(es2015.run("var async = 1, await = 2; async + await").unwrap(), JsValue::Number(3.0)); + syntax_error(&mut Realm::with_options(Options::default(), Limits::default()), "async function f() {}"); + syntax_error(&mut Realm::new(), "var f = async () => 1;"); +} + +/// Starts `src` in a realm with `start`, calls `change` once the run has paused, runs it to its +/// end, and gives the run's value and the realm's options after it. +fn run_changing_language(src: &str, start: Options, change: impl FnOnce(&mut Realm)) -> (Result, Options) { + let mut realm = Realm::with_options(start, Limits::default()); + if let Err(e) = realm.start(src) { + return (Err(e), realm.interp().options.clone()); + } + match realm.advance(20) { + Ok(crate::Progress::Paused) => {} + other => panic!("{other:?}"), + } + change(&mut realm); + loop { + match realm.advance(1000) { + Ok(crate::Progress::Done(v)) => return (Ok(v), realm.interp().options.clone()), + Ok(_) => {} + Err(e) => return (Err(e), realm.interp().options.clone()), + } + } +} + +#[test] +fn language_changes_during_a_run_apply_after_it_in_the_order_they_were_made() { + let src = "for (var i = 0; i < 200; i++) {} eval('(async function () {})'); 1"; + let es2017 = Options { es2017: true, ..Options::default() }; + let es2015 = Options { es2015: true, ..Options::default() }; + let (v, o) = run_changing_language(src, es2017.clone(), |r| r.set_es2017(false)); + assert_eq!(v, Ok(JsValue::Number(1.0)), "the run keeps async functions for the code it evaluates"); + assert!(o.es2015 && !o.es2017, "{o:?}"); + let (v, o) = run_changing_language(src, es2017.clone(), |r| { + r.set_es2015(false); + r.set_es2017(true); + }); + assert_eq!(v, Ok(JsValue::Number(1.0))); + assert!(o.es2015 && o.es2017, "the later call wins: {o:?}"); + let (v, o) = run_changing_language(src, es2017, |r| { + r.set_es2017(true); + r.set_es2015(false); + }); + assert_eq!(v, Ok(JsValue::Number(1.0))); + assert!(!o.es2015 && !o.es2017, "turning es2015 off turns es2017 off: {o:?}"); + let (v, o) = run_changing_language("for (var i = 0; i < 200; i++) {} 1", es2015, |r| r.set_es2017(true)); + assert_eq!(v, Ok(JsValue::Number(1.0))); + assert!(o.es2015 && o.es2017, "{o:?}"); +} diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index d13e08bfdc..69af7138fa 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -14,6 +14,7 @@ //! run past [`crate::Limits`]. mod array; +mod async_function; pub(crate) mod binary; pub(crate) mod collections; pub(crate) mod extensions; @@ -250,6 +251,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { method(interp, object_proto, "propertyIsEnumerable", property_is_enumerable, 1)?; let function = native(interp, "Function", function_ctor, 1, NativeKind::Plain, true)?; + interp.intrinsics.function_ctor = function; constructor(interp, "Function", function, function_proto)?; let call = native(interp, "call", unreachable_native, 1, NativeKind::Call, false)?; data(interp, function_proto, "call", Value::Object(call), HIDDEN)?; @@ -670,13 +672,21 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b /// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as /// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function. fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - create_dynamic_function(interp, args, false) + create_dynamic_function(interp, args, false, false) } -/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function` and, with -/// `generator`, for `GeneratorFunction`, whose source is read as `(function* anonymous(…`. -pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool) -> JsResult { - let head: &str = if generator { "(function* anonymous(" } else { "(function anonymous(" }; +/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function`, with +/// `generator` for `GeneratorFunction`, whose source is read as `(function* anonymous(…`, and with +/// `is_async` for `AsyncFunction` (ECMA-262 2017 section 25.5.1.1), whose source is read as +/// `(async function anonymous(…`. An async function's source is read with +/// [`crate::Options::es2017`] whatever the realm reads scripts with, since only an async function +/// leads a script to `AsyncFunction`. +pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool, is_async: bool) -> JsResult { + let head: &str = match (generator, is_async) { + (true, _) => "(function* anonymous(", + (false, true) => "(async function anonymous(", + (false, false) => "(function anonymous(", + }; const MID: &str = "\n) {\n"; const TAIL: &str = "\n})"; let mut parts = Vec::with_capacity(args.len()); @@ -706,14 +716,15 @@ pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], gener interp.observe_code(&units); interp.source_units = interp.source_units.saturating_add(units.len()); let remaining = interp.options.max_source_units.saturating_sub(interp.source_units.saturating_sub(units.len())); - let options = crate::Options { strict: false, max_source_units: remaining, ..interp.options.clone() }; + let es2017 = interp.options.es2017 || is_async; + let options = crate::Options { strict: false, max_source_units: remaining, es2017, ..interp.options.clone() }; let program = match crate::parse_utf16(&units, &options) { Ok(p) => p, Err(e) => return Err(interp.throw(ErrorType::Syntax, &e.message)), }; let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() }); let code = match compile_constructed_function(&program, &source) { - Ok(Some(code)) if code.generator == generator => code, + Ok(Some(code)) if code.generator == generator && code.is_async == is_async => code, Ok(_) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), Err(CompileFail::Syntax(e)) => return Err(interp.throw(ErrorType::Syntax, &e.message)), Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)), diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index ac8dd4639c..9b45ba4e12 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -190,8 +190,10 @@ impl Indices { if self.lo >= self.hi { return Ok(None); } + // The object may have become one of a host class with an indexer meanwhile, whose + // elements are not properties: the rest of the range is then visited index by index. if self.sparse.as_ref().is_some_and(|s| s.epoch != interp.heap.index_epoch) { - self.sparse = self.gather(interp)?; + self.sparse = if interp.host_indexer(self.obj)?.is_some() { None } else { self.gather(interp)? }; } let k = match &mut self.sparse { None if self.ascending => self.lo, @@ -389,8 +391,15 @@ fn concat(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult let mut n = 0u64; for e in std::iter::once(Value::Object(o)).chain(args.iter().cloned()) { interp.use_fuel()?; - // A proxy whose target is an array is spread too (ECMA-262 2020 section 22.1.3.1.1). - let spread = if interp.is_array(&e)? { e.as_object() } else { None }; + // Code run without the ECMAScript 2015 option reads no such Symbol, even in a realm + // that has it from an earlier run. + let spreadable = if interp.options.es2015 { interp.well_known(|w| &w.is_concat_spreadable) } else { None }; + let override_spread = match (e.as_object(), spreadable) { + (Some(_), Some(sym)) => interp.get_value_sym(&e, &sym)?, + _ => Value::Undefined, + }; + let spread = if matches!(override_spread, Value::Undefined) { interp.is_array(&e)? } else { override_spread.truthy() }; + let spread = if spread { e.as_object() } else { None }; let Some(e) = spread else { if n >= 9_007_199_254_740_991 { return Err(interp.type_error("concat exceeds the maximum safe length")); diff --git a/crates/js/src/builtins/async_function.rs b/crates/js/src/builtins/async_function.rs new file mode 100644 index 0000000000..1baaeaad79 --- /dev/null +++ b/crates/js/src/builtins/async_function.rs @@ -0,0 +1,40 @@ +//! `AsyncFunction` and its prototype (ECMA-262 2017 section 25.5, +//! ), in realms with +//! [`crate::Options::es2015`]: the prototype of every async function, and the constructor a script +//! reaches through it. `AsyncFunction` is not a global. + +use super::{create_dynamic_function, data, native}; +use crate::heap::{CONFIGURABLE, Class, NativeKind, Object, Prop}; +use crate::interp::{Interp, JsResult}; +use crate::value::Value; + +/// Creates `AsyncFunction` and `AsyncFunction.prototype`, keeping the prototype for the async +/// functions the realm makes. +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let function_proto = interp.intrinsics.function_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto))); + interp.promises.async_function_proto = Some(proto); + let ctor = native(interp, "AsyncFunction", async_function_ctor, 1, NativeKind::Plain, true)?; + interp.promises.async_function_ctor = Some(ctor); + // The built-in `Function` is the constructor's prototype (section 25.5.2), even after a + // script has replaced `Function.prototype.constructor`. + let function_ctor = interp.intrinsics.function_ctor; + if let Some(o) = interp.heap.object_mut(ctor) { + o.proto = Some(function_ctor); + } + data(interp, ctor, "prototype", Value::Object(proto), 0)?; + // Configurable and not writable (section 25.5.3.1), unlike the `constructor` of the ordinary + // built-in prototypes. + data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE)?; + // `AsyncFunction.prototype[@@toStringTag]` is "AsyncFunction", configurable only (section + // 25.5.3.2). + if let Some(tag) = interp.well_known(|w| &w.to_string_tag) { + interp.define_sym(proto, tag, Prop::Data { value: Value::str("AsyncFunction"), flags: CONFIGURABLE })?; + } + Ok(()) +} + +/// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1). +fn async_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + create_dynamic_function(interp, args, false, true) +} diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 5a48799007..16c6a6a160 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -824,6 +824,23 @@ fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) } +fn typed_create(interp: &mut Interp, this: &Value, len: u64, name: &str) -> JsResult { + if !this.as_object().is_some_and(|o| interp.is_proxy(o)) { + let elem = ctor_elem(interp, this, name)?; + return new_typed(interp, elem, len); + } + #[allow(clippy::cast_precision_loss)] + let result = interp.construct_value(this, &[Value::Number(len as f64)], this)?; + interp.rooted(std::slice::from_ref(&result), |interp| { + let Some(o) = result.as_object() else { return Err(interp.type_error("the constructor did not return a typed array")) }; + let Some(view) = view_of(interp, o) else { return Err(interp.type_error("the constructor did not return a typed array")) }; + if (view.length as u64) < len { + return Err(interp.type_error(&format!("TypedArray.{name} constructor returned a typed array that is too short"))); + } + Ok(o) + }) +} + /// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { if !interp.is_constructor(&this) { @@ -836,16 +853,15 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe } let this_arg = arg(args, 2); 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")?; - new_typed(interp, elem, len) - }) + typed_array_from(interp, &arg(args, 0), map, |interp, len| typed_create(interp, &this, len, "from")) } /// `%TypedArray%.of(...items)` (section 22.2.2.2). fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let elem = ctor_elem(interp, &this, "of")?; - let ta = new_typed(interp, elem, args.len() as u64)?; + if !interp.is_constructor(&this) { + return Err(interp.type_error("TypedArray.of must be called on a typed array constructor")); + } + let ta = typed_create(interp, &this, args.len() as u64, "of")?; let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; interp.rooted(&[Value::Object(ta)], |interp| { for (i, v) in args.iter().enumerate() { diff --git a/crates/js/src/builtins/generator.rs b/crates/js/src/builtins/generator.rs index c8e46e09d6..506cf23182 100644 --- a/crates/js/src/builtins/generator.rs +++ b/crates/js/src/builtins/generator.rs @@ -47,5 +47,5 @@ pub(super) fn install(interp: &mut Interp, function: ObjId) -> JsResult<()> { /// `GeneratorFunction(p1, …, body)` and `new GeneratorFunction(…)` (section 25.2.1.1). fn generator_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - super::create_dynamic_function(interp, args, true) + super::create_dynamic_function(interp, args, true, false) } diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index a6d8babc9e..e5027df1c6 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -414,6 +414,7 @@ fn revive(interp: &mut Interp, v: Value, reviver: &Value) -> JsResult { struct Settings { replacer: Option, properties: Option>, + _held_properties: Option, gap: Vec, } @@ -474,12 +475,14 @@ fn stringify_rooted(interp: &mut Interp, args: &[Value]) -> JsResult { /// Reads the replacer and the space argument (section 15.12.3, steps 4 to 8). fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult { - let mut s = Settings { replacer: None, properties: None, gap: Vec::new() }; + let mut s = Settings { replacer: None, properties: None, _held_properties: None, gap: Vec::new() }; if let Value::Object(r) = replacer { if interp.is_callable(replacer) { s.replacer = Some(replacer.clone()); } else if interp.is_array(replacer)? { - s.properties = Some(property_list(interp, *r)?); + let (keys, held) = property_list(interp, *r)?; + s.properties = Some(keys); + s._held_properties = Some(held); } } let space = unwrap_primitive(interp, space, false)?.unwrap_or_else(|| space.clone()); @@ -495,12 +498,13 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult JsResult> { +/// Each name kept is charged to the heap for as long as the returned holder lives. +fn property_list(interp: &mut Interp, r: ObjId) -> JsResult<(Vec, crate::interp::HeldBytes)> { let len = super::collections::length_of(interp, r)?; if len > interp.fuel { return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel)); } - interp.reserve_heap(usize::try_from(len).unwrap_or(usize::MAX).saturating_mul(ELEMENT_BYTES))?; + let mut held = crate::interp::HeldBytes::new(interp); let mut list: Vec = Vec::new(); let mut seen = HashSet::new(); for i in 0..len { @@ -529,10 +533,11 @@ fn property_list(interp: &mut Interp, r: ObjId) -> JsResult> { } // The list lives until the call returns, so its names are rooted. interp.temp_roots.push(Value::String(s)); + held.add(interp, ELEMENT_BYTES)?; list.push(k); } } - Ok(list) + Ok((list, held)) } /// Steps 1 to 4 and 10 of Str (section 15.12.3): reads `holder[key]`, applies `toJSON` and the diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 7f684fbbf5..eb1e0dbc9e 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -145,6 +145,8 @@ enum Then { Settle(ObjId, Option), /// An exception rejects through this resolving record. Reject(ObjId), + /// An async function goes on after `await`; its own promise takes its result. + Resume, /// The call was a `finally` callback that a reaction job runs in place of the Then Finally or /// Catch Finally function: `derived` is settled as that function's result settles it. Finally { derived: ObjId, value: Value, throws: bool }, @@ -162,9 +164,11 @@ enum Kind { CatchFinally, ValueThunk, Thrower, + AwaitFulfilled, + AwaitRejected, } -const KINDS: [(Kind, NativeFn); 9] = [ +const KINDS: [(Kind, NativeFn); 11] = [ (Kind::Resolve, resolve_function), (Kind::Reject, reject_function), (Kind::AllElement, all_element), @@ -174,6 +178,8 @@ const KINDS: [(Kind, NativeFn); 9] = [ (Kind::CatchFinally, catch_finally), (Kind::ValueThunk, value_thunk), (Kind::Thrower, thrower), + (Kind::AwaitFulfilled, await_continuation), + (Kind::AwaitRejected, await_continuation), ]; /// `Promise`'s objects and the run's job queue. @@ -192,11 +198,17 @@ pub(crate) struct Promises { rejected: Vec, /// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower). pub(crate) max_jobs: usize, + /// `AsyncFunction.prototype` (ECMA-262 2017 section 25.5.3), the prototype of async functions. + pub(crate) async_function_proto: Option, + /// `AsyncFunction` (section 25.5.1), which is not a global. + pub(crate) async_function_ctor: Option, } impl Default for Promises { fn default() -> Self { Self { + async_function_proto: None, + async_function_ctor: None, proto: None, ctor: None, natives: Vec::new(), @@ -214,6 +226,7 @@ impl Promises { /// Adds what the queue and the promise objects hold to the collector's roots. pub(crate) fn add_roots<'a>(&'a self, roots: &mut Roots<'a>) { roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); + roots.objects.extend(self.async_function_proto.iter().chain(&self.async_function_ctor)); roots.values.extend(self.completion.iter()); match &self.running { Some(Then::Settle(o, site)) => { @@ -225,7 +238,7 @@ impl Promises { roots.objects.push(*derived); roots.values.push(value); } - None => {} + Some(Then::Resume) | None => {} } for job in &self.queue { match job { @@ -282,7 +295,7 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { let n = native(interp, "", f, 1, NativeKind::Plain, false)?; interp.promises.natives.push(n); } - Ok(()) + super::async_function::install(interp) } /// Creates `Promise` in a realm made without [`crate::Options::es2015`], replacing a global @@ -575,6 +588,140 @@ fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult }) } +// ---- async functions ---- + +/// The built-in a suspended async function's reactions are bound to. The job queue resumes the +/// function instead of calling it, and scripts cannot reach it. +fn await_continuation(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(Abrupt::Internal("an await continuation was called".into())) +} + +impl Interp { + /// Settles the promise of an async function whose frame ends: its return value resolves it, + /// and the exception that leaves it rejects it. + pub(crate) fn settle_async(&mut self, p: ObjId, r: Result) -> JsResult<()> { + match r { + Ok(v) => resolve_promise(self, p, v), + Err(e) => { + let site = caught(self); + reject_promise(self, p, e, site) + } + } + } + + /// Resolves the promise of an async function whose frame has returned `v` and is already off + /// the frames. Returning the promise itself rejects it with a `TypeError` at `site`, the + /// return. + pub(crate) fn resolve_async_return(&mut self, p: ObjId, v: Value, site: Option) -> JsResult<()> { + if matches!(v, Value::Object(o) if o == p) { + return scoped(self, |interp| { + root(interp, &Value::Object(p)); + let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself"); + root(interp, &e); + reject_promise(interp, p, e, site) + }); + } + resolve_promise(self, p, v) + } + + /// A new pending promise for the async function call whose frame is on top. + pub(crate) fn new_async_promise(&mut self) -> JsResult { + new_promise(self) + } + + /// `await v` in the async function the top frame runs (Await, ECMA-262 2017 section 6.2.3.1, + /// with PromiseResolve as later editions have it): `v` becomes a built-in promise, the frame + /// is suspended until it settles, and the function's call gives its promise, `Some` when the + /// frame was the boundary frame. Throws at the `await` when reading `v`'s `constructor` throws. + pub(crate) fn await_value(&mut self, v: Value) -> JsResult> { + if self.async_promise().is_none() { + return Err(Abrupt::Internal("await outside an async function".into())); + } + let ctor = self.promises.ctor.map_or(Value::Undefined, Value::Object); + scoped(self, |interp| { + let p = promise_resolve(interp, &ctor, v)?; + root(interp, &p); + let Value::Object(p) = p else { return Err(Abrupt::Internal("PromiseResolve gave a value that is not a promise".into())) }; + let bytes = interp.suspend_bytes(); + interp.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?; + let act = interp.heap.alloc_object(Object::new(Class::Activation(None), None)); + root(interp, &Value::Object(act)); + let on_fulfilled = record_function(interp, Kind::AwaitFulfilled, act, 1)?; + root(interp, &on_fulfilled); + let on_rejected = record_function(interp, Kind::AwaitRejected, act, 1)?; + root(interp, &on_rejected); + // The reactions settle no promise of their own; this one stays pending and unseen. + let derived = new_promise(interp)?; + root(interp, &Value::Object(derived)); + promise_data(interp, derived)?.handled = true; + // The allocations above used up the room checked for at the start, so the reaction or + // job and the frame's bytes are checked again, with the frame still on top, before the + // awaited promise gets its reaction. + let then_bytes = if promise_data(interp, p)?.state == State::Pending { REACTION_BYTES } else { JOB_BYTES }; + interp.reserve_heap(then_bytes.saturating_add(bytes))?; + perform_then(interp, p, on_fulfilled, on_rejected, derived)?; + let (a, boundary) = interp.suspend_frame()?; + let promise = a.promise; + let held = a.bytes(); + if let Some(o) = interp.heap.object_mut(act) { + o.class = Class::Activation(Some(Box::new(a))); + } + interp.heap.bytes = interp.heap.bytes.saturating_add(held); + if boundary { + return Ok(Some(Value::Object(promise))); + } + interp.push(Value::Object(promise))?; + Ok(None) + }) + } + + /// The activation `handler` resumes when it is a suspended async function's reaction, and + /// whether it is the rejection's. + fn await_activation(&self, handler: &Value) -> Option<(ObjId, bool)> { + let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| self.heap.object(o)).map(|o| &o.class) else { + return None; + }; + let reject = if self.promises.natives.get(Kind::AwaitFulfilled as usize) == Some(target) { + false + } else if self.promises.natives.get(Kind::AwaitRejected as usize) == Some(target) { + true + } else { + return None; + }; + match args.first() { + Some(Value::Object(act)) => Some((*act, reject)), + _ => None, + } + } + + /// Resumes the async function `handler` belongs to with the settled value: its frame goes back + /// on top as a boundary frame the caller runs, and a rejection is thrown at its `await`. A job + /// that finds the frame already resumed does nothing. + fn resume_async(&mut self, handler: &Value, argument: Value, reject: bool, site: Option) -> JsResult<()> { + let Some((act, _)) = self.await_activation(handler) else { return Err(Abrupt::Internal("not an await reaction".into())) }; + let taken = match self.heap.object_mut(act).map(|o| &mut o.class) { + Some(Class::Activation(slot)) => slot.take(), + _ => return Err(Abrupt::Internal("an await reaction lost its activation".into())), + }; + let Some(a) = taken else { return Ok(()) }; + self.heap.bytes = self.heap.bytes.saturating_sub(a.bytes()); + self.restore_frame(*a)?; + self.promises.running = Some(Then::Resume); + if !reject { + return self.push(argument); + } + if site.is_some() { + self.throw_site = site; + } + match self.unwind_or_abort(argument) { + Ok(Some(v)) => self.finish_job(Ok(v)), + Ok(None) => Ok(()), + Err(Abrupt::Throw(e)) => self.finish_job(Err(e)), + Err(e) => Err(e), + } + } +} + // ---- the job queue ---- impl Interp { @@ -583,6 +730,11 @@ impl Interp { !self.frames.is_empty() || self.promises.draining } + /// Whether promise jobs wait to run. + pub(crate) fn jobs_waiting(&self) -> bool { + !self.promises.queue.is_empty() + } + /// Runs the queued jobs, and the jobs they queue, until the queue is empty, after the script's /// code ended with `completion`, which this gives back. pub(crate) fn drain_jobs(&mut self, completion: Value) -> JsResult { @@ -660,6 +812,10 @@ impl Interp { self.use_fuel()?; scoped(self, |interp| { let (f, this, args, then) = match job { + Job::Reaction { handler, argument, reject, site, .. } if interp.await_activation(&handler).is_some() => { + root(interp, &argument); + return interp.resume_async(&handler, argument, reject, site); + } Job::Reaction { handler, argument, reject, derived, site } => { if !interp.is_callable(&handler) { return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) }; @@ -700,7 +856,7 @@ impl Interp { match (then, r) { (Then::Settle(d, _), Ok(v)) => resolve_promise(self, d, v), (Then::Settle(d, _), Err(e)) => reject_promise(self, d, e, site), - (Then::Reject(_), Ok(_)) => Ok(()), + (Then::Reject(_), Ok(_)) | (Then::Resume, _) => Ok(()), (Then::Reject(rec), Err(e)) => scoped(self, |interp| { root(interp, &Value::Object(rec)); reject_through(interp, rec, e, site) @@ -736,9 +892,10 @@ impl Interp { } /// The promises the run rejected that still have no handler, the first [`MAX_REPORTED`] of - /// them described, and how many there are; the run's notes are cleared. - pub(crate) fn take_unhandled(&mut self) -> (Vec, usize) { - let rejected = std::mem::take(&mut self.promises.rejected); + /// them described, and how many there are. The run's notes stay until the next run starts, so a + /// later call leaves out a promise that has a handler since. + pub(crate) fn unhandled(&mut self) -> (Vec, usize) { + let rejected = self.promises.rejected.clone(); let mut out = Vec::new(); let mut attribution = Vec::new(); let mut count = 0; @@ -935,8 +1092,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let mut v = v.clone(); loop { @@ -945,7 +1102,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { _ => return Ok(false), }; match func { - Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator), + Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator && !code.is_async), 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, .. } => { diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index 0bbccebb1c..e020e6335b 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -18,6 +18,8 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { ("hasInstance", well_known.has_instance.clone()), ("toPrimitive", well_known.to_primitive.clone()), ("toStringTag", well_known.to_string_tag.clone()), + ("unscopables", well_known.unscopables.clone()), + ("isConcatSpreadable", well_known.is_concat_spreadable.clone()), ]; let (to_string_tag, to_primitive, has_instance) = (well_known.to_string_tag.clone(), well_known.to_primitive.clone(), well_known.has_instance.clone()); @@ -171,7 +173,7 @@ fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bo interp.rooted(&[Value::Object(o)], |interp| { // A proxy's list stays counted against the heap until the array holds its Symbols. let (syms, _held) = if interp.is_proxy(o) { - let keys = interp.proxy_own_keys(o)?; + let keys = interp.proxy_own_keys(o, false)?; (keys.syms, keys.held) } else { let syms = interp.own_symbols(o)?; diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index cda3d45ece..6512b2e91c 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -334,6 +334,9 @@ pub(crate) enum Op { DelegateResult(u32), /// `mode value` → `value`; for `return`, jumps with it. DelegateDone(u32), + /// `value` → its awaited value: suspends the running async function until the value settles, + /// and goes on with its fulfillment value or throws its rejection reason here. + Await, } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -406,6 +409,11 @@ pub(crate) struct Code { pub(crate) vars: Vec, /// Function declarations to instantiate on entry: their names and indices in `functions`. pub(crate) fun_decls: Vec<(Key, u32)>, + /// In script and eval code, the variables of block functions (Annex B.3.3.2 and B.3.3.3) that + /// the code does not declare otherwise: each is declared, and its function assigned to it, only + /// when no `let`, `const` or block function between the code and its variable environment has + /// the name and the variable can be declared. + pub(crate) annex_vars: Vec, /// The body refers to `arguments` or calls `eval`. pub(crate) uses_arguments: bool, pub(crate) source: Rc, @@ -453,6 +461,8 @@ pub(crate) struct Code { /// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]), /// and it is not a constructor. pub(crate) generator: bool, + /// The code is an async function's: a call returns a promise, and it may run [`Op::Await`]. + pub(crate) is_async: bool, /// What `super` and `new.target` may do in eval code a direct `eval` in this code runs: the /// rules of the function's body, of the code around an arrow function, or those eval code was /// read with (ECMA-262 2015 section 18.2.1.1). @@ -596,7 +606,7 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { 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::ToStr | Op::Await | 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")?), Op::PatternGet(n) => e(n.checked_add(2).ok_or("operand too large")?, n.checked_add(3).ok_or("operand too large")?), diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 93f8afb3e6..87c1c744c8 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -155,7 +155,7 @@ impl Interp { return p.constructor; } match self.func_of(&v) { - Some(Func::Closure { code, .. }) => return !(code.arrow || code.method || code.generator), + Some(Func::Closure { code, .. }) => return !(code.arrow || code.method || code.generator || code.is_async), 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), @@ -172,7 +172,15 @@ impl Interp { 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)) + || i.error_protos.contains(&p) + || self.dynamic_function_proto(p)) + } + + /// Is `p` the prototype of the functions that `GeneratorFunction` or `AsyncFunction` makes? + /// Both constructors take a subclass's prototype from `new.target` (ECMA-262 2017 sections + /// 25.2.1.1 and 25.5.1.1, through CreateDynamicFunction in section 19.2.1.1.1). + fn dynamic_function_proto(&self, p: ObjId) -> bool { + self.symbols.objects.is_some_and(|o| p == o.generator_function_proto) || self.promises.async_function_proto == Some(p) } /// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14). @@ -320,6 +328,7 @@ impl Interp { 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.is_async => Err(self.type_error("an async 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); @@ -366,13 +375,13 @@ impl Interp { return Err(self.type_error("the Promise executor is not a function")); } // `Number`, `String` and `Date` convert arguments before reading `prototype` - // (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function` and `GeneratorFunction` - // convert and parse source first (sections 19.2.1.1.1 and 25.2.1.1). + // (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function`, `GeneratorFunction` and + // `AsyncFunction` convert and parse source first (sections 19.2.1.1.1, 25.2.1.1 + // and 25.5.1.1). let converts_first = { let i = &self.intrinsics; intrinsic.is_some_and(|p| { - [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p) - || self.symbols.objects.is_some_and(|o| p == o.generator_function_proto) + [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p) || self.dynamic_function_proto(p) }) }; let fallback = intrinsic.unwrap_or(self.intrinsics.object_proto); @@ -413,6 +422,11 @@ impl Interp { let v = self.call_data(&host, &name, &Value::Undefined, &args, &read); self.constructing = was; let v = v?; + // `new` gives an object ([[Construct]]): a constructor that gives another value + // is a TypeError. + if !matches!(v, Value::Object(_)) { + return Err(self.type_error(&format!("the constructor {name} did not give an object"))); + } 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"))? diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 62436ae9ab..f13677ca52 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -124,6 +124,9 @@ struct FnCompiler<'a> { struct Hoisted { vars: Vec, fun_decls: Vec<(Key, u32)>, + /// The names of block functions (Annex B.3.3) that are neither a `var` nor a function at the + /// top of the body. + annex_vars: Vec, } fn key_of(name: &str) -> Key { @@ -273,7 +276,8 @@ impl<'a> FnCompiler<'a> { /// hoisted; one in a block is instantiated when the block is entered, and outside strict mode /// code its name is also a variable (Annex B.3.3) unless that clashes with a parameter or with /// a `let` or a `const` of the body or of a block or loop around the declaration, or with a - /// function of a block around the one that holds it. + /// function of a block around the one that holds it. Such a name that the body does not also + /// declare with `var` or as a function at its top goes in [`Hoisted::annex_vars`]. fn hoist(&mut self, body: &[StmtId], params: &[Key]) -> CResult { let mut out = Hoisted::default(); let mut seen = HashSet::new(); @@ -290,6 +294,7 @@ impl<'a> FnCompiler<'a> { } }; let mut annex: Vec<(Key, usize, StmtId)> = Vec::new(); + let mut annex_seen = HashSet::new(); while let Some((id, nested, scope)) = work.pop() { let Some(stmt) = self.ast.stmt(id) else { return internal("statement out of range") }; let inner = self.es2015; @@ -301,13 +306,15 @@ impl<'a> FnCompiler<'a> { Stmt::Var(decls) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name))), Stmt::Lexical(..) | Stmt::Class(_) => {} Stmt::FunctionDecl(fid) => { - let Some((name, generator)) = self.ast.function(*fid).and_then(|f| Some((f.name.as_ref()?, f.generator))) else { + let Some(f) = self.ast.function(*fid) else { return internal("function out of range") }; + let Some(name) = f.name.as_ref() else { return internal("function declaration without a name"); }; let k = key_of(&name.name); if self.es2015 && nested { - // Annex B.3.3 gives plain function declarations only a var binding too. - if !self.strict && !generator { + // Annex B.3.3 gives plain function declarations a variable, not generator + // or async ones. + if !self.strict && !f.generator && !f.is_async { annex.push((k, scope, id)); } } else { @@ -415,7 +422,9 @@ impl<'a> FnCompiler<'a> { } if !clash { self.annex.insert(id); - add_var(&mut out, k); + if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) { + out.annex_vars.push(k); + } } } Ok(out) @@ -1396,6 +1405,11 @@ impl<'a> FnCompiler<'a> { self.uses_new_target = true; self.emit(Op::NewTarget); } + Expr::Await(arg) => { + self.expr(*arg)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::Await); + } Expr::Update { op, prefix, target } => self.update(*op, *prefix, *target)?, Expr::Unary { .. } => self.unary(id)?, Expr::Binary { .. } | Expr::Logical { .. } => self.binary_chain(id)?, @@ -2400,6 +2414,7 @@ impl<'a> FnCompiler<'a> { params: meta.params, vars: hoisted.vars, fun_decls: hoisted.fun_decls, + annex_vars: hoisted.annex_vars, uses_arguments: self.uses_arguments, source: self.source.clone(), span: meta.span, @@ -2419,6 +2434,7 @@ impl<'a> FnCompiler<'a> { own_name: meta.own_name, method: meta.method, generator: self.generator, + is_async: meta.is_async, supers: self.supers, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; @@ -2443,6 +2459,7 @@ struct Meta { pattern_names: Vec, own_name: Option, method: bool, + is_async: bool, } fn len_u32(n: usize) -> u32 { @@ -2478,7 +2495,10 @@ pub(crate) fn compile_function( let rest = f.rest.as_ref().map(|r| param_key(&c, f.params.len(), r)); let pattern_names: Vec = f.params.iter().chain(&f.rest).filter(|p| matches!(p, Binding::Pattern(_))).flat_map(|p| c.bound_keys(p)).collect(); let all_params: Vec = f.params.iter().chain(&f.rest).flat_map(|p| c.bound_keys(p)).collect(); - let hoisted = c.hoist(&f.body, &all_params)?; + let mut hoisted = c.hoist(&f.body, &all_params)?; + // A function's block functions always have their variable (Annex B.3.3.1). + let annex = std::mem::take(&mut hoisted.annex_vars); + hoisted.vars.extend(annex); let top_scope = c.list_scope(&f.body, false)?; // Default values are expressions (ContainsExpression, ECMA-262 2015 section 14.1.5), and a // destructured parameter is bound by code of its own: a rest parameter alone leaves the @@ -2551,6 +2571,7 @@ pub(crate) fn compile_function( }), method: (f.home && !f.is_class_constructor()) || (es2015 && matches!(f.kind, FunctionKind::Method | FunctionKind::Getter | FunctionKind::Setter)), + is_async: f.is_async, }; c.finish(hoisted, meta) } diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 397521b8a3..ec43bfe327 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -181,6 +181,39 @@ fn a_block_function_inside_another_of_its_name_leaves_the_variable_alone() { truth("function g() { { function f() { return 1; } { function f() { return 2; } } } return f(); } g() === 1"); } +#[test] +fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() { + // A block function of a script or of eval code gets no variable when a `let`, a `const` or a + // block function out to the variable environment has its name, or when the global object + // cannot take it (Annex B.3.3.2 and B.3.3.3); its block still has it, and a `var` of the name + // is still a SyntaxError. + let mut realm = es(); + assert_eq!(realm.run("let f = 1; 0"), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run("var inner; { function f() { return 2; } inner = f(); } inner + f"), Ok(JsValue::Number(3.0))); + assert!(is_thrown(&realm.run("{ function f() {} } var f;"), "SyntaxError")); + assert_eq!(realm.run("(0, eval)('{ function f() { return 4; } }'); f"), Ok(JsValue::Number(1.0))); + truth("function t() { let h = 1; { eval('{ function h() { return 2; } }'); } return h; } t() === 1"); + truth("function t() { let h = 1; eval('{ function h() {} }'); return h; } t() === 1"); + // A `catch` parameter does not stop the variable (Annex B.3.5). + truth("try { throw 1; } catch (c) { eval('{ function c() { return 5; } }'); } c() === 5"); + let mut realm = es(); + assert_eq!(realm.run("var out; Object.preventExtensions(this); 0"), Ok(JsValue::Number(0.0))); + let kept = realm.run("{ function n() { return 6; } out = n(); } out + typeof n"); + assert_eq!(kept, Ok(JsValue::String("6undefined".into()))); + assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into()))); +} + +#[test] +fn a_block_function_in_eval_in_a_default_parameter_leaves_a_parameter_of_its_name_alone() { + // A parameter between the eval code and its variable environment has the name, so the block + // function gets no variable (Annex B.3.2.3) and the parameter keeps its value. + truth("function f(a = eval('{ function a() {} }'), b = a) { return typeof b; } f() === 'undefined'"); + truth("function f(a = 1, b = eval('{ function a() {} }'), c = a) { return c + typeof a; } f() === '1number'"); + truth("function f(a = 2, b = eval('{ function a() {} }')) { return a; } f() === 2"); + // A name that no parameter has still gets the variable. + truth("function f(x = eval('{ function a() { return 3; } }'), b = a) { return b(); } f() === 3"); +} + #[test] fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() { truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0"); @@ -333,6 +366,17 @@ fn a_global_var_makes_its_own_property_over_an_inherited_one() { assert_eq!(realm.run("var inherited; !this.hasOwnProperty('inherited') && inherited === 1"), Ok(JsValue::Bool(true))); } +#[test] +fn a_var_an_inherited_property_declared_does_not_stop_a_later_let() { + // Without the option, `var x` uses the inherited `x` and makes no own property, so a later + // run with the option may declare `x` with `let`. + let mut realm = Realm::new(); + assert_eq!(realm.run("Object.prototype.x = 1; 0"), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run("var x; delete this.x"), Ok(JsValue::Bool(true))); + realm.set_es2015(true); + assert_eq!(realm.run("let x = 2; x"), Ok(JsValue::Number(2.0))); +} + #[test] fn a_global_function_that_cannot_be_declared_declares_nothing() { let mut realm = es(); @@ -454,6 +498,38 @@ fn a_global_var_that_cannot_be_declared_declares_nothing() { assert_eq!(realm.run("let x = 2; var kept; x + kept"), Ok(JsValue::Number(3.0))); } +#[test] +fn a_script_stopped_by_the_frame_limit_declares_no_let() { + let mut realm = Realm::with_options(es_options(), Limits { frames: 0, ..Limits::default() }); + let stopped = realm.run("let early = 1; const fixed = 2;"); + assert!(matches!(&stopped, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Frames)), "{stopped:?}"); + realm.set_limits(Limits::default()); + assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0))); +} + +#[test] +fn a_script_stopped_by_the_heap_limit_declares_no_let() { + // The `let` and `const` names of a script go in before its functions are made; a heap too + // small for both stops the script before any name is declared. + let lets: String = (0..200).map(|i| format!("let a_long_lexical_name_{i} = {i}; ")).collect(); + let decls: String = (0..40).map(|i| format!("function f{i}() {{ return {i}; }} ")).collect(); + let src = format!("let early = 1; const fixed = 2; {lets}{decls}"); + let mut stopped = 0; + for spare in (40_000..200_000).step_by(97) { + let mut realm = es(); + let live = realm.collect_garbage(); + realm.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() }); + match realm.run(&src) { + Ok(_) => continue, + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => stopped += 1, + Err(e) => panic!("{spare}: {e:?}"), + } + realm.set_limits(Limits::default()); + assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0)), "{spare}"); + } + assert!(stopped > 0); +} + #[test] fn eval_code_keeps_its_let_and_const_to_itself() { truth("eval('let e = 1; e') === 1 && typeof e === 'undefined'"); @@ -866,6 +942,37 @@ fn spread_stops_at_the_heap_limit_before_the_next_step_runs() { } } +#[test] +fn a_template_object_stays_within_the_heap_limit() { + // The template object's two arrays, the index name of each string and the `raw` property are + // reserved before they are made, so the heap stays within each limit tried. + let setup = "function t(s) { return s.length; } 0"; + let run = format!("t`{}`", (0..10).map(|i| format!("p{i}${{{i}}}")).collect::()); + let mut measure = Realm::with_options(es_options(), Limits::default()); + assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0))); + measure.interp().collect_garbage(); + let base = measure.interp().heap.bytes; + assert_eq!(measure.run(&run), Ok(JsValue::Number(11.0))); + let need = measure.interp().settled_heap_bytes() - base; + let mut stopped = 0; + for heap_bytes in (base..=base + need).step_by(4) { + let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() }); + if realm.run(setup).is_err() { + continue; + } + realm.interp().collect_garbage(); + let r = realm.run(&run); + stopped += usize::from(r.is_err()); + assert!( + matches!(&r, Ok(JsValue::Number(_))) || matches!(&r, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)), + "{heap_bytes}: {r:?}" + ); + let bytes = realm.interp().settled_heap_bytes(); + assert!(bytes <= heap_bytes, "{bytes} > {heap_bytes}"); + } + assert!(stopped > 0, "no limit stopped the run"); +} + #[test] fn spreading_other_values_is_a_type_error() { throws("[...1];", "TypeError"); @@ -972,6 +1079,47 @@ fn spreading_a_rope_counts_its_flattened_length_first() { assert_eq!(made, Ok(JsValue::Number(0.0)), "the rope is made within the fuel"); } +#[test] +fn spreading_a_string_counts_the_string_it_makes_for_each_character() { + // Each of the 16,384 elements is a property and a one-character string of its own. The + // smaller heap has room for the properties alone but not for the strings as well, so the + // spread stops with the heap limit. The larger heap holds the array, its keys and the + // strings. The spread steps the string's iterator, so the fuel is set well above what it + // takes. + const N: usize = 16_384; + let property = crate::heap::PROP_BYTES; + let string = crate::heap::string_bytes(1); + let setup = "var s = 'x'; for (var i = 0; i < 14; i++) s = s + s; s[0]; 0"; + let cases = [(property + string / 2, N * 1000, Err(LimitKind::Heap)), (2 * (property + string) + 8, N * 1000, Ok(N as f64))]; + for (per_element, fuel, expected) in cases { + let mut r = es(); + assert_eq!(r.run(setup), Ok(JsValue::Number(0.0))); + r.interp().collect_garbage(); + let heap_bytes = r.interp().heap.bytes + N * per_element; + r.set_limits(Limits { heap_bytes, fuel: fuel as u64, ..Limits::default() }); + match (r.run("var a = [...s]; a.length"), expected) { + (Ok(JsValue::Number(n)), Ok(m)) if n == m => {} + (Err(e), Err(kind)) if e.kind == RunErrorKind::Limit(kind) => {} + (result, expected) => panic!("{per_element} bytes for each element: {result:?}, expected {expected:?}"), + } + } +} + +#[test] +fn the_strings_a_string_spread_makes_stay_counted_while_the_array_holds_them() { + const N: u32 = 4096; + let mut r = es(); + assert_eq!(r.run("var s = 'x'; for (var i = 0; i < 12; i++) s = s + s; s[0]; 0"), Ok(JsValue::Number(0.0))); + r.interp().collect_garbage(); + let before = r.interp().heap.bytes; + assert_eq!(r.run("var a = [...s]; a.length"), Ok(JsValue::Number(f64::from(N)))); + // Takes the bytes the spread held while it ran off the estimate. + r.interp().reserve_heap(0).unwrap(); + let element = |i: u32| crate::heap::PROP_BYTES + crate::heap::string_bytes(i.to_string().len()) + crate::heap::string_bytes(1); + let least = before + (0..N).map(element).sum::(); + assert!(r.interp().heap.bytes >= least, "{} < {least}", r.interp().heap.bytes); +} + #[test] fn a_rest_parameter_checks_the_heap_before_its_array_is_made() { // The 20,000 arguments fit in the room left over, and the rest array of them does not, so diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 84062f9801..91bd67cfed 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -152,7 +152,8 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { /// object made with `Object.create(File.prototype)` included. pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult> { let Some(c) = &i.files else { return Ok(None) }; - if i.object(id)?.proto != Some(c.file_proto) { + let o = i.object(id)?; + if o.proto != Some(c.file_proto) { return Ok(None); } Ok(match own_path(i, id)? { diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs index 3a542a6365..361af9a01f 100644 --- a/crates/js/src/generator.rs +++ b/crates/js/src/generator.rs @@ -18,7 +18,7 @@ use crate::LimitKind; use crate::builtins::iterator::iter_result; use crate::bytecode::Code; use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key}; -use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; +use crate::interp::{Abrupt, AnnexOff, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; use crate::value::Value; /// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4). @@ -305,6 +305,8 @@ impl Interp { completion, boundary, generator: Some(generator), + async_promise: None, + annex_off: AnnexOff::new(), chained: false, pending_module: false, }); diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs index 551fb4e5e6..19eb0c1edf 100644 --- a/crates/js/src/generator_tests.rs +++ b/crates/js/src/generator_tests.rs @@ -253,6 +253,23 @@ fn bad_generators_are_syntax_errors() { truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3"); } +#[test] +fn a_class_extends_generator_function_and_function() { + // CreateDynamicFunction takes the prototype from `new.target` (ECMA-262 2015 section + // 19.2.1.1.1). + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor;\n\ + class G extends GF { tag() { return 'g'; } }\n\ + var g = new G('yield 7');\n\ + Object.getPrototypeOf(g) === G.prototype && g instanceof GF && g.tag() === 'g' && g().next().value === 7", + ); + truth( + "class F extends Function { tag() { return 'f'; } }\n\ + var f = new F('a', 'return a * 2');\n\ + Object.getPrototypeOf(f) === F.prototype && f.tag() === 'f' && f(3) === 6", + ); +} + #[test] fn realms_without_es2015_have_no_generators() { let es5 = Options::default(); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index d69e34fae4..3698826ab0 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -215,9 +215,8 @@ pub(crate) struct ArgMap { #[derive(Clone, Debug)] pub(crate) struct ForIn { pub(crate) keys: Vec, - /// The proxies whose `ownKeys` trap returned a listed name, each with the positions in `keys` - /// of the names it returned. - pub(crate) listed: Vec, + /// Each proxy on the chain maps to the positions in `keys` of the names its `ownKeys` trap returned. + pub(crate) listed: HashMap, pub(crate) pos: usize, pub(crate) object: Option, } @@ -227,7 +226,8 @@ pub(crate) struct ForIn { /// name's position is here. #[derive(Clone, Debug)] pub(crate) struct Listed { - pub(crate) proxy: ObjId, + /// The proxy returned by this proxy's prototype lookup, if any. + pub(crate) prototype: Option, pub(crate) positions: Vec, } @@ -301,6 +301,8 @@ pub(crate) enum Class { Promise(Box), /// The state that the functions a promise operation makes share; scripts never see it. PromiseRecord(Box), + /// An async function's frame waiting at `await`, until it is resumed; scripts never see it. + Activation(Option>), /// A `Map` (ECMA-262 6.0 section 23.1): its entries in the order they were added. Map(Box), /// A `Set` (section 23.2): its values in the order they were added, each with `undefined`. @@ -609,7 +611,7 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) => "Object", + Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) | Class::Activation(_) => "Object", Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", @@ -1105,6 +1107,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) { + code.params.len() + code.pattern_names.len() + code.vars.len() + + code.annex_vars.len() + 2 * code.fun_decls.len() + code.templates.iter().map(|t| 2 + t.cooked.len() + t.raw.len()).sum::(); let tables = code.finally_tables.iter().map(|t| 24 + 4 * t.len()).sum::(); @@ -1128,7 +1131,14 @@ fn mark_code(code: &Code, strings: &mut StringSizes) { strings.add(pattern); strings.add(flags); } - let keys = code.names.iter().chain(&code.params).chain(&code.pattern_names).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k)); + let keys = code + .names + .iter() + .chain(&code.params) + .chain(&code.pattern_names) + .chain(&code.vars) + .chain(&code.annex_vars) + .chain(code.fun_decls.iter().map(|(k, _)| k)); for k in keys.chain(&code.self_name).chain(&code.decl_name).chain(&code.rest) { strings.add_key(k); } @@ -1191,7 +1201,8 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } Class::ForIn(state) => { work.extend(state.object.iter().map(|o| o.0)); - work.extend(state.listed.iter().map(|l| l.proxy.0)); + work.extend(state.listed.keys().map(|o| o.0)); + work.extend(state.listed.values().filter_map(|l| l.prototype.map(|o| o.0))); strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::(); strings.bytes += crate::interp::listed_bytes(&state.listed); } @@ -1297,6 +1308,16 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } extra = crate::builtins::promise::RECORD_BYTES; } + Class::Activation(Some(a)) => { + for v in a.values() { + mark_value(v, work, strings); + } + work.extend(a.ids()); + for code in a.codes() { + mark_code(code, strings); + } + extra = a.bytes(); + } _ => {} } OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 06d3f2e220..b3d171aea9 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -204,7 +204,8 @@ struct Reading { path: Vec, function: Rc, /// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under - /// [`crate::FILE_REF_KEY`], and a plain object that has either key is refused. + /// [`crate::FILE_REF_KEY`], and a plain object that has one of the keys, or + /// [`crate::FOLDER_REF_KEY`], is refused. hosted: bool, } diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 10bcc8b49c..4a3aadb9cb 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -9,8 +9,9 @@ //! of a host class from its own data. A class's prototype and constructor are frozen. While a //! script holds the object for a class and handle, each read of that class and handle gives the //! same object. Classes that descend from the same class without a parent share their objects: a -//! read of another of them with the same handle gives the object the script holds, now of the -//! class that read names. +//! read of an ancestor or descendant of the held object's class with the same handle gives the +//! object the script holds, now of the class that read names. A read of a class on another branch +//! gives a new object, and the held object keeps its class. //! //! Every member function gets the object it is called on (`this`) as its first argument, or //! `undefined` when `this` is not an object of a host class, followed by the call's arguments; a @@ -170,6 +171,18 @@ pub(crate) struct Reflected { pub(crate) info: MemberInfo, } +/// Whether class `a` is class `b` or descends from it, both indexes into `classes`. +fn descends(classes: &[Entry], a: u32, b: u32) -> bool { + let mut at = Some(a); + while let Some(c) = at { + if c == b { + return true; + } + at = classes.get(c as usize).and_then(|e| e.parent); + } + false +} + impl Entry { pub(crate) fn objects(&self) -> [ObjId; 2] { [self.proto, self.ctor] @@ -179,8 +192,9 @@ impl Entry { /// A family of classes ([`Entry::family`]) and the bits of a handle. type MadeKey = (u32, Box<[u64]>); -/// The object made for each family of classes and handle ([`Interp::host_objects`]). -pub(crate) type Made = std::collections::HashMap; +/// The objects made for each family of classes and handle ([`Interp::host_objects`]), one for each +/// branch of the family a read named, oldest first. +pub(crate) type Made = std::collections::HashMap>; /// Whether `id` is still the object made for `key`, and not a freed cell or another object that /// was given its cell. @@ -195,7 +209,10 @@ fn is_made(heap: &crate::heap::Heap, classes: &[Entry], id: ObjId, key: &MadeKey /// Drops the entries of `made` whose objects the last collection freed. pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap, classes: &[Entry]) { - made.retain(|key, id| is_made(heap, classes, *id, key)); + made.retain(|key, ids| { + ids.retain(|id| is_made(heap, classes, *id, key)); + !ids.is_empty() + }); } /// The [`Data`] that stands for the object of host class `class` with `handle`. @@ -295,16 +312,33 @@ impl Interp { let (proto, family) = (entry.proto, entry.family); let class = u32::try_from(class).unwrap_or(u32::MAX); let made = (family, handle.iter().map(|n| n.to_bits()).collect::>()); - if let Some(&id) = self.host_objects.get(&made) - && is_made(&self.heap, &self.host_classes, id, &made) - { - // An object of another class of the family becomes one of `class`. + // The held object of `class` itself, or else the newest of an ancestor or descendant class, + // which becomes one of `class`. An object of a class on another branch of the family keeps + // its class, and a read of `class` with no such object gives a new object. + let mut found = None; + for &id in self.host_objects.get(&made).map(Vec::as_slice).unwrap_or_default() { + if !is_made(&self.heap, &self.host_classes, id, &made) { + continue; + } + let Class::Host(h) = &self.object(id)?.class else { continue }; + if h.class == class { + found = Some(id); + break; + } + if descends(&self.host_classes, h.class, class) || descends(&self.host_classes, class, h.class) { + found = Some(id); + } + } + if let Some(id) = found { + // Its indexer and the indices its prototypes hold can change with its class, so a list + // of the indices it has is made again ([`crate::heap::Heap::index_epoch`]). let o = self.object_mut(id)?; if let Class::Host(h) = &mut o.class && h.class != class { h.class = class; o.proto = Some(proto); + self.heap.index_epoch = self.heap.index_epoch.wrapping_add(1); } return Ok(Value::Object(id)); } @@ -314,7 +348,13 @@ impl Interp { o.extensible = false; let id = self.heap.alloc_object(o); self.heap.bytes = self.heap.bytes.saturating_add(extra); - self.host_objects.insert(made, id); + if let Some(ids) = self.host_objects.get_mut(&made) { + let (heap, classes) = (&self.heap, &self.host_classes); + ids.retain(|&old| old != id && is_made(heap, classes, old, &made)); + ids.push(id); + } else { + self.host_objects.insert(made, vec![id]); + } Ok(Value::Object(id)) } @@ -452,9 +492,9 @@ struct Undo { /// replaced values stay in the interpreter's temporary roots until [`install`] returns, so a /// collection during the call does not free them. globals: Vec<(Key, Option)>, - /// The class and prototype of the object made for each family and handle before the call. An + /// The class and prototype of each object made for a family and handle before the call. An /// instance of the call can give such an object one of the call's classes. - objects: Vec<(MadeKey, u32, Option)>, + objects: Vec<(MadeKey, ObjId, u32, Option)>, } impl Undo { @@ -486,9 +526,9 @@ impl Undo { } } } - for (made, class, proto) in self.objects { - let Some(&id) = i.host_objects.get(&made) else { continue }; - if is_made(&i.heap, &i.host_classes, id, &made) + for (made, id, class, proto) in self.objects { + if i.host_objects.get(&made).is_some_and(|ids| ids.contains(&id)) + && is_made(&i.heap, &i.host_classes, id, &made) && let Ok(o) = i.object_mut(id) && let Class::Host(h) = &mut o.class { @@ -534,12 +574,14 @@ fn install_checked( install_class(i, class, members, undo)?; } if !instances.is_empty() { - for (made, &id) in &i.host_objects { - if is_made(&i.heap, &i.host_classes, id, made) - && let Ok(o) = i.object(id) - && let Class::Host(h) = &o.class - { - undo.objects.push((made.clone(), h.class, o.proto)); + for (made, ids) in &i.host_objects { + for &id in ids { + if is_made(&i.heap, &i.host_classes, id, made) + && let Ok(o) = i.object(id) + && let Class::Host(h) = &o.class + { + undo.objects.push((made.clone(), id, h.class, o.proto)); + } } } } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 194a199b19..44ad23caee 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -931,6 +931,57 @@ fn the_handles_of_host_objects_given_to_the_host_count_toward_the_data_limits() assert_eq!(r.run("thing.take([thing, thing]) === undefined").unwrap(), JsValue::Bool(true)); } +#[test] +fn a_read_of_a_class_on_another_branch_gives_a_new_object() { + let mut r = realm(1_000_000); + let class = |name: &str, parent: Option<&str>| HostClass { + name: name.into(), + parent: parent.map(Into::into), + members: Vec::new(), + info: Vec::new(), + index: None, + construct: None, + }; + let get: HostFunction = Rc::new(|a| match a.get(1) { + Some(Data::String(name)) => Ok(host_ref(name, &[1.0])), + _ => Ok(Data::Null), + }); + let mut maker = class("Maker", None); + maker.members.push(("get".into(), HostMember::Method(get))); + let classes = vec![class("Base", None), class("Left", Some("Base")), class("Right", Some("Base")), class("Leaf", Some("Left")), maker]; + r.define_host_classes(classes, vec![("maker".into(), host_ref("Maker", &[]))]).unwrap(); + let script = "function get(n) { return maker.get(n); } var l = get('Left'), b = get('Base'), f = get('Leaf'); var r = get('Right'); \ + [l === b, b === f, f instanceof Leaf, r === l, r instanceof Right, l instanceof Leaf, get('Leaf') === l, \ + get('Right') === r, get('Base') === r].join()"; + assert_eq!(r.run(script).unwrap(), JsValue::String("true,true,true,false,true,true,true,true,true".into())); +} + +/// The path of a `File` a member of a host class gives is charged to the heap. +#[test] +fn the_path_of_a_file_a_host_class_gives_is_charged_to_the_heap() { + let bytes_after = |len: usize| { + let mut r = realm(1_000_000); + let current: HostFunction = Rc::new(|_| Ok(Data::String("d".into()))); + // The host's `parse` gives the path it is handed as the platform path. + let parse: HostFunction = Rc::new(|a| { + let text = match a.first() { + Some(Data::String(s)) => s.clone(), + _ => String::new(), + }; + Ok(Data::Object(vec![("fs".into(), Data::String(text))])) + }); + r.define_file_classes(vec![("current".into(), HostItem::Function(current)), ("parse".into(), HostItem::Function(parse))]).unwrap(); + let file: HostFunction = Rc::new(move |_| Ok(file_ref(&"p".repeat(len)))); + let members = vec![("file".to_string(), HostMember::Method(file))]; + let maker = HostClass { name: "Maker".into(), parent: None, members, info: Vec::new(), index: None, construct: None }; + r.define_host_classes(vec![maker], vec![("maker".into(), host_ref("Maker", &[]))]).unwrap(); + assert_eq!(r.run("var f = maker.file(); f instanceof File"), Ok(JsValue::Bool(true))); + r.interp().heap.bytes + }; + let (short, long) = (bytes_after(1), bytes_after(100_000)); + assert!(long >= short + 2 * 99_999, "{short} {long}"); +} + #[test] fn a_host_class_constructor_called_with_new_cannot_wait() { let mut r = realm(1_000_000); @@ -946,6 +997,70 @@ fn a_host_class_constructor_called_with_new_cannot_wait() { assert_eq!(could.get(), Some(false)); } +#[test] +fn a_host_class_constructor_called_with_new_cannot_give_a_primitive() { + let mut r = realm(1_000_000); + let make: HostFunction = Rc::new(|_| Ok(Data::Number(7.0))); + with_thing(&mut r, Some(make)); + r.start("var r; try { r = new Thing(); } catch (e) { r = e instanceof TypeError; } r").unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::Bool(true)); +} + +#[test] +fn new_on_a_host_constructor_that_gives_a_value_other_than_an_object_throws() { + let mut r = realm(1_000_000); + let make: HostFunction = Rc::new(|_| Ok(Data::Undefined)); + with_thing(&mut r, Some(make)); + let out = r.run("var e; try { new Thing(); } catch (x) { e = x; } [e instanceof TypeError, typeof Thing()].join()").unwrap(); + assert_eq!(out, JsValue::String("true,undefined".into())); +} + +#[test] +fn an_array_method_visits_every_element_after_its_object_takes_a_class_with_an_indexer() { + let mut r = realm(10_000_000); + // `Base` has a length of 5,000, an element `0` on its prototype and no indexer; `Indexed`, of + // the same family, gives `list[i]` for each index. `upgrade()` gives the same object as an + // `Indexed`. + let length: HostFunction = Rc::new(|_| Ok(Data::Number(5_000.0))); + let zero: HostFunction = Rc::new(|_| Ok(Data::Number(0.0))); + let upgrade: HostFunction = Rc::new(|_| Ok(host_ref("Indexed", &[1.0]))); + let members = vec![ + ("length".to_string(), HostMember::Get(length)), + ("0".to_string(), HostMember::Get(zero)), + ("upgrade".to_string(), HostMember::Method(upgrade)), + ]; + let base = HostClass { name: "Base".into(), parent: None, members, info: Vec::new(), index: None, construct: None }; + let index: HostFunction = Rc::new(|a| Ok(a.get(1).cloned().unwrap_or(Data::Undefined))); + let indexed = + HostClass { name: "Indexed".into(), parent: Some("Base".into()), members: Vec::new(), info: Vec::new(), index: Some(index), construct: None }; + r.define_host_classes(vec![base, indexed], vec![("list".into(), host_ref("Base", &[1.0]))]).unwrap(); + let out = r + .run("var n = 0; Array.prototype.forEach.call(list, function () { if (n === 0) list.upgrade(); n++; }); [list instanceof Indexed, n].join()") + .unwrap(); + assert_eq!(out, JsValue::String("true,5000".into())); +} + +#[test] +fn array_methods_visit_every_element_of_a_long_host_list() { + let mut r = realm(10_000_000); + // `list[i]` is `i` below 5,000, past the span the array methods visit without listing. + let index: HostFunction = Rc::new(|a| { + let i = a.get(1).and_then(|i| if let Data::Number(n) = i { Some(*n) } else { None }); + Ok(i.filter(|n| *n < 5_000.0).map_or(Data::Undefined, Data::Number)) + }); + let length: HostFunction = Rc::new(|_| Ok(Data::Number(5_000.0))); + let members = vec![("length".to_string(), HostMember::Get(length))]; + let class = HostClass { name: "List".into(), parent: None, members, info: Vec::new(), index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("list".into(), host_ref("List", &[1.0]))]).unwrap(); + let out = r + .run( + "var n = 0; Array.prototype.forEach.call(list, function () { n++; });\ + [Array.prototype.indexOf.call(list, 4999), Array.prototype.lastIndexOf.call(list, 0), n].join()", + ) + .unwrap(); + assert_eq!(out, JsValue::String("4999,0,5000".into())); +} + #[test] fn objects_of_a_host_class_report_its_available_members_as_their_own() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 5f1f170b8b..3784b3a515 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -18,6 +18,7 @@ //! keeps its operands on the operand stack until it is done, so everything it holds is reachable //! from the roots when a nested run collects. +use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -122,6 +123,9 @@ impl ErrorType { pub(crate) struct Intrinsics { pub(crate) object_proto: ObjId, pub(crate) function_proto: ObjId, + /// The built-in `Function`, which a script can replace as the global or as the prototype's + /// `constructor`. + pub(crate) function_ctor: ObjId, pub(crate) array_proto: ObjId, pub(crate) string_proto: ObjId, pub(crate) number_proto: ObjId, @@ -149,6 +153,7 @@ impl Intrinsics { Self { object_proto: o, function_proto: o, + function_ctor: o, array_proto: o, string_proto: o, number_proto: o, @@ -185,6 +190,7 @@ impl Intrinsics { let mut v = vec![ self.object_proto, self.function_proto, + self.function_ctor, self.array_proto, self.string_proto, self.number_proto, @@ -206,6 +212,9 @@ impl Intrinsics { } } +/// The names of [`Frame::annex_off`], looked up once for each block function a frame assigns. +pub(crate) type AnnexOff = std::collections::HashSet; + pub(crate) struct Frame { pub(crate) code: Rc, pub(crate) pc: usize, @@ -235,6 +244,12 @@ pub(crate) struct Frame { pub(crate) boundary: bool, /// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it. pub(crate) generator: Option, + /// The promise of the async function the frame runs: a return resolves it, an exception + /// that leaves the frame rejects it, and the call's value is the promise. + pub(crate) async_promise: Option, + /// The block functions of script or eval code ([`Code::annex_vars`]) whose variable was not + /// declared: [`Op::AnnexB`] leaves them alone. + pub(crate) annex_off: AnnexOff, /// The frame runs a module that another module of the same run waits under (ECMA-262 2015 /// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception /// that leaves it ends the run at the boundary frame without stopping in the frames between. @@ -245,6 +260,8 @@ pub(crate) struct Frame { /// Where the exception being thrown was raised: the code and the instruction. pub(crate) type ThrowSite = (Rc, usize); +pub(crate) mod async_function; + /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -329,6 +346,10 @@ pub(crate) struct Interp { /// ECMAScript 2015 gives them ([`crate::builtins::es2015_names`]): set once the realm first /// reads code with [`Options::es2015`], and kept after that. pub(crate) builtin_names: bool, + /// The [`Options::es2017`] a host set while a run was going, for the runs after it. It is + /// applied after [`Self::next_es2015`], and the setters keep the two consistent with the + /// order they were called in. + pub(crate) next_es2017: Option, /// The template objects tagged templates have made, by code and template index, each with /// its code (ECMA-262 2015 section 12.2.9.3 keeps one object for each site). pub(crate) template_objects: std::collections::HashMap<(usize, u32), (Rc, ObjId)>, @@ -374,9 +395,9 @@ pub(crate) struct Interp { pub(crate) host_classes: Vec, /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. pub(crate) write_hosted: bool, - /// The object made for each family of classes and handle ([`crate::host_classes`]), so that two reads of - /// the same one give the same object. It is not a root: an entry whose object was collected is - /// dropped after each collection. + /// The objects made for each family of classes and handle ([`crate::host_classes`]), so that two reads of + /// the same one give the same object. It is not a root: an object that was collected is dropped + /// after each collection. pub(crate) host_objects: crate::host_classes::Made, /// `UnitValue`, once a host has added it ([`crate::Realm::add_unit_values`]). Until then the /// operators take no object as a measurement. @@ -575,11 +596,11 @@ pub(crate) const KEY_ENTRY_BYTES: usize = 32; pub(crate) const SOURCE_ENTRY_BYTES: usize = std::mem::size_of::(); /// The bytes of a `for-in` loop's record of one proxy that listed names, without its positions. -const LISTED_ENTRY_BYTES: usize = std::mem::size_of::(); +const LISTED_ENTRY_BYTES: usize = std::mem::size_of::<(ObjId, Listed)>() + KEY_ENTRY_BYTES; /// The bytes of a `for-in` loop's records of the proxies that listed its names. -pub(crate) fn listed_bytes(listed: &[Listed]) -> usize { - listed.iter().map(|l| LISTED_ENTRY_BYTES.saturating_add(l.positions.len().saturating_mul(SOURCE_ENTRY_BYTES))).sum() +pub(crate) fn listed_bytes(listed: &HashMap) -> usize { + listed.values().map(|l| LISTED_ENTRY_BYTES.saturating_add(l.positions.len().saturating_mul(SOURCE_ENTRY_BYTES))).sum() } /// The most units of a computed property name an error about a property of `null` or `undefined` @@ -674,7 +695,7 @@ fn declaration_bytes(code: &Code) -> usize { let closure = code.functions.get(*fi as usize).map_or(0, |f| closure_bytes(f)); total.saturating_add(binding_bytes(name.len()) + closure) }); - code.vars.iter().fold(funs, |total, v| total.saturating_add(binding_bytes(v.len()))) + code.vars.iter().chain(&code.annex_vars).fold(funs, |total, v| total.saturating_add(binding_bytes(v.len()))) } /// At least the bytes that [`Interp::block_env`] adds to the heap for `code.scopes[i]`: the @@ -753,7 +774,8 @@ fn is(k: &[u16], s: &str) -> bool { } impl Interp { - pub(crate) fn new(options: Options, limits: Limits) -> Self { + pub(crate) fn new(mut options: Options, limits: Limits) -> Self { + options.es2015 = options.modern(); let mut heap = Heap::default(); let global = heap.alloc_object(Object::new(Class::Ordinary, None)); let global_env = heap.alloc_env(Env::Obj { object: global, with_this: false, outer: None }); @@ -773,6 +795,7 @@ impl Interp { next_es2015: None, es2015_installed: false, builtin_names: false, + next_es2017: None, template_objects: std::collections::HashMap::new(), intrinsics: Intrinsics::placeholder(), fuel: u64::MAX, @@ -1073,7 +1096,9 @@ impl Interp { for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); - roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.new_target.iter()).chain(f.generator.iter())); + roots + .objects + .extend(f.callee.iter().chain(f.construct.iter()).chain(f.new_target.iter()).chain(f.generator.iter()).chain(f.async_promise.iter())); roots.envs.extend(f.this_env); roots.envs.push(f.env); roots.envs.push(f.var_env); @@ -1118,7 +1143,11 @@ impl Interp { match self.step() { Ok(Some(v)) => return Ok(v), Ok(None) => {} - Err(Abrupt::Throw(v)) => self.unwind(v)?, + Err(Abrupt::Throw(v)) => { + if let Some(v) = self.unwind_or_abort(v)? { + return Ok(v); + } + } Err(other) => { self.note_site(); self.abort_to_boundary(); @@ -1137,7 +1166,11 @@ impl Interp { match self.step() { Ok(Some(v)) => return Ok(Some(v)), Ok(None) => {} - Err(Abrupt::Throw(v)) => self.unwind(v)?, + Err(Abrupt::Throw(v)) => { + if let Some(v) = self.unwind_or_abort(v)? { + return Ok(Some(v)); + } + } Err(other) => { self.note_site(); self.abort_to_boundary(); @@ -1183,10 +1216,26 @@ impl Interp { } Op::GeneratorStart => self.op_generator_start(), Op::Yield(raw) => self.op_yield(raw), + Op::Await => { + let v = self.pop()?; + self.await_value(v) + } _ => self.exec(op).map(|()| None), } } + /// [`Self::unwind`], ending the frames down to the boundary frame when it fails with a limit + /// or an internal error, which leaves the frame it was in on top. + pub(crate) fn unwind_or_abort(&mut self, v: Value) -> JsResult> { + match self.unwind(v) { + Err(e @ (Abrupt::Limit(_) | Abrupt::Internal(_))) => { + self.abort_to_boundary(); + Err(e) + } + r => r, + } + } + fn note_site(&mut self) { if self.throw_site.is_none() && let Some(f) = self.frames.last() @@ -1197,7 +1246,10 @@ impl Interp { /// Finds the handler for an exception: in the top frame, or in the frames below it up to the /// boundary frame. Returns the exception when no handler takes it before the boundary frame. - fn unwind(&mut self, v: Value) -> JsResult<()> { + /// An async function's frame without a handler rejects its promise with the exception and + /// returns the promise as a `return` would: `Some` with it when that frame was the boundary + /// frame. + fn unwind(&mut self, v: Value) -> JsResult> { self.note_site(); let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b); if !passed @@ -1236,11 +1288,26 @@ impl Interp { if let (false, Some(site)) = (caught, site) { self.finally_sites.push((site, target_len)); } - return Ok(()); + return Ok(None); + } + // The promise is settled while the frame is still on top, so a limit reached doing it + // ends the frames the way any other limit does. + let promise = frame.async_promise; + if let Some(p) = promise { + self.settle_async(p, Err(v.clone()))?; } let Some(frame) = self.pop_frame() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); self.end_generator(frame.generator); + if let Some(p) = promise { + self.drop_left_finally_marks(); + self.drop_left_finally_sites(frame.base); + if frame.boundary { + return Ok(Some(Value::Object(p))); + } + self.push(Value::Object(p))?; + return Ok(None); + } if frame.chained { // The modules under it have not started, so no handler of theirs takes it. self.abort_to_boundary(); @@ -1304,9 +1371,24 @@ impl Interp { }; let Some(frame) = self.pop_frame() else { return internal("return without a frame") }; self.stack.truncate(frame.base); - self.end_generator(frame.generator); // A `return` in a finally block leaves the block, and the value takes its exception's slot. self.drop_left_finally_sites(frame.base); + // An async function's return resolves its promise after the frame is off the frames, so + // a `then` getter the resolution reads runs without it, and the call gives the promise. + // Settling roots the promise and the value, and a rejection for returning the promise + // itself is reported at the return. When settling fails, the frame goes back on top, so + // the error is reported at the return and ends the frames down to its boundary. + let v = match frame.async_promise { + Some(p) => match self.resolve_async_return(p, v, Some((frame.code.clone(), frame.pc.saturating_sub(1)))) { + Ok(()) => Value::Object(p), + Err(e) => { + self.frames.push(frame); + return Err(e); + } + }, + None => v, + }; + self.end_generator(frame.generator); let v = match frame.construct { Some(o) if !matches!(v, Value::Object(_)) => Value::Object(o), _ => v, @@ -1519,7 +1601,9 @@ impl Interp { Op::DelegateCall(t) => self.op_delegate_call(t), Op::DelegateResult(t) => self.op_delegate_result(t), Op::DelegateDone(t) => self.op_delegate_done(t), - Op::Return | Op::ReturnCompletion | Op::GeneratorStart | Op::Yield(_) => internal("a frame-ending instruction reached the dispatcher"), + Op::Return | Op::ReturnCompletion | Op::Await | Op::GeneratorStart | Op::Yield(_) => { + internal("a frame-ending instruction reached the dispatcher") + } } } @@ -1619,7 +1703,7 @@ impl Interp { cur = *outer; } Some(&Env::Obj { object, with_this, outer }) => { - if self.scope_has(object, name)? { + if self.scope_binding(object, name, with_this)? { return Ok(Resolved::Obj { object, with_this }); } cur = outer; @@ -1630,6 +1714,23 @@ impl Interp { Ok(Resolved::Unresolved) } + fn scope_binding(&mut self, object: ObjId, name: &Key, with_this: bool) -> JsResult { + if !self.scope_has(object, name)? { + return Ok(false); + } + if with_this + && self.options.es2015 + && let Some(sym) = self.well_known(|w| &w.unscopables) + { + let blocked = self.get_value_sym(&Value::Object(object), &sym)?; + if let Value::Object(o) = blocked { + let value = self.rooted(&[Value::Object(o)], |i| i.get_from(o, name, &Value::Object(o)))?; + return Ok(!value.truthy()); + } + } + Ok(true) + } + pub(crate) fn binding_value(&self, env: EnvId, name: &[u16]) -> JsResult { match self.heap.env(env) { Some(Env::Decl { bindings, .. }) => Ok(bindings.get(name).map_or(Value::Undefined, |b| b.value.clone())), @@ -1673,7 +1774,7 @@ impl Interp { cur = *outer; } Some(&Env::Obj { object, with_this, outer }) => { - if self.scope_has(object, name)? { + if self.scope_binding(object, name, with_this)? { return self.get_resolved(Resolved::Obj { object, with_this }, name); } let this = Value::Object(object); @@ -2389,7 +2490,7 @@ impl Interp { /// list is checked first. A proxy's names come from its `ownKeys` trap. pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult { if self.is_proxy(id) { - return self.proxy_own_keys(id); + return self.proxy_own_keys(id, false); } let o = self.object(id)?; // A typed array's indices come first, as a String object's do (section 9.4.5.6). @@ -2422,14 +2523,15 @@ impl Interp { } pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult { - let mut keys = self.own_keys(id)?; - if !self.is_proxy(id) { - if matches!(self.object(id)?.class, Class::Array { .. }) { - let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?; - keys.insert(0, length); - } - keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n))); + if self.is_proxy(id) { + return self.proxy_own_keys(id, true); } + let mut keys = self.own_keys(id)?; + if matches!(self.object(id)?.class, Class::Array { .. }) { + let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?; + keys.insert(0, length); + } + keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n))); Ok(keys) } @@ -2999,8 +3101,13 @@ impl Interp { Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }), None => env, }; + let is_async = code.is_async; let generator = code.generator.then(|| self.symbols.objects.map(|o| (o.generator_function_proto, o.generator_proto))).flatten(); - let proto = generator.map_or(self.intrinsics.function_proto, |(function_proto, _)| function_proto); + let proto = match (generator, self.promises.async_function_proto) { + (Some((function_proto, _)), _) => function_proto, + (None, Some(p)) if is_async => p, + _ => self.intrinsics.function_proto, + }; let length = code.length; let strict = code.strict; let arrow = code.arrow; @@ -3033,6 +3140,15 @@ impl Interp { if arrow || method || class_ctor { return Ok(f); } + // An async function has no `prototype` and cannot be constructed (ECMA-262 2017 section + // 25.5.4), and must not have own `caller` or `arguments` properties, restricted or not, in + // sloppy code too (section 16.2). + if is_async { + if let Some(name) = self_name { + self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?; + } + return Ok(f); + } let p = self.new_object(); self.define(p, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?; self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?; @@ -3219,9 +3335,13 @@ impl Interp { Ok(()) } - /// Assigns a function declared in a block to the variable of the same name. + /// Assigns a function declared in a block to the variable of the same name, unless the + /// variable of script or eval code was not declared. fn op_annex_b(&mut self, n: u32) -> JsResult<()> { let name = self.name(n)?; + if self.frame()?.annex_off.contains(&name) { + return self.pop().map(drop); + } let v = self.peek(0)?; let var_env = self.frame()?.var_env; match self.heap.env(var_env) { @@ -3332,29 +3452,28 @@ impl Interp { /// For a String object, the heap budget for all its index names is checked before any is /// built. Each index name and each property visited takes a unit of fuel. /// - /// The second list holds each proxy whose `ownKeys` trap returned a listed name, with the - /// positions of the names it returned. - fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec, Vec)> { + /// The map records each proxy's listed positions and the proxy returned by its prototype lookup. + /// Listing roots remain until `op_for_in_start` installs the iterator. + fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec, HashMap)> { if self.options.e4x && self.is_xml(&Value::Object(id)) { - return Ok((self.xml_enumerate(id)?, Vec::new())); + return Ok((self.xml_enumerate(id)?, HashMap::new())); } let slot = self.temp_roots.len(); self.temp_roots.push(Value::Undefined); - let r = self.enumerable_keys_from(id, slot); - self.temp_roots.truncate(slot); - r + self.enumerable_keys_from(id, slot) } /// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its /// `ownKeys` trap and the next object with its `getPrototypeOf` trap. /// `temp_roots[slot]` roots the current proxy through that lookup, then the returned prototype. /// Descriptors are checked when iteration reaches each name. - fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec, Vec)> { + fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec, HashMap)> { // Each name met on the chain, with its position in `out` when it is listed. let mut seen: std::collections::HashMap> = std::collections::HashMap::new(); let mut held = HeldBytes::new(self); let mut out: Vec = Vec::new(); - let mut listed: Vec = Vec::new(); + let mut listed = HashMap::new(); + let mut proxy_positions: std::collections::HashSet<(ObjId, u32)> = std::collections::HashSet::new(); let next_pos = |out: &Vec| u32::try_from(out.len()).unwrap_or(u32::MAX); let mut cur = Some(id); while let Some(o) = cur { @@ -3362,6 +3481,7 @@ impl Interp { if let Some(root) = self.temp_roots.get_mut(slot) { *root = Value::Object(o); } + self.temp_roots.push(Value::Object(o)); let keys = self.own_keys(o)?; let mut positions = Vec::new(); for k in keys { @@ -3377,18 +3497,20 @@ impl Interp { } }; // A name an earlier object has but does not list is not listed again. - if let Some(pos) = pos { - held.add(self, SOURCE_ENTRY_BYTES)?; + // A proxy met again on the chain records each position once. + if let Some(pos) = pos.filter(|&pos| !proxy_positions.contains(&(o, pos))) { + held.add(self, SOURCE_ENTRY_BYTES.saturating_add(KEY_ENTRY_BYTES))?; + proxy_positions.insert((o, pos)); positions.push(pos); } } - if !positions.is_empty() { - held.add(self, LISTED_ENTRY_BYTES)?; - positions.sort_unstable(); - positions.dedup(); - listed.push(Listed { proxy: o, positions }); - } + held.add(self, LISTED_ENTRY_BYTES)?; cur = self.get_prototype_of(o)?; + let prototype = cur.filter(|&p| self.is_proxy(p)); + // A proxy met again on the chain keeps the names its earlier visits listed. + let entry = listed.entry(o).or_insert_with(|| Listed { prototype, positions: Vec::new() }); + entry.prototype = prototype; + entry.positions.append(&mut positions); if let Some(root) = self.temp_roots.get_mut(slot) { *root = cur.map_or(Value::Undefined, Value::Object); } @@ -3439,18 +3561,30 @@ impl Interp { } cur = obj.proto; } + // Sorted once after the walk, for the iterator's binary search. + for entry in listed.values_mut() { + entry.positions.sort_unstable(); + entry.positions.dedup(); + entry.positions.shrink_to_fit(); + } Ok((out, listed)) } fn op_for_in_start(&mut self) -> JsResult<()> { + let saved = self.temp_roots.len(); + let r = self.op_for_in_start_rooted(); + self.temp_roots.truncate(saved); + r + } + + fn op_for_in_start_rooted(&mut self) -> JsResult<()> { let v = self.peek(0)?; let ((keys, listed), object) = if v.is_nullish() { - ((Vec::new(), Vec::new()), None) + ((Vec::new(), HashMap::new()), None) } else { let o = self.to_object(&v)?; // A wrapper made by ToObject is not on the stack; a collection while the names are // listed or their bytes reserved must not free it. - let saved = self.temp_roots.len(); self.temp_roots.push(Value::Object(o)); // Listing a namespace object's exports does not read them (ECMA-262 2015 section // 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed. @@ -3460,7 +3594,6 @@ impl Interp { self.heap.bytes = self.heap.bytes.saturating_add(bytes); Ok((keys, listed)) }); - self.temp_roots.truncate(saved); (keys?, Some(o)) }; let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, listed, pos: 0, object })), None)); @@ -3493,8 +3626,9 @@ impl Interp { /// /// `pos` is the position of `k` in the names of the loop `iter`. A proxy is asked through its /// `getOwnPropertyDescriptor` trap only when its `ownKeys` trap returned `k` while the names - /// were listed, wherever it sits on the chain now; any other proxy cannot hide an inherited - /// name. A typed array without the element `k` names does not hide its prototypes' `k`. + /// were listed, or when the same prototype lookup returns a fresh proxy of that target. + /// Recorded proxies can move on the chain; any other proxy cannot hide an inherited name. + /// A typed array without the element `k` names does not hide its prototypes' `k`. fn for_in_still_has(&mut self, iter: ObjId, o: ObjId, k: &Key, pos: u32) -> JsResult { // One root slot holds the proxy the walk has reached, then the prototype it gave. let mark = self.temp_roots.len(); @@ -3506,13 +3640,18 @@ impl Interp { fn for_in_still_has_rooted(&mut self, iter: ObjId, mut cur: ObjId, k: &Key, pos: u32, slot: usize) -> JsResult { let mut steps = 0usize; + let mut candidate = None; loop { if self.is_proxy(cur) { if let Some(root) = self.temp_roots.get_mut(slot) { *root = Value::Object(cur); } self.use_fuel()?; - if self.for_in_listed_by(iter, cur, pos)? + let source = self.for_in_listing_proxy(iter, cur, candidate)?; + let Class::ForIn(state) = &self.object(iter)?.class else { return internal("not a for-in iterator") }; + let listed = source.and_then(|p| state.listed.get(&p)); + candidate = listed.and_then(|l| l.prototype); + if listed.is_some_and(|l| l.positions.binary_search(&pos).is_ok()) && let Some(prop) = self.get_own_property(cur, k)? { return Ok(prop.enumerable()); @@ -3524,6 +3663,7 @@ impl Interp { cur = next; continue; } + candidate = None; if let Some(prop) = self.ordinary_own_property(cur, k)? { return Ok(prop.enumerable()); } @@ -3536,11 +3676,18 @@ impl Interp { } } - /// Whether the `ownKeys` trap of `proxy` returned the name at `pos` when the loop `iter` - /// listed its names. - fn for_in_listed_by(&self, iter: ObjId, proxy: ObjId, pos: u32) -> JsResult { + /// Finds a recorded proxy by identity or by the preceding proxy's recorded prototype lookup. + fn for_in_listing_proxy(&self, iter: ObjId, proxy: ObjId, candidate: Option) -> JsResult> { let Class::ForIn(state) = &self.object(iter)?.class else { return internal("not a for-in iterator") }; - Ok(state.listed.iter().any(|l| l.proxy == proxy && l.positions.binary_search(&pos).is_ok())) + if state.listed.contains_key(&proxy) { + return Ok(Some(proxy)); + } + let target = |p: ObjId| match self.heap.object(p).map(|o| &o.class) { + Some(Class::Proxy(d)) => d.target, + _ => None, + }; + let Some(own) = target(proxy) else { return Ok(None) }; + Ok(candidate.filter(|&p| target(p) == Some(own))) } // ---- calls ---- @@ -3759,6 +3906,7 @@ impl Interp { /// the stack. pub(crate) fn enter_function(&mut self, entry: Entry, construct: Option, boundary: bool) -> JsResult<()> { let Entry { callee, code, env, this, args, new_target } = entry; + let code_is_async = code.is_async; self.check_frame_room()?; let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len()))); // An arrow function reads the `arguments` object of the function around it. @@ -3820,6 +3968,8 @@ impl Interp { completion: Value::Undefined, boundary, generator: None, + async_promise: None, + annex_off: AnnexOff::new(), chained: false, pending_module: false, }); @@ -3827,7 +3977,16 @@ impl Interp { }; let r = enter(); self.temp_roots.truncate(mark); - r + r?; + // An async function's call makes its promise first thing (section 25.5.5.2); the frame + // keeps what the function holds reachable while it is made. + if code_is_async && let Err(e) = self.start_async_call() { + if let Some(frame) = self.frames.pop() { + self.stack.truncate(frame.base); + } + return Err(e); + } + Ok(()) } /// Declaration binding instantiation for function code (section 10.5). Each parameter and @@ -4222,10 +4381,11 @@ impl Interp { }; self.stack.truncate(start); self.check_frame_room()?; - let env = self.instantiate_pending(&code, env, var_env, true)?; + let (env, annex_off) = self.instantiate_pending(&code, env, var_env, true)?; self.push_code_frame(code, env, var_env, this, false)?; - // The eval code reads `this` the way the code that called it does (section 18.2.1.1). let frame = self.frame_mut()?; + frame.annex_off = annex_off; + // The eval code reads `this` the way the code that called it does (section 18.2.1.1). frame.this_in_env = this_in_env; frame.new_target = new_target.and_then(|v| v.as_object()); Ok(()) @@ -4234,7 +4394,7 @@ impl Interp { /// [`Self::instantiate_global`] with `code` and its environment `env` kept reachable, and the /// code counted against the heap, until its frame holds them: the scopes and functions it /// makes can collect. - fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> { let mark = self.temp_envs.len(); self.temp_envs.push(env); self.temp_codes.push(code.clone()); @@ -4260,7 +4420,9 @@ impl Interp { r } - /// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. + /// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. The + /// frame limit and the heap, with a script's `let` and `const` names, are checked before + /// anything is declared. pub(crate) fn enter_global(&mut self, code: Rc, is_eval: bool) -> JsResult<()> { // A script's `let` and `const` names are counted with its declarations, so none of them // is declared unless all of them fit. @@ -4276,8 +4438,10 @@ impl Interp { // The frame limit is checked before anything is declared, so a script that cannot start // leaves the global scope as it was. self.check_frame_room()?; - let env = self.instantiate_pending(&code, env, var_env, is_eval)?; - self.push_code_frame(code, env, var_env, Value::Object(global), true) + let (env, annex_off) = self.instantiate_pending(&code, env, var_env, is_eval)?; + self.push_code_frame(code, env, var_env, Value::Object(global), true)?; + self.frame_mut()?.annex_off = annex_off; + Ok(()) } /// The environment global code runs in: the one that holds the scripts' `let` and `const` @@ -4286,10 +4450,18 @@ impl Interp { self.global_lex } - /// Sets [`Options::es2015`] for the next runs. The first run with it on gives the built-in - /// functions their ECMAScript 2015 `name` and `length` ([`crate::builtins::es2015_names`]). + /// Sets [`Options::es2015`] for the next runs; turning it off turns [`Options::es2017`] off too. + /// The first run with it on gives the built-in functions their ECMAScript 2015 `name` and + /// `length` ([`crate::builtins::es2015_names`]). pub(crate) fn set_es2015(&mut self, es2015: bool) { self.options.es2015 = es2015; + self.options.es2017 &= es2015; + } + + /// Sets [`Options::es2017`] for the next runs; turning it on turns [`Options::es2015`] on too. + pub(crate) fn set_es2017(&mut self, es2017: bool) { + self.options.es2017 = es2017; + self.options.es2015 |= es2017; } /// Declares a script's top-level `let` and `const` names in the global scope, uninitialized @@ -4400,6 +4572,8 @@ impl Interp { completion: Value::Undefined, boundary, generator: None, + async_promise: None, + annex_off: AnnexOff::new(), chained: false, pending_module: false, }); @@ -4417,7 +4591,8 @@ impl Interp { let scope = self.global_lex; let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) }); self.temp_envs.push(env); - let lex = self.instantiate_global(code, env, env, true)?; + // Module code is strict, so no block function needs its variable left alone. + let (lex, _annex_off) = self.instantiate_global(code, env, env, true)?; self.temp_envs.push(lex); Ok((lex, env)) } @@ -4529,7 +4704,9 @@ impl Interp { /// global scope ([`Self::declare_global_lexical`]). Eval code outside strict mode code is /// checked against the `let` and `const` names around it ([`Self::check_eval_vars`]) with the /// option on or off, so it also meets the names that earlier runs of a kept realm declared. - fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + /// Also gives the names of [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not + /// declare. + fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> { // Strict eval code's own environment is in no frame yet, so it is a root while the // declarations reserve heap. let mark = self.temp_envs.len(); @@ -4540,7 +4717,7 @@ impl Interp { } /// [`Self::instantiate_global`] with `env` and `var_env` in [`Self::temp_envs`]. - fn instantiate_global_rooted(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + fn instantiate_global_rooted(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> { let configurable = if is_eval { CONFIGURABLE } else { 0 }; if is_eval && !code.strict { self.check_eval_vars(code, env, var_env)?; @@ -4562,7 +4739,8 @@ impl Interp { // some of it (a script's names in the global scope were checked with the declarations // before they were added). Their environment stays reachable if the check collects. self.temp_envs.push(lex); - let r = self.reserve_heap(declaration_bytes(code)).and_then(|()| self.declare_global_functions_and_vars(code, lex, var_env, configurable)); + let r = + self.reserve_heap(declaration_bytes(code)).and_then(|()| self.declare_global_functions_and_vars(code, (env, lex), var_env, configurable)); self.temp_envs.pop(); if r.is_err() && global_lets { // A script that stops before it runs, at a limit, leaves none of its `let` and `const` @@ -4574,12 +4752,19 @@ impl Interp { } } } - r.map(|()| lex) + r.map(|annex_off| (lex, annex_off)) } /// Declares the functions and variables of global or eval code for - /// [`Self::instantiate_global_rooted`], each taking a unit of fuel. - fn declare_global_functions_and_vars(&mut self, code: &Rc, lex: EnvId, var_env: EnvId, configurable: u8) -> JsResult<()> { + /// [`Self::instantiate_global_rooted`], each taking a unit of fuel, and gives the names of + /// [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not declare. + fn declare_global_functions_and_vars( + &mut self, + code: &Rc, + (env, lex): (EnvId, EnvId), + var_env: EnvId, + configurable: u8, + ) -> JsResult { // Functions close over the code's own environment with ES2015's scoping, and over its // variable environment otherwise (ECMA-262 5.1 section 13). When that is the global // object's, they close over the global scope inside it, which also holds the scripts' @@ -4610,7 +4795,55 @@ impl Interp { self.declare(var_env, v, None, configurable)?; self.note_global_var(on_global, v)?; } - Ok(()) + let mut annex_off = AnnexOff::new(); + for v in &code.annex_vars { + self.use_fuel()?; + if !self.annex_var_declarable(v, env, var_env)? { + annex_off.insert(v.clone()); + continue; + } + self.declare(var_env, v, None, configurable)?; + if on_global { + self.global_vars.insert(v.clone()); + } + } + Ok(annex_off) + } + + /// A block function's variable in script or eval code can be declared (Annex B.3.3.2 and + /// B.3.3.3, ): no + /// `let`, `const` or block function from `env` out to `var_env` has the name, a `catch` + /// parameter does not count, no parameter has the name when the code is in a default + /// parameter's value (B.3.2.3), and on the global object the name is its own property or the + /// object is extensible. Each environment passed takes a unit of fuel. + fn annex_var_declarable(&mut self, name: &Key, env: EnvId, var_env: EnvId) -> JsResult { + let mut cur = Some(env).filter(|&e| e != var_env); + while let Some(e) = cur { + self.use_fuel()?; + cur = match self.heap.env(e) { + Some(Env::Decl { bindings, outer }) => { + if bindings.get(name).is_some_and(|b| b.lexical) { + return Ok(false); + } + *outer + } + Some(Env::Obj { outer, .. }) => *outer, + None => return internal("environment out of range"), + } + .filter(|&o| o != var_env); + } + if var_env != self.global_env { + // Eval code in a default parameter's value declares into the parameters' environment, + // where the parameters are lexical bindings. + self.use_fuel()?; + return match self.heap.env(var_env) { + Some(Env::Decl { bindings, .. }) => Ok(!bindings.get(name).is_some_and(|b| b.lexical)), + Some(Env::Obj { .. }) => Ok(true), + None => internal("environment out of range"), + }; + } + let global = self.global; + Ok(self.get_own_property(global, name)?.is_some() || self.object(global)?.extensible) } /// Adds `name`, which global code just declared, to [`Self::global_vars`] when `on_global` diff --git a/crates/js/src/interp/async_function.rs b/crates/js/src/interp/async_function.rs new file mode 100644 index 0000000000..9bcf7f274c --- /dev/null +++ b/crates/js/src/interp/async_function.rs @@ -0,0 +1,176 @@ +//! An async function's frame while it waits at `await` (ECMA-262 2017 sections 25.5 and 6.2.3.1, +//! ): [`Interp::suspend_frame`] moves the running +//! frame, its operands and its pending `finally` state into an [`Activation`], which lives on the +//! heap inside the functions that resume it, and [`Interp::restore_frame`] puts it back on top of +//! the frames to go on. An activation that nothing can resume any more is collected like any +//! other object. + +use std::rc::Rc; + +use super::{Frame, Interp, JsResult, ThrowSite, internal}; +use crate::bytecode::Code; +use crate::heap::{EnvId, ObjId}; +use crate::value::Value; + +/// The estimated bytes of an activation, beyond the object and its operands. +pub(crate) const ACTIVATION_BYTES: usize = 128; +/// The estimated bytes of each operand, `finally` mark or `finally` site an activation keeps. +pub(crate) const SLOT_BYTES: usize = 16; + +/// A suspended frame. Stack slots in `marks` and `sites` count from the frame's first operand. +#[derive(Clone)] +pub(crate) struct Activation { + code: Rc, + pc: usize, + env: EnvId, + var_env: EnvId, + env_depth: u32, + this: Value, + this_in_env: bool, + strict_class: bool, + callee: Option, + new_target: Option, + this_env: Option, + completion: Value, + /// The promise the async function's call returned. + pub(crate) promise: ObjId, + stack: Vec, + marks: Vec<(ObjId, u32, usize)>, + sites: Vec<(ThrowSite, usize)>, +} + +impl Activation { + /// The values the activation holds, for the collector. + pub(crate) fn values(&self) -> impl Iterator { + self.stack.iter().chain([&self.this, &self.completion]) + } + + /// The objects and environments the activation holds, for the collector. + pub(crate) fn ids(&self) -> impl Iterator { + self.callee + .iter() + .chain(self.new_target.iter()) + .chain([&self.promise]) + .chain(self.marks.iter().map(|(o, _, _)| o)) + .map(|o| o.0) + .chain([self.env.0, self.var_env.0]) + .chain(self.this_env.iter().map(|e| e.0)) + } + + /// The code the activation runs and the code of its `finally` sites, for the collector. + pub(crate) fn codes(&self) -> impl Iterator { + std::iter::once(&*self.code).chain(self.sites.iter().map(|((code, _), _)| &**code)) + } + + /// The estimated bytes of the activation, beyond the object. + pub(crate) fn bytes(&self) -> usize { + ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(self.stack.len() + self.marks.len() + self.sites.len())) + } +} + +impl Interp { + /// The promise of the async function the top frame runs, when it runs one. + pub(crate) fn async_promise(&self) -> Option { + self.frames.last().and_then(|f| f.async_promise) + } + + /// Makes the promise of the async function call whose frame was just pushed. + pub(crate) fn start_async_call(&mut self) -> JsResult<()> { + let p = self.new_async_promise()?; + match self.frames.last_mut() { + Some(f) => { + f.async_promise = Some(p); + Ok(()) + } + None => internal("an async call without a frame"), + } + } + + /// The bytes [`Self::suspend_frame`] will move off the operand stack, for the heap check made + /// before it. + pub(crate) fn suspend_bytes(&self) -> usize { + let Some(f) = self.frames.last() else { return ACTIVATION_BYTES }; + let n = self.stack.len().saturating_sub(f.base) + + self.finally_marks.iter().filter(|&&(_, _, s)| s >= f.base).count() + + self.finally_sites.iter().filter(|&&(_, s)| s >= f.base).count(); + ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(n)) + } + + /// Takes the top frame, which runs an async function, off the frames with its operands and + /// its `finally` state. Gives the activation and whether the frame was a boundary frame. + pub(crate) fn suspend_frame(&mut self) -> JsResult<(Activation, bool)> { + let Some(frame) = self.frames.pop() else { return internal("await without a frame") }; + let Some(promise) = frame.async_promise else { return internal("await outside an async function") }; + let base = frame.base; + if self.stack.len() < base { + return internal("frame operands below the stack"); + } + let stack = self.stack.split_off(base); + let mut marks = Vec::new(); + self.finally_marks.retain(|&(o, mark, slot)| { + if slot < base { + return true; + } + marks.push((o, mark, slot - base)); + false + }); + let at = self.finally_sites.iter().position(|&(_, slot)| slot >= base).unwrap_or(self.finally_sites.len()); + let sites = self.finally_sites.split_off(at).into_iter().map(|(site, slot)| (site, slot - base)).collect(); + let activation = Activation { + code: frame.code, + pc: frame.pc, + env: frame.env, + var_env: frame.var_env, + env_depth: frame.env_depth, + this: frame.this, + this_in_env: frame.this_in_env, + strict_class: frame.strict_class, + callee: frame.callee, + new_target: frame.new_target, + this_env: frame.this_env, + completion: frame.completion, + promise, + stack, + marks, + sites, + }; + Ok((activation, frame.boundary)) + } + + /// Puts a suspended frame back on top of the frames as a boundary frame, with its operands at + /// the top of the operand stack. + pub(crate) fn restore_frame(&mut self, a: Activation) -> JsResult<()> { + if self.frames.len() >= self.limits.frames { + return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Frames)); + } + let base = self.stack.len(); + for v in a.stack { + self.push(v)?; + } + self.finally_marks.extend(a.marks.into_iter().map(|(o, mark, slot)| (o, mark, slot + base))); + self.finally_sites.extend(a.sites.into_iter().map(|(site, slot)| (site, slot + base))); + self.frames.push(Frame { + code: a.code, + pc: a.pc, + base, + env: a.env, + var_env: a.var_env, + env_depth: a.env_depth, + this: a.this, + this_in_env: a.this_in_env, + strict_class: a.strict_class, + callee: a.callee, + construct: None, + new_target: a.new_target, + this_env: a.this_env, + completion: a.completion, + boundary: true, + generator: None, + async_promise: Some(a.promise), + annex_off: super::AnnexOff::new(), + chained: false, + pending_module: false, + }); + Ok(()) + } +} diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index cf47fa9848..8fa4dfe23d 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -1029,6 +1029,7 @@ fn code(ops: Vec) -> Code { params: Vec::new(), vars: Vec::new(), fun_decls: Vec::new(), + annex_vars: Vec::new(), uses_arguments: false, source, span: (0, 0), @@ -1048,6 +1049,7 @@ fn code(ops: Vec) -> Code { own_name: None, method: false, generator: false, + is_async: false, supers: crate::parser::SuperRules::default(), } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 731ef1aed1..77b3e00856 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -126,7 +126,12 @@ //! ECMAScript 2020 defines them (sections 26.1 and 26.2 and 9.5, //! ), with string and Symbol property keys: a trap is //! given either kind of key, an `ownKeys` trap may return both, and `Reflect.ownKeys` lists both. +//! +//! With [`Options::es2017`], the parser and the realm also read and run async functions and +//! `await` (ECMA-262 2017 section 25.5, ). +//! An `await` suspends its function's frame until the value settles, and a promise job resumes it. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ast; mod builtins; @@ -220,11 +225,29 @@ pub struct Options { /// `Promise` to a realm made without it. Runs with it on also convert `0b` and `0o` strings to /// numbers. pub es2015: bool, + /// Also read and run async functions and `await` (ECMAScript 2017). It turns on + /// [`Options::es2015`] too, whatever that field says. Off, `async` and `await` are identifiers. + pub es2017: bool, +} + +impl Options { + /// [`Options::es2015`], which [`Options::es2017`] turns on too. + pub(crate) fn modern(&self) -> bool { + self.es2015 || self.es2017 + } } impl Default for Options { fn default() -> Self { - Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false } + Self { + strict: false, + preprocessor_lines: false, + max_depth: DEFAULT_MAX_DEPTH, + max_source_units: 64 << 20, + e4x: false, + es2015: false, + es2017: false, + } } } @@ -355,6 +378,8 @@ impl LineTable { } } +#[cfg(test)] +mod async_tests; #[cfg(test)] mod builtins_tests; #[cfg(test)] diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 12c76f6b47..b733f90093 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -47,6 +47,23 @@ struct Context { /// The code is a generator function's body or parameters: `yield` starts a yield expression /// there and is not an identifier (ECMA-262 2015 sections 12.1.1 and 14.4). generator: bool, + /// The code is an async function's body: `await` is an operator, not an identifier. + in_async: bool, + /// The code is an async function's parameters: `await` is neither an operator nor an + /// identifier there (ECMA-262 2017 section 14.6.1). + async_params: bool, +} + +/// What the parser noted about a parenthesized expression or a call to `async` that may turn out +/// to be an arrow function's head. +#[derive(Clone, Copy, Debug)] +struct Head { + /// A line break comes between `async` and `(`. + line_break: bool, + /// The parentheses hold an `await` expression or the identifier `await`. + awaits: bool, + /// A comma follows the last item in the parentheses. + trailing_comma: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -104,6 +121,8 @@ enum BinKind { enum Prefix { Unary(UnaryOp), Update(UpdateOp), + /// `await`, in an async function's body. + Await, } pub(crate) struct Parser<'s> { @@ -154,11 +173,20 @@ pub(crate) struct Parser<'s> { /// Where each yield expression read so far starts, in the order read, so the parameters of a /// generator function and an arrow function's head can be checked for one. yields: Vec, + /// Read async functions and `await` ([`crate::Options::es2017`]). + es2017: bool, + /// How many `await` expressions and `await` identifiers have been read. + awaits: u32, + /// The parenthesized expressions and calls to `async` read so far that may be arrow heads. + heads: HashMap, + /// The last identifier expression read from an `async` written without escapes. + async_ident: Option, } impl<'s> Parser<'s> { pub(crate) fn new(src: &'s [u16], options: &crate::Options, keep_tokens: bool) -> Result { - let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(options.es2015); + let es2015 = options.modern(); + let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(es2015); let placeholder = Token { kind: TokenKind::Eof, span: Span::default(), line: 1, column: 1, newline_before: false, escaped: false, legacy_octal: false }; let mut parser = Self { @@ -176,8 +204,12 @@ impl<'s> Parser<'s> { function_allowed: false, in_list: false, e4x: options.e4x, - es2015: options.es2015, - scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + es2015, + scopes: if es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + es2017: options.es2017, + awaits: 0, + heads: HashMap::new(), + async_ident: None, supers: SuperRules::default(), module: false, cover_inits: Vec::new(), @@ -349,6 +381,9 @@ impl<'s> Parser<'s> { if self.ctx.generator && name == "yield" { return Err(self.error_at_token(token, "'yield' cannot be an identifier in a generator function")); } + if name == "await" && (self.ctx.in_async || self.ctx.async_params) { + return Err(self.error_at_token(token, "'await' cannot be an identifier in an async function")); + } Ok(()) } @@ -358,6 +393,17 @@ impl<'s> Parser<'s> { self.yields.get(i).is_some_and(|&y| y < end) } + /// The current token is `async` written without escapes, read as the start of an async + /// function or arrow function only with [`crate::Options::es2017`]. + fn at_async(&self) -> bool { + self.es2017 && self.tok.ident() == Some("async") && !self.tok.escaped + } + + /// The current token is `async` and `function` follows it on the same line: an async function. + fn at_async_function(&self) -> bool { + self.at_async() && self.peek().is_some_and(|t| t.is_keyword(Keyword::Function) && !t.newline_before) + } + /// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does, /// and in strict code neither `eval` nor `arguments`. fn binding_identifier(&mut self) -> Result { @@ -369,6 +415,9 @@ impl<'s> Parser<'s> { if self.ctx.strict && is_eval_or_arguments(&name) { return Err(self.error_at_token(&self.tok, format!("'{name}' cannot be declared in strict mode"))); } + if name == "await" { + self.awaits = self.awaits.saturating_add(1); + } let token = self.bump()?; Ok(Name { name, span: token.span }) } @@ -438,7 +487,11 @@ impl<'s> Parser<'s> { /// Declares a function declaration that stands in a statement list: var-scoped in a function /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { - let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) }; + let Some(f) = self.ast.function(id) else { return Ok(()) }; + let Some(name) = f.name.clone() else { return Ok(()) }; + // Only plain function declarations may repeat in a block (Annex B.3.3.4), not generator + // or async ones. + let plain = !f.is_async && !f.generator; if self.module && self.scopes.len() == 1 { return self.declare_lexical(&name, true); } @@ -450,8 +503,7 @@ impl<'s> Parser<'s> { scope.vars.insert(name.name); Ok(()) } - // Only plain function declarations may repeat in a block (Annex B.3.3.4). - Some(_) => self.declare_lexical(&name, !generator), + Some(_) => self.declare_lexical(&name, plain), None => Ok(()), } } @@ -565,7 +617,7 @@ impl<'s> Parser<'s> { /// A source element: a function declaration or a statement. fn parse_statement_item(&mut self) -> Result { - if self.at_keyword(Keyword::Function) { + if self.at_keyword(Keyword::Function) || self.at_async_function() { self.enter()?; let result = self.parse_function_declaration(); self.leave(); @@ -631,6 +683,9 @@ impl<'s> Parser<'s> { } self.parse_function_declaration() } + TokenKind::Ident(_) if self.at_async_function() => { + Err(self.error_at_token(&self.tok, "an async function declaration cannot stand here; put it in a block")) + } TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list), _ => self.plain_statement(start), } @@ -1138,10 +1193,13 @@ impl<'s> Parser<'s> { // ---- functions ---- fn parse_function_declaration(&mut self) -> Result { - let start = self.expect_keyword(Keyword::Function)?.span; - let generator = self.es2015 && self.eat(Punct::Star)?; + let is_async = self.at_async(); + let start = if is_async { self.bump()?.span } else { self.tok.span }; + self.expect_keyword(Keyword::Function)?; + // Async generators (ECMAScript 2018) stay syntax errors: the `*` is not read after `async`. + let generator = !is_async && self.es2015 && self.eat(Punct::Star)?; let name = self.function_name()?; - let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?; + let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, is_async)?; Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start))) } @@ -1157,20 +1215,22 @@ impl<'s> Parser<'s> { Ok((Name { name, span: token.span }, token)) } - /// The parameters and body of a function, from `(`; with `generator`, a generator function's. + /// The parameters and body of a function, from `(`; with `generator`, a generator function's, + /// and with `is_async`, an async function's. fn parse_function_rest( &mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, generator: bool, + is_async: bool, ) -> Result { - self.parse_function_with(kind, name, start, false, generator) + self.parse_function_with(kind, name, start, false, generator, is_async) } /// The parameters and body of a function, from `(`; `home` for one defined in a class body or - /// as a method of an object literal, where `super.property` may stand, and with `generator`, a - /// generator function's. + /// as a method of an object literal, where `super.property` may stand, with `generator`, a + /// generator function's, and with `is_async`, an async function's. fn parse_function_with( &mut self, kind: FunctionKind, @@ -1178,6 +1238,7 @@ impl<'s> Parser<'s> { start: Span, home: bool, generator: bool, + is_async: bool, ) -> Result { self.enter()?; let rules = SuperRules::function(home, kind == FunctionKind::DerivedConstructor); @@ -1185,7 +1246,16 @@ impl<'s> Parser<'s> { // The parameters are read with the function's own `yield` rule, not the enclosing code's. let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); let yields = self.yields.len(); - let result = self.function_rest(kind, name, start, home, generator); + // The parameters are read with `await` as the function has it, then the code around + // them goes on as it was. + // An `await` inside the function does not count for an arrow function's head around it. + let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits); + self.ctx.in_async = false; + self.ctx.async_params = is_async; + let result = self.function_rest(kind, name, start, home, generator, is_async); + self.ctx.in_async = in_async; + self.ctx.async_params = async_params; + self.awaits = awaits; // The `yield` expressions of this function are not in the code around it. self.yields.truncate(yields); self.ctx.generator = outer_generator; @@ -1201,6 +1271,7 @@ impl<'s> Parser<'s> { start: Span, home: bool, generator: bool, + is_async: bool, ) -> Result { let params_start = self.tok.span.start; self.expect(Punct::LParen)?; @@ -1254,7 +1325,7 @@ impl<'s> Parser<'s> { self.expect(Punct::LBrace)?; let names: Vec = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, generator, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, generator, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let body = self.parse_body(true); @@ -1263,14 +1334,18 @@ impl<'s> Parser<'s> { self.ctx = outer; let body = body?; self.expect(Punct::RBrace)?; - let function = - Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, span: self.span_from(start), home }; + let span = self.span_from(start); + let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, is_async, span, home }; + // An async declaration or expression takes FormalParameters as a plain function does + // (ECMA-262 2017 section 14.6): repeated simple names are an error only in strict code. + // Arrow functions and async methods reject every repeat. self.check_params(&function, use_strict)?; Ok(self.ast.push_function(function)) } - /// An arrow function's body and the function, from `=>`, with its parameters read. - fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool) -> Result { + /// An arrow function's body and the function, from `=>`, with its parameters read; with + /// `is_async`, an async arrow function's. + fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool, is_async: bool) -> Result { if self.tok.newline_before { return Err(self.error_at_token(&self.tok, "a line break cannot come before '=>'")); } @@ -1278,8 +1353,10 @@ impl<'s> Parser<'s> { self.enter()?; let names: Vec = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); + // An `await` in the body does not count for an async arrow function's head around it. + let awaits = self.awaits; self.push_scope(true, names); let block = self.at(Punct::LBrace); let body = if block { @@ -1288,6 +1365,7 @@ impl<'s> Parser<'s> { self.parse_assignment(no_in).map(|e| vec![self.ast.push_stmt(Stmt::Return(Some(e)), self.ast.expr_span(e))]) }; self.pop_scope(); + self.awaits = awaits; let (strict, use_strict) = (self.ctx.strict, self.ctx.use_strict); self.ctx = outer; self.leave(); @@ -1305,6 +1383,7 @@ impl<'s> Parser<'s> { body, strict, generator: false, + is_async, span: self.span_from(start), home: false, }; @@ -1323,6 +1402,13 @@ impl<'s> Parser<'s> { Some(Expr::Sequence(list)) => list.clone(), _ => vec![*inner], }; + self.arrow_items(items) + } + + /// The parameters the items of an arrow function's head give: names, names with `= default`, + /// and a last `...name`. + fn arrow_items(&mut self, items: Vec) -> Result { + let invalid = |p: &Self, at: ExprId| p.error_at_offset(p.ast.expr_span(at).start, "invalid arrow function parameters"); let (mut params, mut defaults, mut rest) = (Vec::new(), Vec::new(), None); let count = items.len(); for (i, item) in items.into_iter().enumerate() { @@ -1426,10 +1512,12 @@ impl<'s> Parser<'s> { fn assignment(&mut self, no_in: bool) -> Result { let mut targets: Vec<(ExprId, AssignOp)> = Vec::new(); loop { + // `async` followed on its line by a name starts an async arrow function. + let async_name = self.at_async() && self.peek().is_some_and(|t| matches!(t.kind, TokenKind::Ident(_)) && !t.newline_before); let expr = if self.ctx.generator && self.tok.ident() == Some("yield") && !self.tok.escaped { self.parse_yield(no_in)? } else { - let mut expr = self.parse_conditional(no_in)?; + let mut expr = if async_name { self.parse_async_name_arrow(no_in)? } else { self.parse_conditional(no_in)? }; if self.es2015 && self.at(Punct::Arrow) { expr = self.arrow_from(expr, no_in)?; } @@ -1475,12 +1563,46 @@ impl<'s> Parser<'s> { if self.yield_between(start.start, start.end) { return Err(self.error_at_offset(start.start, "a yield expression cannot stand in an arrow function's parameters")); } - let params = match self.ast.expr(expr) { - Some(Expr::Ident(name)) => (vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None), - Some(Expr::Paren(_)) => self.arrow_params(expr)?, + let head = self.heads.get(&expr).copied(); + let (params, is_async) = match self.ast.expr(expr) { + Some(Expr::Ident(name)) => ((vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None), false), + Some(Expr::Paren(_)) => (self.arrow_params(expr)?, false), + // `async (…) =>` was read as a call to `async` (ECMA-262 2017 section 14.7). + Some(Expr::Call { args, .. }) if head.is_some() => { + if head.is_some_and(|h| h.line_break) { + return Err(self.error_at_offset(start.start, "a line break cannot come after 'async' in an async arrow function")); + } + // No comma may follow a rest parameter (ECMA-262 2017 section 14.1). + if let Some(&last) = args.last() + && head.is_some_and(|h| h.trailing_comma) + && matches!(self.ast.expr(last), Some(Expr::Spread(_))) + { + return Err(self.error_at_offset(self.ast.expr_span(last).start, "a rest parameter must be the last parameter")); + } + (self.arrow_items(args.clone())?, true) + } _ => return Err(self.unexpected()), }; - self.parse_arrow(start, params, no_in) + // `await` cannot be an arrow function's parameter, or stand in one's default value, + // where it is an operator or in an async arrow function's head. + if head.is_some_and(|h| h.awaits) && (is_async || self.ctx.in_async) { + return Err(self.error_at_offset(start.start, "'await' cannot stand in an arrow function's parameters here")); + } + self.parse_arrow(start, params, no_in, is_async) + } + + /// `async name => …` from `async` (ECMA-262 2017 section 14.7): the one parameter is read as + /// an async function's is. + fn parse_async_name_arrow(&mut self, no_in: bool) -> Result { + let start = self.bump()?.span; + let async_params = std::mem::replace(&mut self.ctx.async_params, true); + let param = self.binding_identifier(); + self.ctx.async_params = async_params; + let param = param?; + if !self.at(Punct::Arrow) { + return Err(self.error_at_token(&self.tok, format!("expected '=>' but found {}", describe(&self.tok)))); + } + self.parse_arrow(start, (vec![Binding::Name(param)], vec![None], None), no_in, true) } /// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code @@ -1571,7 +1693,17 @@ impl<'s> Parser<'s> { /// Prefix operators, read with a loop and applied innermost first. fn parse_unary(&mut self) -> Result { let mut prefixes = Vec::new(); - while let Some(prefix) = prefix_op(&self.tok) { + loop { + // In an async function's body, `await` is a prefix operator (ECMA-262 2017 section 14.6). + let prefix = if self.ctx.in_async && self.tok.ident() == Some("await") { + if self.tok.escaped { + return Err(self.error_at_token(&self.tok, "keyword 'await' must not contain escaped characters")); + } + Prefix::Await + } else { + let Some(prefix) = prefix_op(&self.tok) else { break }; + prefix + }; prefixes.push((prefix, self.tok.span)); self.bump()?; } @@ -1589,6 +1721,10 @@ impl<'s> Parser<'s> { } self.ast.push_expr(Expr::Unary { op, arg: expr }, span) } + Prefix::Await => { + self.awaits = self.awaits.saturating_add(1); + self.ast.push_expr(Expr::Await(expr), span) + } }; } Ok(expr) @@ -1650,12 +1786,23 @@ impl<'s> Parser<'s> { expr = self.ast.push_expr(Expr::TaggedTemplate { tag: expr, quasis, exprs }, span); } TokenKind::Punct(Punct::LParen) => { - let args = self.parse_arguments()?; + let async_head = news.is_empty() && self.async_ident.is_some_and(|a| a == expr); + let line_break = self.tok.newline_before; + let awaits = self.awaits; + // The arguments of a possible async arrow function's head may be patterns + // such as `{a = 1}`; they are checked as expressions once no `=>` follows. + let mark = self.cover_inits.len(); + let (args, trailing_comma) = self.arguments(async_head)?; let span = Span::new(self.ast.expr_span(expr).start, self.prev_end); expr = match news.pop() { Some(new) => self.ast.push_expr(Expr::New { callee: expr, args }, Span::new(new.start, self.prev_end)), None => self.ast.push_expr(Expr::Call { callee: expr, args }, span), }; + if async_head && self.at(Punct::Arrow) { + self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits, trailing_comma }); + } else if async_head { + self.check_cover(mark)?; + } } TokenKind::Punct(Punct::QuestionDot) => { if !news.is_empty() { @@ -1802,19 +1949,33 @@ impl<'s> Parser<'s> { } fn parse_arguments(&mut self) -> Result> { + Ok(self.arguments(false)?.0) + } + + /// An argument list, and whether a comma follows its last argument. With `cover`, the + /// arguments may hold initializers such as `{a = 1}`, which the caller checks. + fn arguments(&mut self, cover: bool) -> Result<(Vec, bool)> { self.expect(Punct::LParen)?; let mut args = Vec::new(); + let mut trailing_comma = false; if !self.at(Punct::RParen) { loop { + if cover { + self.cover_ok = true; + } args.push(self.parse_element()?); // A comma may follow the last argument (ECMAScript 2017, section 12.3). - if !self.eat(Punct::Comma)? || self.at(Punct::RParen) { + if !self.eat(Punct::Comma)? { + break; + } + if self.at(Punct::RParen) { + trailing_comma = true; break; } } } self.expect(Punct::RParen)?; - Ok(args) + Ok((args, trailing_comma)) } fn parse_primary(&mut self) -> Result { @@ -1836,9 +1997,20 @@ impl<'s> Parser<'s> { let class = self.parse_class(false)?; return Ok(self.ast.push_expr(Expr::Class(Box::new(class)), self.span_from(start))); } + TokenKind::Ident(_) if self.at_async_function() => return self.parse_function_expression(), TokenKind::Ident(name) => { let name = name.clone(); self.check_identifier(&self.tok, &name)?; + if name == "await" { + self.awaits = self.awaits.saturating_add(1); + } + // With E4X, `async::name` is a qualified name. + if self.at_async() && !(self.e4x && self.peek().is_some_and(|t| t.is_punct(Punct::ColonColon))) { + let token = self.bump()?; + let id = self.ast.push_expr(Expr::Ident(name), token.span); + self.async_ident = Some(id); + return Ok(id); + } Expr::Ident(name) } TokenKind::Number(n) => { @@ -1887,9 +2059,11 @@ impl<'s> Parser<'s> { } /// `( … )` with [`crate::Options::es2015`]: a parenthesized expression, or the head of an arrow - /// function, which may also be `()` or end with `...name`; those two must come before `=>`. + /// function, which may also be `()`, end with `...name` or end with a comma; those three must + /// come before `=>`. fn parse_paren_or_arrow_head(&mut self) -> Result { let start = self.expect(Punct::LParen)?.span; + let awaits = self.awaits; let mut items = Vec::new(); let mut head_only = self.at(Punct::RParen); let mark = self.cover_inits.len(); @@ -1906,8 +2080,11 @@ impl<'s> Parser<'s> { if !self.eat(Punct::Comma)? { break; } + // A comma may follow the last parameter (ECMA-262 2017 section 14.2), but not the + // last item of a parenthesized expression. if self.at(Punct::RParen) { - return Err(self.unexpected()); + head_only = true; + break; } } self.expect(Punct::RParen)?; @@ -1924,7 +2101,11 @@ impl<'s> Parser<'s> { self.ast.push_expr(Expr::Sequence(items), span) } }; - Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start))) + let paren = self.ast.push_expr(Expr::Paren(inner), self.span_from(start)); + if self.at(Punct::Arrow) { + self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits, trailing_comma: false }); + } + Ok(paren) } /// A template literal from its first piece (the current token): its pieces and substitutions. @@ -1953,14 +2134,25 @@ impl<'s> Parser<'s> { } fn parse_function_expression(&mut self) -> Result { - let start = self.expect_keyword(Keyword::Function)?.span; - let generator = self.es2015 && self.eat(Punct::Star)?; - // A generator expression's name is read with its own `yield` rule. + let is_async = self.at_async(); + let start = if is_async { self.bump()?.span } else { self.tok.span }; + self.expect_keyword(Keyword::Function)?; + // Async generators (ECMAScript 2018) stay syntax errors: the `*` is not read after `async`. + let generator = !is_async && self.es2015 && self.eat(Punct::Star)?; + // A function expression's name is read as its own body reads names (ECMA-262 2017 + // section 14.6): `await` is a name for an ordinary one, and not for an async one, and a + // generator expression's name is read with its own `yield` rule. + // Nor does the name count for an arrow function's head around it. + let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits); + self.ctx.in_async = is_async; + self.ctx.async_params = false; let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) }; self.ctx.generator = outer_generator; - let name = name?; - let id = self.parse_function_rest(FunctionKind::Expression, name, start, generator)?; + self.ctx.in_async = in_async; + self.ctx.async_params = async_params; + self.awaits = awaits; + let id = self.parse_function_rest(FunctionKind::Expression, name?, start, generator, is_async)?; Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start))) } @@ -2023,14 +2215,21 @@ impl<'s> Parser<'s> { self.bump()?; } let start = self.tok.span; - let generator = self.eat(Punct::Star)?; + // `async name(…) {…}` (ECMA-262 2017 section 14.6): an async method, with no line break + // after `async`. Async generator methods (ECMAScript 2018) stay syntax errors. + let is_async = + self.at_async() && self.peek().is_some_and(|t| !t.newline_before && (property_key(&t).is_some() || t.is_punct(Punct::LBracket))); + if is_async { + self.bump()?; + } + let generator = !is_async && self.eat(Punct::Star)?; // `get` and `set` start an accessor only when written without escapes and followed by a name. let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) { Some("get") => Some(MethodKind::Get), Some("set") => Some(MethodKind::Set), _ => None, } - .filter(|_| !generator && self.peek().is_some_and(|t| property_key(&t).is_some() || t.is_punct(Punct::LBracket))); + .filter(|_| !generator && !is_async && self.peek().is_some_and(|t| property_key(&t).is_some() || t.is_punct(Punct::LBracket))); if accessor.is_some() { self.bump()?; } @@ -2051,7 +2250,10 @@ impl<'s> Parser<'s> { return Err(self.error_at_offset(start.start, "a class constructor cannot be a generator")); } let ctor = if derived { FunctionKind::DerivedConstructor } else { FunctionKind::ClassConstructor }; - return Ok(Err(self.parse_function_with(ctor, None, start, true, false)?)); + if is_async { + return Err(self.error_at_offset(start.start, "a class constructor cannot be async")); + } + return Ok(Err(self.parse_function_with(ctor, None, start, true, false, false)?)); } if is_static && named("prototype") { return Err(self.error_at_offset(start.start, "a class cannot have a static method named 'prototype'")); @@ -2061,7 +2263,7 @@ impl<'s> Parser<'s> { MethodKind::Get => FunctionKind::Getter, MethodKind::Set => FunctionKind::Setter, }; - let function = self.parse_function_with(fkind, None, start, true, generator)?; + let function = self.parse_function_with(fkind, None, start, true, generator, is_async)?; Ok(Ok(ClassElement { key, is_static, kind, function })) } @@ -2078,8 +2280,19 @@ impl<'s> Parser<'s> { } else { (FunctionKind::ClassConstructor, None, Vec::new()) }; - let function = - Function { kind, name: None, params: Vec::new(), defaults: Vec::new(), rest, body, strict: true, generator: false, span, home: true }; + let function = Function { + kind, + name: None, + params: Vec::new(), + defaults: Vec::new(), + rest, + body, + strict: true, + generator: false, + is_async: false, + span, + home: true, + }; self.ast.push_function(function) } @@ -2162,7 +2375,7 @@ impl<'s> Parser<'s> { let word = self.bump()?; if property_key(&self.tok).is_some() { let (key, _) = self.parse_property_key()?; - let function = self.parse_function_rest(kind, None, start, false)?; + let function = self.parse_function_rest(kind, None, start, false, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs index 5d186c9b11..0cfb20cce2 100644 --- a/crates/js/src/parser/module.rs +++ b/crates/js/src/parser/module.rs @@ -266,7 +266,10 @@ impl Parser<'_> { self.bump()?; return self.export_default(info, span).map(Some); } - let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some(); + let exportable = self.at_keyword(Keyword::Var) + || self.at_keyword(Keyword::Function) + || self.at_async_function() + || self.at_lexical_declaration().is_some(); if !exportable { return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok)))); } @@ -287,7 +290,7 @@ impl Parser<'_> { if self.at_keyword(Keyword::Class) { return Err(self.error_at_token(&self.tok, "classes are not supported")); } - if self.at_keyword(Keyword::Function) { + if self.at_keyword(Keyword::Function) || self.at_async_function() { self.enter()?; let result = self.default_function(); self.leave(); @@ -305,19 +308,22 @@ impl Parser<'_> { Ok(stmt) } - /// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of - /// `name`, or of [`DEFAULT_BINDING`] for a function without one. + /// `function name(…) {…}` or `function (…) {…}` after `export default`, either one optionally + /// `async`: a declaration of `name`, or of [`DEFAULT_BINDING`] for a function without one. fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> { + let is_async = self.at_async(); + let async_start = if is_async { Some(self.bump()?.span) } else { None }; let keyword = self.expect_keyword(Keyword::Function)?; - let start = keyword.span; - let generator = self.es2015 && self.eat(Punct::Star)?; + let start = async_start.unwrap_or(keyword.span); + // Async generators (ECMAScript 2018) stay syntax errors, as in a plain declaration. + let generator = !is_async && self.es2015 && self.eat(Punct::Star)?; let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name()? } else { (Name { name: DEFAULT_BINDING.into(), span: start }, keyword) }; let local = name.0.name.clone(); - let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?; + let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, is_async)?; let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start)); Ok((stmt, fid, local)) } @@ -410,6 +416,36 @@ mod tests { assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("true".into()))); } + #[test] + fn async_function_declarations_are_exported() { + let options = Options { es2015: true, es2017: true, ..Options::default() }; + let cases = [ + ("export async function f() {}", "f", "f"), + ("export default async function f() {}", "default", "f"), + ("export default async function () {}", "default", crate::ast::DEFAULT_BINDING), + ]; + for (source, export, binding) in cases { + let (program, info) = match parse_module(source, &options) { + Ok(parsed) => parsed, + Err(error) => panic!("{source}: {error:?}"), + }; + assert!( + matches!(info.exports.as_slice(), [crate::ExportEntry::Local { export_name, local, .. }] if export_name == export && local == binding), + "{source}: {:?}", + info.exports + ); + let declared = program.body.iter().any(|&stmt| match program.ast.stmt(stmt) { + Some(crate::ast::Stmt::FunctionDecl(fid)) => program.ast.function(*fid).is_some_and(|f| f.is_async), + _ => false, + }); + assert!(declared, "{source}: an async function declaration"); + } + // A line break after `async` ends the declaration; the export is then an expression. + assert!(parse_module("export async\nfunction f() {}", &options).is_err()); + // Without ES2017, `async` is an identifier and cannot start an exported declaration. + assert!(parse_module("export async function f() {}", &Options { es2015: true, ..Options::default() }).is_err()); + } + #[test] fn module_specifiers_reject_legacy_octal_escapes() { for source in diff --git a/crates/js/src/parser/pattern.rs b/crates/js/src/parser/pattern.rs index b25350549a..4bb126f8c2 100644 --- a/crates/js/src/parser/pattern.rs +++ b/crates/js/src/parser/pattern.rs @@ -149,7 +149,15 @@ impl Parser<'_> { // `*name(…) {…}`: a generator method (ECMA-262 2015 section 14.4). if self.eat(Punct::Star)? { let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; - let function = self.parse_function_with(FunctionKind::Method, None, start, true, true)?; + let function = self.parse_function_with(FunctionKind::Method, None, start, true, true, false)?; + return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); + } + // `async name(…) {…}` (ECMA-262 2017 section 14.6): an async method, with no line break + // after `async`. Async generator methods (ECMAScript 2018) stay syntax errors. + if self.at_async() && self.peek().is_some_and(|t| !t.newline_before && (property_key(&t).is_some() || t.is_punct(Punct::LBracket))) { + self.bump()?; + let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; + let function = self.parse_function_with(FunctionKind::Method, None, start, true, false, true)?; return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); } // `get` and `set` start an accessor only when written without escapes and followed by a @@ -165,7 +173,7 @@ impl Parser<'_> { self.bump()?; let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; // An accessor is a method, whose home object is the literal's object. - let function = self.parse_function_with(kind, None, start, true, false)?; + let function = self.parse_function_with(kind, None, start, true, false, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } @@ -178,6 +186,10 @@ impl Parser<'_> { { let name = name.clone(); self.check_identifier(&self.tok, &name)?; + // A shorthand `await` counts as one in an async arrow function's head, as a name does. + if name == "await" { + self.awaits = self.awaits.saturating_add(1); + } let token = self.bump()?; let target = self.ast.push_expr(Expr::Ident(name.clone()), token.span); let value = if self.at(Punct::Eq) { @@ -199,7 +211,7 @@ impl Parser<'_> { /// the value may still turn out to be a pattern. fn cover_property_value(&mut self, key: PropertyKey, start: Span) -> Result { if self.at(Punct::LParen) { - let function = self.parse_function_with(FunctionKind::Method, None, start, true, false)?; + let function = self.parse_function_with(FunctionKind::Method, None, start, true, false, false)?; return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); } self.expect(Punct::Colon)?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 1fbdb5c003..078175b562 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -167,7 +167,7 @@ fn a_promise_resolved_with_itself_rejects_with_a_type_error() { #[test] fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() { - let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\ + let src = "var bad = 0, seen = 0; function check(e) { seen++; if (!(e instanceof TypeError)) bad++; }\n\ for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }"; let mut finished = 0; for spare in (40_000..240_000).step_by(641) { @@ -181,6 +181,7 @@ fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() { } r.set_limits(Limits::default()); assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}"); + assert_eq!(r.run("seen"), Ok(JsValue::Number(200.0)), "{spare}"); } assert!(finished > 0); } @@ -193,6 +194,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { Promise.allSettled([Promise.reject('r'), 4]).then(function (v) { log.push(v[0].status + ':' + v[0].reason + ' ' + v[1].status + ':' + v[1].value); });\n\ Promise.race([new Promise(function () {}), Promise.resolve('fast')]).then(function (v) { log.push('race ' + v); });\n\ Promise.all('ab').then(function (v) { log.push('chars ' + v.length); });\n\ + Promise.all(new String('a\\uD83D\\uDE00')).then(function (v) { log.push('boxed ' + v.length + ' ' + v[1].length); });\n\ Promise.all(5).then(null, function (e) { log.push('not a list ' + (e instanceof TypeError)); });\n\ Promise.race(new Error('e')).then(null, function (e) { log.push('no length ' + (e instanceof TypeError)); });\n\ Promise.all({ length: 1.5 }).then(null, function (e) { log.push('bad length ' + (e instanceof TypeError)); });"; @@ -205,6 +207,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { "rejected:r fulfilled:4", "race fast", "chars 2", + "boxed 2 2", "not a list true", "no length true", "bad length true", diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index fcb103b50c..b9bf04e87a 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -421,11 +421,11 @@ impl Interp { /// non-configurable key of the target, and of a non-extensible target exactly its keys. Each /// key takes a unit of fuel and counts against the heap limit until the caller drops the list, /// which keeps the trap's order in [`HeldKeys::ordered`]. - pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult { + pub(crate) fn proxy_own_keys(&mut self, p: ObjId, ecma_order: bool) -> JsResult { self.proxy_op(p, "list the properties of", &[], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { // A target that is a proxy gives its Symbols with its names. - let mut keys = i.ecma_own_keys(target)?; + let mut keys = if ecma_order { i.ecma_own_keys(target)? } else { i.own_keys(target)? }; if !i.is_proxy(target) { keys.syms = i.own_symbols(target)?; keys.held.add(i, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?; @@ -441,12 +441,15 @@ impl Interp { } /// The object's own names and its own Symbols together, from a single [[OwnPropertyKeys]]: - /// one `ownKeys` trap call for a proxy. + /// one `ownKeys` trap call for a proxy. With [`crate::Options::es2015`] the names come in + /// ECMAScript order (array indices ascending first), through proxies without an `ownKeys` + /// trap too; without it they come in the order `for-in` visits them. pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult { + let ecma_order = self.options.es2015; if self.is_proxy(id) { - return self.proxy_own_keys(id); + return self.proxy_own_keys(id, ecma_order); } - let mut keys = self.own_keys(id)?; + let mut keys = if ecma_order { self.ecma_own_keys(id)? } else { self.own_keys(id)? }; keys.syms = self.own_symbols(id)?; keys.held.add(self, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?; Ok(keys) diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 0bbe6e0b02..aa64eb6b8e 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -626,6 +626,43 @@ fn reflect_methods_answer_with_booleans_and_receivers() { ); } +#[test] +fn reflect_keeps_symbol_keys_as_symbols() { + truth( + "var s = Symbol('x'), o = { a: 1 }; o[s] = 7; + var read = Reflect.get(o, s) === 7 && Reflect.has(o, s) && !Reflect.has(o, Symbol('x')) + && Reflect.getOwnPropertyDescriptor(o, s).value === 7; + var written = Reflect.set(o, s, 8) && o[s] === 8; + var r = {}, base = {}; Object.defineProperty(base, s, { value: 1, writable: true }); + var received = Reflect.set(base, s, 2, r) && r[s] === 2 && base[s] === 1; + var fixed = {}; Object.defineProperty(fixed, s, { value: 1 }); + var refused = !Reflect.set(fixed, s, 2) && !Reflect.deleteProperty(fixed, s); + var t = Symbol('t'), defined = Reflect.defineProperty(o, t, { value: 3, configurable: true }) && o[t] === 3; + var deleted = Reflect.deleteProperty(o, t) && !(t in o) && o['Symbol(t)'] === undefined; + var keys = Reflect.ownKeys(o); + read && written && received && refused && defined && deleted && keys.length === 2 && keys[0] === 'a' && keys[1] === s", + ); + // A proxy's Symbol keys are its target's. + truth( + "var s = Symbol('x'), t = { a: 1 }; t[s] = 1; + var keys = Reflect.ownKeys(new Proxy(t, {})); + keys.length === 2 && keys[0] === 'a' && keys[1] === s", + ); +} + +#[test] +fn a_subclassable_built_in_runs_the_outer_get_trap_of_a_new_target_whose_inner_proxy_is_revoked() { + // The outer trap runs; its invariant check then reads the revoked target and throws + // (ECMA-262 2020 section 9.5.8, step 9). + truth( + "class DerivedArray extends Array {} + var P = {}, inner = Proxy.revocable(function () {}, {}), reads = 0; + var outer = new Proxy(inner.proxy, { get: function (t, k) { if (k === 'prototype') { reads++; return P; } } }); + inner.revoke(); + type_error(function () { Reflect.construct(DerivedArray, [], outer); }) && reads === 1", + ); +} + #[test] fn reflect_construct_gives_a_built_in_object_the_prototype_of_new_target() { truth( @@ -707,6 +744,184 @@ fn a_descriptor_a_trap_makes_stays_reachable_while_it_is_read() { // ---- proxies elsewhere in the language ---- +#[test] +fn proxy_with_bindings_honor_unscopables() { + truth_collecting( + "var x = 'outer', result, log = [], scope, blocked; + var p = new Proxy({ x: 'inner' }, { + has: function (t, k) { if (k === 'x') log.push('has'); return Reflect.has(t, k); }, + get: function (t, k, r) { + if (k === Symbol.unscopables) { + scope = r; + return new Proxy({ x: true }, { get: function (t, k, r) { + log.push(k); blocked = r; return t[k]; + } }); + } + throw 'unexpected binding read'; + } + }); + with (p) { result = x; } + result === 'outer' && scope === p && typeof blocked === 'object' && log.join() === 'has,x'", + ); + for blocked in ["undefined", "null", "false", "1", "{}", "{ x: false }"] { + truth(&format!( + "var x = 'outer', result, t = {{ x: 'inner' }}; + t[Symbol.unscopables] = {blocked}; + with (new Proxy(t, {{}})) {{ result = x; }} + result === 'inner'" + )); + } + truth( + "var x = 'outer', kind, result, t = { x: 'inner' }; + t[Symbol.unscopables] = { x: true }; + with (new Proxy(t, {})) { x = 'changed'; kind = typeof x; result = delete x; } + x === 'changed' && t.x === 'inner' && kind === 'string' && result === false", + ); + for trap in ["return new Proxy({}, { get: function () { throw marker; } });", "throw marker;"] { + truth(&format!( + "var marker = {{}}, caught = false; + var p = new Proxy({{ x: 1 }}, {{ get: function (t, k) {{ + if (k === Symbol.unscopables) {{ {trap} }} return t[k]; + }} }}); + try {{ with (p) {{ x; }} }} catch (e) {{ caught = e === marker; }} + caught" + )); + } + let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()); + assert_eq!( + realm.run( + "function method() { return 'outer'; } + var t = { method: function () { return 'inner'; } }, result; + t[Symbol.unscopables] = { method: true }; + with (new Proxy(t, {})) { result = method(); } + result === 'outer'" + ), + Ok(JsValue::Bool(true)) + ); +} + +#[test] +fn transparent_proxies_preserve_object_key_order() { + truth_collecting( + "var o = { z: 0, 10: 10, 2: 2, a: 1 }, a = [1, 2]; a.label = 'a'; + [o, a].every(function (target) { + var p = new Proxy(new Proxy(target, {}), {}); + return Object.keys(p).join() === Object.keys(target).join() && + Object.getOwnPropertyNames(p).join() === Object.getOwnPropertyNames(target).join() && + Reflect.ownKeys(p).join() === Reflect.ownKeys(target).join(); + })", + ); + truth( + "var calls = 0, p = new Proxy({ a: 1, b: 2 }, { ownKeys: function () { calls++; return ['b', 'a']; } }); + var q = new Proxy(p, {}); + Object.keys(q).join() === 'b,a' && Object.getOwnPropertyNames(q).join() === 'b,a' && + Reflect.ownKeys(q).join() === 'b,a' && calls === 3", + ); +} + +#[test] +fn concat_honors_proxy_spreadability_overrides() { + truth_collecting( + "var reads = 0, receiver, p = new Proxy([1, 2], { get: function (t, k, r) { + if (k === Symbol.isConcatSpreadable) { reads++; receiver = r; return false; } + return Reflect.get(t, k, r); + } }); + var a = [].concat(p), b = p.concat(3); + a.length === 1 && a[0] === p && b.length === 2 && b[0] === p && b[1] === 3 && reads === 2 && receiver === p", + ); + truth_collecting( + "var reads = [], receiver; + var p = new Proxy({ 0: 'a', 2: 'c', length: 3 }, { get: function (t, k, r) { + if (k === Symbol.isConcatSpreadable) { reads.push('spread'); receiver = r; return true; } + reads.push(k); return Reflect.get(t, k, r); + } }); + var a = [].concat(p); + a.length === 3 && a[0] === 'a' && !(1 in a) && a[2] === 'c' && receiver === p && reads.join() === 'spread,length,0,2'", + ); + truth( + "var p = new Proxy([1, 2], {}), t = [3, 4]; t[Symbol.isConcatSpreadable] = null; + var q = new Proxy(t, {}), a = [].concat(p, q); + a.length === 3 && a[0] === 1 && a[1] === 2 && a[2] === q", + ); + truth( + "var marker = {}, caught = false; + var p = new Proxy([], { get: function (t, k) { if (k === Symbol.isConcatSpreadable) throw marker; return t[k]; } }); + try { [].concat(p); } catch (e) { caught = e === marker; } + caught", + ); + type_errors(&["var p = Proxy.revocable([], {}); p.revoke(); [].concat(p.proxy)"]); +} + +#[test] +fn spreadability_and_unscopables_kept_from_an_earlier_run_apply_only_with_the_option() { + let mut realm = es(); + let setup = "var a = [1, 2]; a[Symbol.isConcatSpreadable] = false; + var o = { x: 'own' }; o[Symbol.unscopables] = { x: true }; var x = 'outer'; true"; + assert_eq!(realm.run(setup), Ok(JsValue::Bool(true))); + realm.set_es2015(false); + assert_eq!(realm.run("var c = [].concat(a), w; with (o) { w = x; } c.length === 2 && c[0] === 1 && w === 'own'"), Ok(JsValue::Bool(true))); + realm.set_es2015(true); + assert_eq!(realm.run("var c = [].concat(a), w; with (o) { w = x; } c.length === 1 && c[0] === a && w === 'outer'"), Ok(JsValue::Bool(true))); +} + +#[test] +fn define_properties_defines_array_index_keys_in_ascending_order() { + truth( + "var log = [], bag = {}; bag.b = { value: 0 }; bag[2] = { value: 2 }; bag[1] = { value: 1 }; + var p = new Proxy({}, { defineProperty: function (t, k, d) { log.push(k); return Reflect.defineProperty(t, k, d); } }); + Object.defineProperties(p, bag); + var wrapped = [], q = new Proxy({}, { defineProperty: function (t, k, d) { wrapped.push(k); return Reflect.defineProperty(t, k, d); } }); + Object.defineProperties(q, new Proxy(bag, {})); + log.join() === '1,2,b' && wrapped.join() === '1,2,b'", + ); + // Without the option, descriptors are read in the order for-in visits the names. + let mut realm = Realm::new(); + let src = "var order = [], bag = {}; bag.b = 0; bag[2] = 0; bag[1] = 0; + var seen = [], descs = {}; + for (var k in bag) { order.push(k); (function (k) { Object.defineProperty(descs, k, { enumerable: true, get: function () { seen.push(k); return { value: 0 }; } }); })(k); } + Object.defineProperties({}, descs); + seen.join() === order.join()"; + assert_eq!(realm.run(src), Ok(JsValue::Bool(true))); +} + +#[test] +fn typed_array_statics_construct_through_proxy_receivers() { + truth_collecting( + "var p = new Proxy(Uint8Array, {}), a = p.of(257, 2), b = p.from([3, 260]); + a instanceof Uint8Array && a.length === 2 && a[0] === 1 && a[1] === 2 && + b instanceof Uint8Array && b.length === 2 && b[0] === 3 && b[1] === 4", + ); + truth_collecting( + "var calls = [], receiver, context = { add: 1 }; + var p = new Proxy(Uint8Array, { construct: function (t, args, nt) { + calls.push(t === Uint8Array, args.length, args[0], nt === p); + return new Uint16Array(args[0]); + } }); + var a = p.of(257, 2), b = p.from({ 0: 300, length: 1 }, function (v, i) { receiver = this; return v + i + this.add; }, context); + a instanceof Uint16Array && a[0] === 257 && a[1] === 2 && b instanceof Uint16Array && b[0] === 301 && + receiver === context && calls.join() === 'true,1,2,true,true,1,1,true'", + ); + for method in ["of(1, 2)", "from([1, 2])"] { + for result in ["{}", "new Uint8Array(1)", "new Proxy(new Uint8Array(2), {})"] { + truth(&format!( + "var p = new Proxy(Uint8Array, {{ construct: function () {{ return {result}; }} }}); + type_error(function () {{ p.{method}; }})" + )); + } + truth(&format!( + "var marker = {{}}, caught = false; + var p = new Proxy(Uint8Array, {{ construct: function () {{ throw marker; }} }}); + try {{ p.{method}; }} catch (e) {{ caught = e === marker; }} + caught" + )); + } + truth( + "var pair = Proxy.revocable(Uint8Array, {}), p = pair.proxy; + pair.revoke(); + type_error(function () { Uint8Array.of.call(p, 1); }) && type_error(function () { Uint8Array.from.call(p, [1]); })", + ); +} + #[test] fn a_proxy_works_as_a_prototype_and_a_with_scope() { truth( @@ -732,21 +947,27 @@ fn a_proxy_works_as_a_prototype_and_a_with_scope() { fn typeof_reads_the_binding_a_with_scope_reported_once() { // GetBindingValue asks `has` again, and a binding gone by then reads as undefined without `get`. truth( - "var asked = 0, got = 0; + "var asked = 0, got = 0, unscopables = 0; var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, - get: function (t, k) { got++; return k === 'x' ? function () {} : undefined; } }); + get: function (t, k) { + if (k === Symbol.unscopables) { unscopables++; return undefined; } + got++; return k === 'x' ? function () {} : undefined; + } }); var r; with (p) { r = typeof x; } - r === 'undefined' && asked === 2 && got === 0", + r === 'undefined' && asked === 2 && got === 0 && unscopables === 1", ); // A plain read of the same binding takes the same path. truth( - "var asked = 0, got = 0; + "var asked = 0, got = 0, unscopables = 0; var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, - get: function (t, k) { got++; return 1; } }); + get: function (t, k) { + if (k === Symbol.unscopables) { unscopables++; return undefined; } + got++; return 1; + } }); var r; with (p) { r = x; } - r === undefined && asked === 2 && got === 0", + r === undefined && asked === 2 && got === 0 && unscopables === 1", ); } @@ -755,15 +976,19 @@ fn e4x_bare_calls_resolve_proxy_scopes_once() { for present in ["asked++ < 2", "asked++ === 0", "false"] { let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()); let src = format!( - "var asked = 0, got = 0, outer = 0, receiver; + "var asked = 0, got = 0, outer = 0, unscopables = 0, receiver; function method() {{ outer++; return 'outer'; }} var p = new Proxy({{}}, {{ has: function (t, k) {{ return k === 'method' && ({present}); }}, - get: function () {{ got++; return function () {{ receiver = this; return 'proxy'; }}; }} + get: function (t, k) {{ + if (k === Symbol.unscopables) {{ unscopables++; return undefined; }} + got++; return function () {{ receiver = this; return 'proxy'; }}; + }} }}); var result, caught = false; try {{ with (p) {{ result = method(); }} }} catch (e) {{ caught = e instanceof TypeError; }} - {expected}", + ({expected}) && unscopables === {unscopables}", + unscopables = usize::from(present != "false"), expected = match present { "asked++ < 2" => "result === 'proxy' && receiver === p && asked === 2 && got === 1 && outer === 0 && !caught", "asked++ === 0" => "caught && asked === 2 && got === 0 && outer === 0", @@ -779,16 +1004,21 @@ fn e4x_bare_calls_resolve_proxy_scopes_once() { #[test] fn concat_proxy_array_lengths_use_to_length() { truth( - "var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0; + "var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0, spreadReads = 0; var empty = lengths.every(function (length) { var p = new Proxy([7], { - get: function (t, k) { if (k === 'length') return length; reads++; return t[k]; }, + get: function (t, k) { + if (k === Symbol.isConcatSpreadable) { spreadReads++; return undefined; } + if (k === 'length') return length; + reads++; return t[k]; + }, has: function () { reads++; return true; } }); return [3].concat(new Proxy(p, {}), 9).join() === '3,9'; }); var p = new Proxy([7, 8], { get: function (t, k) { return k === 'length' ? '1.9' : t[k]; } }); - empty && reads === 0 && [].concat(p).join() === '7' && Array.prototype.concat.call(p, 9).join() === '7,9'", + empty && reads === 0 && spreadReads === lengths.length && + [].concat(p).join() === '7' && Array.prototype.concat.call(p, 9).join() === '7,9'", ); } @@ -818,7 +1048,11 @@ fn concat_and_reviver_proxy_lengths_check_limits_before_reading_elements() { for length in ["4294967296", "Infinity"] { let setup = format!( "var p = new Proxy([], {{ - get: function (t, k) {{ if (k === 'length') return {length}; throw new Error('element read'); }}, + get: function (t, k) {{ + if (k === Symbol.isConcatSpreadable) return undefined; + if (k === 'length') return {length}; + throw new Error('element read'); + }}, has: function () {{ throw new Error('element checked'); }} }});" ); @@ -1129,6 +1363,23 @@ fn a_typed_array_receiver_converts_the_value_for_an_index_it_lacks() { ); } +#[test] +fn symbol_keys_pass_through_a_proxy_to_its_target() { + truth( + "var s = Symbol('x'), t = {}, p = new Proxy(t, {}); + Object.defineProperty(p, s, { value: 7, writable: true, configurable: true }); + var defined = t[s] === 7 && p[s] === 7 && Object.getOwnPropertySymbols(p)[0] === s; + p[s] = 8; + var written = t[s] === 8; + delete p[s]; + var self = null, u = {}; Object.defineProperty(u, s, { set: function () { self = this; } }); + var q = new Proxy(u, {}); q[s] = 1; + defined && written && !(s in t) && self === q && type_error(function () { + var pair = Proxy.revocable({}, {}); pair.revoke(); Object.defineProperty(pair.proxy, s, { value: 1 }); + })", + ); +} + fn namespace_script(source: &str) -> Realm { let mut realm = es(); assert!(realm.run("var out = false;").is_ok()); @@ -1308,12 +1559,23 @@ fn a_host_function_refuses_a_proxy_and_names_the_argument() { } } assert!(seen.borrow().is_empty(), "the host function did not run"); - // The traps did not run either. + // The same argument with a trap is refused too, before the host function or the trap runs. let mut realm = es(); - let f: HostFunction = Rc::new(|_| Ok(Data::Undefined)); + let calls = Rc::new(RefCell::new(0usize)); + let counter = calls.clone(); + let f: HostFunction = Rc::new(move |_| { + *counter.borrow_mut() += 1; + Ok(Data::Undefined) + }); realm.define_host_object("host", vec![("take".into(), HostItem::Function(f))]).unwrap(); - let r = realm.run("var ran = false; try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); } catch (e) {} ran"); - assert_eq!(r, Ok(JsValue::Bool(false))); + let r = realm.run( + "var ran = false, threw = false; + try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); } + catch (e) { threw = e instanceof TypeError; } + threw && !ran", + ); + assert_eq!(r, Ok(JsValue::Bool(true))); + assert_eq!(*calls.borrow(), 0, "the host function did not run"); } #[test] @@ -1703,6 +1965,19 @@ fn legacy_reflection_rejects_proxy_receivers_without_enumerating_them() { assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); } +#[test] +fn legacy_reflect_find_reads_a_proxy_receiver_without_its_traps() { + let mut realm = es(); + realm.add_script_extensions().unwrap(); + let src = format!( + "{PRELUDE} + var r = ({{ a: 1 }}).reflect, find = r.find, calls = 0; + var p = new Proxy(r, {{ getOwnPropertyDescriptor: function (t, k) {{ calls++; return Object.getOwnPropertyDescriptor(t, k); }} }}); + find.call(r, 'a') !== null && type_error(function () {{ find.call(p, 'a'); }}) && calls === 0" + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); +} + #[test] fn transparent_proxy_and_reflect_membership_use_host_indexers() { let index: HostFunction = Rc::new(|args| { @@ -1854,6 +2129,131 @@ fn for_in_asks_only_the_proxies_that_listed_a_name() { ); } +#[test] +fn for_in_visits_a_name_from_a_prototype_trap_that_returns_a_new_proxy_each_time() { + // Each [[GetPrototypeOf]] gives a new proxy of `t`: the one asked before each name is not the + // one whose ownKeys listed it. + truth_collecting( + "var t = { a: 1, b: 2 }; + var o = new Proxy({}, { ownKeys: function () { return []; }, getPrototypeOf: function () { return new Proxy(t, {}); } }); + var seen = []; + for (var name in o) seen.push(name); + seen.join() === 'a,b'", + ); + // A non-enumerable descriptor from such a proxy still does not hide a name further on. + truth( + "var c = { x: 1 }; + var o = new Proxy({}, { + ownKeys: function () { return []; }, + getPrototypeOf: function () { + return new Proxy({}, { + ownKeys: function () { return []; }, + getOwnPropertyDescriptor: function () { return { value: 0, enumerable: false, configurable: true }; }, + getPrototypeOf: function () { return c; } + }); + } + }); + var seen = []; + for (var name in o) seen.push(name); + seen.join() === 'x'", + ); + // Two proxies of one target on the chain: the one that listed nothing does not decide for the + // one that listed `x`. + truth( + "var t = {}; + var b = new Proxy(t, { + ownKeys: function () { return ['x']; }, + getOwnPropertyDescriptor: function () { return { value: 1, enumerable: true, configurable: true }; } + }); + var a = new Proxy(t, { + ownKeys: function () { return []; }, + getOwnPropertyDescriptor: function () { return { value: 0, enumerable: false, configurable: true }; }, + getPrototypeOf: function () { return b; } + }); + var seen = []; + for (var name in a) seen.push(name); + seen.join() === 'x'", + ); +} + +#[test] +fn for_in_keeps_the_names_a_proxy_listed_before_it_returns_itself_as_its_prototype() { + // The first visit lists `x`; the proxy is its own prototype once, and the second visit lists + // nothing. The name from the first visit is still visited. + truth( + "var keysCalls = 0, protoCalls = 0; + var p = new Proxy({}, { + ownKeys: function () { return keysCalls++ === 0 ? ['x'] : []; }, + getOwnPropertyDescriptor: function () { return { value: 1, enumerable: true, configurable: true }; }, + getPrototypeOf: function () { return protoCalls++ === 0 ? p : null; } + }); + var seen = []; + for (var name in p) seen.push(name); + seen.join() === 'x'", + ); +} + +#[test] +fn for_in_matches_nested_fresh_wrappers_to_their_prototype_lookups() { + truth_collecting( + "var t = { a: 1, b: 2 }, middle = {}; + var handler = { + ownKeys: function () { return []; }, + getPrototypeOf: function () { return new Proxy(t, {}); } + }; + var o = new Proxy({}, { + ownKeys: function () { return []; }, + getPrototypeOf: function () { return new Proxy(middle, handler); } + }); + var seen = []; + for (var name in o) seen.push(name); + seen.join() === 'a,b'", + ); +} + +#[test] +fn for_in_does_not_ask_an_inserted_proxy_of_a_listing_proxys_target() { + truth_collecting( + "var t = { a: 1, b: 2 }, reads = 0; + var listed = new Proxy(t, {}); + var o = Object.create(listed), seen = []; + for (var name in o) { + seen.push(name); + if (name === 'a') { + Object.setPrototypeOf(o, new Proxy(t, { + getOwnPropertyDescriptor: function () { + reads++; + return { value: 0, enumerable: false, configurable: true }; + }, + getPrototypeOf: function () { return listed; } + })); + } + } + seen.join() === 'a,b' && reads === 0", + ); +} + +#[test] +fn for_in_walks_many_empty_proxies_before_inherited_names() { + truth( + "var base = {}, depth = 256, count = 32, walks = 0, reads = 0; + for (var i = 0; i < count; i++) base['key' + i] = i; + function wrap(next) { + return new Proxy({}, { + ownKeys: function () { return []; }, + getOwnPropertyDescriptor: function () { reads++; return undefined; }, + getPrototypeOf: function () { walks++; return next; } + }); + } + var o = base; + for (var j = 0; j < depth; j++) o = wrap(o); + var seen = []; + for (var name in o) seen.push(name); + seen.length === count && seen.every(function (name, index) { return name === 'key' + index; }) && + reads === 0 && walks === depth * (count + 1)", + ); +} + #[test] fn for_in_reaches_a_name_past_a_typed_array_without_that_element() { truth( @@ -1982,6 +2382,14 @@ fn json_proxy_replacer_lengths_use_to_length() { ); } +#[test] +fn json_replacer_lists_charge_only_the_names_they_keep() { + // A long, sparse replacer array keeps one name, so only that name counts against the heap. + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let src = "var r = ['a']; r.length = 50000; JSON.stringify({ a: 1, b: 2 }, r) === '{\"a\":1}'"; + assert_eq!(Realm::with_options(es_options(), limits).run(src), Ok(JsValue::Bool(true))); +} + #[test] fn json_proxy_lengths_check_limits_before_reading_elements() { for length in ["4294967296", "Infinity"] { @@ -2007,13 +2415,19 @@ fn json_proxy_lengths_check_limits_before_reading_elements() { ), LimitKind::Fuel ); + // A replacer list's length alone is not charged to the heap; the names it keeps are. let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!( + Realm::with_options(es_options(), limits.clone()).run( + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : undefined; } }); + JSON.stringify({ a: 1 }, p) === '{}'" + ), + Ok(JsValue::Bool(true)) + ); assert_eq!( limit( - "var p = new Proxy([], { get: function (t, k) { - if (k === 'length') return 1000000; - throw new Error('element read'); - } }); JSON.stringify({}, p)", + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : 'name' + k; } }); + JSON.stringify({}, p)", limits, ), LimitKind::Heap @@ -2023,17 +2437,123 @@ fn json_proxy_lengths_check_limits_before_reading_elements() { #[test] fn transparent_proxies_construct_bound_builtins_without_allowing_subclasses() { truth( - "var B = Map.bind(null, [[1, 7]]), P = new Proxy(B, {}), Q = new Proxy(P, {}); + "var B = Map.bind(null, [[1, 7]]), proto = Object.create(Map.prototype); + Object.defineProperty(B, 'prototype', { value: proto }); + var P = new Proxy(B, {}), Q = new Proxy(P, {}); var a = new P(), b = new Q(), c = Reflect.construct(Q, []); var R = new Proxy(Q.bind(null), {}), d = new R(); var U = new Proxy(Uint8Array.bind(null, [7, 8]), {}), u = new U(); - Object.defineProperty(B, 'prototype', { value: Map.prototype }); a.get(1) === 7 && b.get(1) === 7 && c.get(1) === 7 && d.get(1) === 7 && - Object.getPrototypeOf(a) === Map.prototype && u.length === 2 && u[1] === 8 && + Object.getPrototypeOf(a) === proto && Object.getPrototypeOf(b) === proto && Object.getPrototypeOf(c) === proto && + Object.getPrototypeOf(d) === Map.prototype && u.length === 2 && u[1] === 8 && type_error(function () { class Child extends P {} new Child(); })", ); } +#[test] +fn own_keys_traps_may_give_symbols_and_keep_the_symbol_invariants() { + truth( + "var s = Symbol('s'), hidden = Symbol('h'), t = {}; t[hidden] = 1; + var calls = 0; + var open = new Proxy(t, { ownKeys: function () { calls++; return ['a', s]; } }); + var listed = Reflect.ownKeys(open); + var syms = Object.getOwnPropertySymbols(open); + listed.length === 2 && listed[0] === 'a' && listed[1] === s && syms.length === 1 && syms[0] === s && calls === 2", + ); + truth( + "var s = Symbol('s'); + var mixed = Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [s, 'a', 'b']; } })); + mixed.length === 3 && mixed[0] === s && mixed[1] === 'a' && mixed[2] === 'b'", + ); + type_errors(&[ + "var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return []; } }))", + "var s = Symbol('s'); Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [s, s]; } }))", + "var s = Symbol('s'); Reflect.ownKeys(new Proxy(Object.preventExtensions({}), { ownKeys: function () { return [s]; } }))", + "Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [1]; } }))", + ]); + truth( + "var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return [s]; } })).length === 1", + ); +} + +#[test] +fn own_keys_checks_target_descriptors_in_combined_key_order() { + truth( + "var s = Symbol('s'), u = Symbol('u'), t = { a: 1, b: 2 }; + t[s] = 3; t[u] = 4; + var reads = [], extensible = 0; + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a', u, 'b']; }, + isExtensible: function () { extensible++; return true; }, + getOwnPropertyDescriptor: function (t, k) { + reads.push(String(k)); + if (k === s) Object.defineProperty(t, u, { configurable: false }); + return Object.getOwnPropertyDescriptor(t, k); + } + }); + // The descriptor of `s`, read first, makes `u` non-configurable before `u` is read, so the + // outer trap that leaves `u` out breaks the invariant. + var threw = type_error(function () { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', 'a', s]; } })); }); + var ok = Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', u, 'a']; } })); + threw && reads.slice(0, 4).join() === 'Symbol(s),a,Symbol(u),b' && extensible === 2 && ok.length === 3", + ); + truth( + "var s = Symbol('s'), t = { a: 1 }, marker = {}; + Object.defineProperty(t, s, { value: 2 }); + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a']; }, + getOwnPropertyDescriptor: function () { throw marker; } + }); + var caught; + try { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return []; } })); } + catch (e) { caught = e; } + caught === marker", + ); +} + +#[test] +fn own_keys_consumers_keep_interleaved_trap_keys() { + truth( + "var s = Symbol('s'), u = Symbol('u'); + var p = new Proxy({}, { ownKeys: function () { return ['a', s, 'b', u, 'c']; } }); + var keys = Reflect.ownKeys(p); + keys.length === 5 && keys[0] === 'a' && keys[1] === s && keys[2] === 'b' && keys[3] === u && keys[4] === 'c'", + ); + truth( + "var s = Symbol('s'), t = { a: { value: 1 }, b: { value: 3 } }; + t[s] = { value: 2 }; + var order = []; + var props = new Proxy(t, { + ownKeys: function () { return ['a', s, 'b']; }, + get: function (t, k) { order.push(k); return t[k]; } + }); + var o = Object.defineProperties({}, props); + order.length === 3 && order[0] === 'a' && order[1] === s && order[2] === 'b' && o.a === 1 && o[s] === 2 && o.b === 3", + ); +} + +#[test] +fn symbol_reads_through_a_proxy_call_its_get_trap() { + truth( + "var s = Symbol('s'); var seen; + var p = new Proxy({}, { get: function (t, k, r) { seen = [k, r]; return 5; } }); + var child = Object.create(p); + p[s] === 5 && seen[0] === s && seen[1] === p && child[s] === 5 && seen[1] === child", + ); + truth( + "var s = Symbol('s'); var t = {}; t[s] = 3; + new Proxy(t, {})[s] === 3 && Object.create(new Proxy(t, {}))[s] === 3", + ); + type_errors(&["var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + new Proxy(t, { get: function () { return 2; } })[s]"]); + truth( + "var p = new Proxy({}, { get: function (t, k) { if (k === Symbol.toPrimitive) return function () { return 9; }; } }); + +p === 9", + ); +} + #[test] fn json_transparent_host_proxies_skip_indexers_but_call_get_traps() { let calls = Rc::new(RefCell::new(0)); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index fe92e15269..0254c2fb80 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -269,12 +269,34 @@ impl Realm { pub fn set_es2015(&mut self, es2015: bool) { if self.is_running() || self.interp.waiting { self.interp.next_es2015 = Some(es2015); + if !es2015 { + self.interp.next_es2017 = Some(false); + } } else { self.interp.next_es2015 = None; + self.interp.next_es2017 = None; self.interp.set_es2015(es2015); } } + /// Sets [`Options::es2017`] for the next runs, and for the code they evaluate; on, it also + /// sets [`Options::es2015`]. Async functions an earlier run made keep running when it is + /// turned off. Call [`Realm::add_es2015`] too in a realm made without either option, since + /// an async function needs `Promise`. Like [`Realm::set_es2015`], it applies once a run that + /// is still going ends. + pub fn set_es2017(&mut self, es2017: bool) { + if self.is_running() || self.interp.waiting { + self.interp.next_es2017 = Some(es2017); + if es2017 { + self.interp.next_es2015 = Some(true); + } + } else { + self.interp.next_es2015 = None; + self.interp.next_es2017 = None; + self.interp.set_es2017(es2017); + } + } + /// The realm's interrupt flag. Setting it stops a running script, or the next one to start. pub fn interrupt(&self) -> Interrupt { Interrupt(self.interp.interrupt.clone()) @@ -462,9 +484,12 @@ impl Realm { if let Some(es2015) = interp.next_es2015.take() { interp.set_es2015(es2015); } + if let Some(es2017) = interp.next_es2017.take() { + interp.set_es2017(es2017); + } match result { Ok(v) => { - self.rejections = interp.take_unhandled(); + self.rejections = interp.unhandled(); Ok(interp.to_js_value(&v)) } Err(Abrupt::Throw(v)) => { @@ -730,6 +755,53 @@ impl Realm { } } + /// Gives the host's `paletteUpdate` the controls of each ScriptUI palette this realm keeps, as + /// the run that just ended left them; nothing when it keeps none. A getter it reads runs in the + /// run's fuel, at most [`Realm::set_unbroken_fuel`] of it, as a nested run that cannot pause + /// does; what it throws ends the run. The promise jobs a getter queues run in the same fuel, + /// and the host then gets the controls once more ([`crate::scriptui::refresh`]). The run's + /// report of unhandled rejections ([`Realm::unhandled_rejections`]) is then made again: it + /// takes in the rejections of those jobs and leaves out a run's rejection that a getter or a + /// job gave a handler. + pub fn refresh_script_ui(&mut self) -> Result<(), RunError> { + let interp = &mut self.interp; + let total = interp.fuel; + let cap = self.unbroken_fuel.min(total); + interp.fuel = cap; + let r = crate::scriptui::refresh(interp); + let used = cap - interp.fuel; + interp.fuel = total - used; + match r { + Ok(()) => { + self.rejections = self.interp.unhandled(); + Ok(()) + } + // A refresh that fails reports no rejection, as after any failed run. + Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => { + self.rejections = (Vec::new(), 0); + self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop) + } + Err(e) => { + self.rejections = (Vec::new(), 0); + self.outcome(Err(e)).map(drop) + } + } + } + + /// [`Realm::refresh_script_ui`] after a run that failed: what the refresh throws is dropped, + /// and the run's error keeps its place ([`Realm::error_source`], [`Realm::error_mark`]) and + /// its thrown value. The report of unhandled rejections stays empty, as after any failed run. + pub fn refresh_script_ui_after_error(&mut self) { + let (tag, mark) = (self.interp.error_tag, self.interp.error_mark); + let thrown = self.interp.last_thrown.clone(); + let rejections = std::mem::take(&mut self.rejections); + let _ = self.refresh_script_ui(); + self.interp.error_tag = tag; + self.interp.error_mark = mark; + self.interp.last_thrown = thrown; + self.rejections = rejections; + } + /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs index 62c63c6bb0..2949ccba0c 100644 --- a/crates/js/src/reflect.rs +++ b/crates/js/src/reflect.rs @@ -328,15 +328,17 @@ fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult flat_charged(interp, &s)?, Some(Prop::Data { value: Value::Number(n), .. }) => flat_charged(interp, &number_to_str(n))?, _ => continue, diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 80982a48ce..8864fc1911 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -2,8 +2,9 @@ //! describes it, whose //! drawing a host does ([`crate::Realm::define_script_ui`]). //! -//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`. A -//! window of type `palette` or `window` throws an `Error` that says it is not available yet. +//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`, and +//! `new Window("palette", ...)` a palette, once the host's `palette` allows it. A window of type +//! `window` throws an `Error` that says it is not available yet. //! `new Window` and `add` also take a resource specification in place of the type, as the help //! page //! describes it (read by [`crate::scriptui_resource`]), and then read no other argument: the @@ -12,7 +13,7 @@ //! assigned to the container's property of that name, a list's `items` gives its item texts as //! `add`'s third argument does, and each other value is assigned to the property of its name. A //! malformed specification throws a `SyntaxError`. `add(type[, bounds, text, properties])` adds a -//! control to a dialog, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, +//! control to a dialog, a palette, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, //! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item //! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum). //! The other documented control types throw an `Error` that says they are not available yet, and @@ -55,6 +56,27 @@ //! other dialog can be shown while one is. When `show()` ends, the host's `end` is given its result //! and whether it ended normally. //! +//! A palette's `show()` gives the host's `paletteShow` its description and its id (none the first +//! time), which gives back the id, then runs `onShow` and returns `undefined` without waiting. +//! `hide()` gives `paletteHide` the id, and `close()` runs `onClose`, and unless it returns `false` +//! gives `paletteClose` the id; a `close()` while `onClose` runs does nothing more. The realm keeps +//! each palette the host shows until it closes. `Window.__vcPaletteEvent()` takes an event from the +//! host's `paletteEvent` (`{palette, event, id, value, element}`, or `null`, with `element` the id +//! of the control), and gives it to that palette as a dialog takes one, without giving +//! `paletteUpdate` any description: the host gets the palettes' controls when the run ends +//! ([`crate::Realm::refresh_script_ui`]). `add()` on a shown palette gives `paletteUpdate` that +//! palette's description, so the host's list of its controls stays in step. +//! `update()` on a shown palette, or on a `group` or a `panel` in one, takes each event that waits +//! for a palette of the run's engine from the host's `paletteTake` (as `paletteEvent` gives it, or +//! `null`) and gives it to its palette, while the host's `palettePending` says one waits, giving +//! `paletteUpdate` each palette's description before each one. When a handler's exception ends +//! this, `update()` calls `palettePending` once more before the exception leaves it. Then, called from the script's own code (not from a +//! handler, a callback of a built-in function, a getter or a conversion), it asks the host's +//! `paletteDraw` whether the palette is drawn now, and when it is, gives `paletteUpdate` the +//! palette's description. On the showing dialog, or a group or panel in it, `update()` does +//! nothing more, and on a window that is not showing it throws an `Error`. A dialog takes the +//! person's events once the running handler returns. +//! //! An element keeps its kind, its container, its controls and a list's items in properties that a //! script cannot change. The description lists the dialog first and every control after the //! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] @@ -74,6 +96,10 @@ use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; use crate::scriptui_resource::{self, Fault, Res, Spec}; use crate::value::{Value, index_key}; +/// The global property, not an identifier, that the run of a palette's handler calls as +/// `this[PALETTE_EVENT_GLOBAL]()` to take its event ([`palette_event`]). +pub const PALETTE_EVENT_GLOBAL: &str = "%vcPaletteEvent"; + /// The most controls a dialog holds, its groups and panels included. pub const MAX_CONTROLS: usize = 512; /// How deeply controls nest in a dialog: a control the dialog holds is at depth 1. @@ -106,6 +132,15 @@ const ITEMS: &str = "__vcItems"; const ITEMS_REV: &str = "__vcItemsRev"; const SELECTION: &str = "__vcSelection"; const LIST: &str = "__vcList"; +const PALETTE_ID: &str = "__vcPaletteId"; +const SHOWN: &str = "__vcShown"; +const IN_CLOSE: &str = "__vcInClose"; +/// How many times a palette was hidden: an event it took before a hide is not its event after a +/// later `show()`. +const HIDES: &str = "__vcHides"; +/// How many times a list's items were added or removed: a palette's waiting change of the list is +/// for the items it had then. +const REVISION: &str = "__vcRevision"; const VALUE: &str = "__vcValue"; const LISTENERS: &str = "__vcListeners"; const STOPPED: &str = "__vcStopped"; @@ -143,7 +178,8 @@ const EVENTS_LATER: [&str; 14] = [ "keydown", ]; -/// The objects of `Window`, kept by the realm, and the dialog that is showing. +/// The objects of `Window`, kept by the realm, the dialog that is showing, and the palettes the +/// host shows, shown or hidden. #[derive(Clone, Debug)] pub(crate) struct Classes { window_proto: ObjId, @@ -157,6 +193,9 @@ pub(crate) struct Classes { radio_get: ObjId, radio_set: ObjId, showing: Option, + palettes: Vec, + /// Whether an `update()` is taking the waiting events ([`take_waiting`]). + taking: bool, /// The event objects whose listeners are running, innermost last. dispatching: Vec, /// The containers above the targets of the running events. @@ -181,12 +220,23 @@ impl Classes { self.radio_set, ]; all.extend(self.showing); + all.extend(self.palettes.iter().copied()); all.extend(self.dispatching.iter().copied()); all.extend(self.above.iter().copied()); all } } +/// Is `kind` a window's: a dialog's or a palette's? +fn is_window(kind: &str) -> bool { + kind == "dialog" || kind == "palette" +} + +/// Does `kind` hold controls? +fn is_container(kind: &str) -> bool { + is_window(kind) || kind == "group" || kind == "panel" +} + /// Forgets the dialog that was showing, and the events that were running, when a run ended where /// it was. pub(crate) fn end_run(i: &mut Interp) { @@ -443,7 +493,7 @@ fn new_element( let d = dimension(i, -1.0, -1.0)?; set_open(i, o, name, d)?; } - let container = matches!(kind, "dialog" | "group" | "panel"); + let container = is_container(kind); if container { let kids = list(i, &[], false)?; set_slot(i, o, KIDS, Value::Object(kids))?; @@ -481,12 +531,20 @@ fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let creation = creation_properties(i, spec)?; - new_element(i, proto, "dialog", None, None, 0, [&Value::Undefined, &Value::Undefined, &creation])? + new_element(i, proto, ty, None, None, 0, [&Value::Undefined, &Value::Undefined, &creation])? } - None => new_element(i, proto, "dialog", None, None, 0, [&arg(args, 2), &arg(args, 1), &arg(args, 3)])?, + None => new_element(i, proto, ty, None, None, 0, [&arg(args, 2), &arg(args, 1), &arg(args, 3)])?, }; set_slot(i, o, COUNT, Value::Number(0.0))?; set_slot(i, o, ITEM_COUNT, Value::Number(0.0))?; @@ -645,9 +703,13 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult if ty.to_lowercase() != "item" { return Err(error(i, "add: a list holds only items")); } - return add_item(i, o, &arg(args, 1)); + let item = add_item(i, o, &arg(args, 1))?; + if let Some(win) = object_slot(i, o, WINDOW)? { + i.rooted(std::slice::from_ref(&item), |i| publish_palette(i, win))?; + } + return Ok(item); } - if !matches!(kind.as_str(), "dialog" | "group" | "panel") { + if !is_container(&kind) { return Err(error(i, &format!("add: a {kind} holds no controls"))); } if is_resource(&ty) { @@ -774,6 +836,9 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult } let counts = vec![(win, COUNT, Value::Number(count + 1.0), 0), (win, ITEM_COUNT, Value::Number(items + staged as f64), 0)]; append(i, o, KIDS, "children", Value::Object(c), counts)?; + // The host's copy of a shown palette keeps each control's place in the list, which events + // name it by. + publish_palette(i, win)?; Ok(Value::Object(c)) })(); i.temp_roots.truncate(mark); @@ -803,6 +868,8 @@ fn new_item(i: &mut Interp, o: ObjId, text: Value, more: Vec>) -> JsRe i.rooted(&[Value::Object(item)], |i| { set_slot(i, item, LIST, Value::Object(o))?; set_open(i, item, "text", text.clone())?; + let mut more = more; + more.push((o, REVISION, Value::Number(number_slot(i, o, REVISION)? + 1.0), 0)); append(i, o, ITEMS, "items", Value::Object(item), more)?; Ok(Value::Object(item)) }) @@ -827,6 +894,9 @@ fn new_items(i: &mut Interp, o: ObjId, texts: &[Value]) -> JsResult { let kept = list(i, &items, false)?; i.temp_roots.push(Value::Object(kept)); set_items(i, o, kept)?; + // Each item counts as one change of the list's items ([`REVISION`]), as `add` counts it. + let revision = number_slot(i, o, REVISION)? + items.len() as f64; + set_slot(i, o, REVISION, Value::Number(revision))?; let copy = list(i, &items, true)?; set_open(i, o, "items", Value::Object(copy))?; Ok(items.len()) @@ -929,6 +999,7 @@ fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult, event: ObjId, phase: f64, cutoff: f64) -> JsResult { +/// `at` when the event started. None runs once the palette of `taker` no longer takes the event. +/// → whether it had any; `None` when the palette stopped taking the event. +fn run_listeners( + i: &mut Interp, + at: ObjId, + ty: &str, + capture: Option, + (event, phase, cutoff): (ObjId, f64, f64), + taker: Taker, +) -> JsResult> { let wanted = |i: &Interp| -> JsResult> { Ok(listeners_of(i, at)? .into_iter() @@ -1154,7 +1233,7 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve }; let first = wanted(i)?; if first.is_empty() { - return Ok(false); + return Ok(Some(false)); } let functions: Vec = first.iter().map(|(f, _)| f.clone()).collect(); i.rooted(&functions, |i| { @@ -1164,9 +1243,12 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve if !wanted(i)?.iter().any(|(_, m)| m == n) { continue; } + if !takes(i, taker)? { + return Ok(None); + } i.call(f, &Value::Object(at), &[Value::Object(event)])?; } - Ok(true) + Ok(Some(true)) }) } @@ -1177,6 +1259,45 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve /// do not capture do not count. A container that a listener took the element out of before its /// turn does not hear the event. fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult { + Ok(dispatch_for(i, target, ty, callback, None)?.unwrap_or(false)) +} + +/// The palette, the event it takes and the event's control, whose handlers run only while the +/// palette takes the event ([`still_takes`]) and holds the control; `None` for a dialog, which +/// always takes it. +type Taker = Option<(ObjId, ObjId, ObjId)>; + +/// Does the palette of `taker` still take its event and hold its control, with the control and +/// every container above it enabled and visible as they are now, read without running a getter +/// ([`plain_state`])? Always true for a dialog. +fn takes(i: &mut Interp, taker: Taker) -> JsResult { + match taker { + Some((win, ev, c)) => Ok(still_takes(i, win, ev, None)? && holds(i, win, c)? && live_up(i, win, c)?), + None => Ok(true), + } +} + +/// Whether `c` and each container above it, up to and including `top`, are enabled and visible, +/// read without running a getter ([`plain_state`]). +fn live_up(i: &Interp, top: ObjId, c: ObjId) -> JsResult { + let mut at = c; + for _ in 0..=MAX_DEPTH + 1 { + if !plain_state(i, at, "enabled")? || !plain_state(i, at, "visible")? { + return Ok(false); + } + if at == top { + return Ok(true); + } + let Some(p) = object_slot(i, at, PARENT)? else { return Ok(false) }; + at = p; + } + Ok(false) +} + +/// [`dispatch`] for the event a palette takes (`taker`): no handler or listener runs once a getter, +/// a handler or a listener of the event closed the palette or took the event's control out of it. +/// → `None` when that happened. +fn dispatch_for(i: &mut Interp, target: ObjId, ty: &str, callback: &str, taker: Taker) -> JsResult> { let above = containers_above(i, target)?; let proto = classes(i)?.event_proto; i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(10)))?; @@ -1191,7 +1312,7 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult } None => 0, }; - let r = run_event(i, event, target, &above, ty, callback); + let r = run_event(i, event, target, &above, ty, callback, taker); if let Some(c) = i.script_ui.as_mut() { if let Some(n) = c.dispatching.iter().rposition(|e| *e == event) { c.dispatching.remove(n); @@ -1217,8 +1338,8 @@ fn containers_above(i: &mut Interp, target: ObjId) -> JsResult> { Ok(above) } -/// The phases of [`dispatch`] for the event object `event`. -fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: &str, callback: &str) -> JsResult { +/// The phases of [`dispatch_for`] for the event object `event`. +fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: &str, callback: &str, taker: Taker) -> JsResult> { i.rooted(&[Value::Object(event)], |i| { let bubbles = ty != "show"; set_open(i, event, "type", Value::str(ty))?; @@ -1235,38 +1356,65 @@ fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: & if !containers_above(i, target)?.contains(p) { continue; } - run_listeners(i, *p, ty, Some(true), event, 1.0, *n)?; + if run_listeners(i, *p, ty, Some(true), (event, 1.0, *n), taker)?.is_none() { + return Ok(None); + } if stopped(i)? { - return Ok(true); + return Ok(Some(true)); } } - let had = handler(i, target, callback)?.is_some(); - let heard = run_listeners(i, target, ty, None, event, 2.0, target_cutoff)?; + if !takes(i, taker)? { + return Ok(None); + } + let f = i.get_value(&Value::Object(target), &key(callback))?; + // A getter for the callback may have closed the palette. + if !takes(i, taker)? { + return Ok(None); + } + let had = i.is_callable(&f); + if had { + i.call(&f, &Value::Object(target), &[])?; + } + if !takes(i, taker)? { + return Ok(None); + } + let Some(heard) = run_listeners(i, target, ty, None, (event, 2.0, target_cutoff), taker)? else { return Ok(None) }; if bubbles && !stopped(i)? { for (p, n) in above.iter().zip(&cutoffs) { if !containers_above(i, target)?.contains(p) { continue; } - run_listeners(i, *p, ty, Some(false), event, 3.0, *n)?; + if run_listeners(i, *p, ty, Some(false), (event, 3.0, *n), taker)?.is_none() { + return Ok(None); + } if stopped(i)? { break; } } } - Ok(had || heard) + Ok(Some(had || heard)) }) } /// A click on the control `c` of `kind`: a check box turns over and a radio button turns on, then /// the click runs. → whether the click was handled, as [`dispatch`] says. fn click_control(i: &mut Interp, c: ObjId, kind: &str) -> JsResult { + Ok(click_control_for(i, c, kind, None)?.unwrap_or(false)) +} + +/// [`click_control`] for the click a palette takes (`taker`), as [`dispatch_for`] runs it. +fn click_control_for(i: &mut Interp, c: ObjId, kind: &str, taker: Taker) -> JsResult> { if kind == "checkbox" { let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); + // A `value` getter may have disabled or hidden the box, or closed its palette. + if taker.is_some() && !takes(i, taker)? { + return Ok(None); + } i.put(c, key("value"), Value::Bool(!on), true)?; } else if kind == "radiobutton" { i.put(c, key("value"), Value::Bool(true), true)?; } - dispatch(i, c, "click", "onClick") + dispatch_for(i, c, "click", "onClick", taker) } /// `notify([event])`: simulates the control's `onClick`, `onChange` or `onChanging`. @@ -1384,12 +1532,14 @@ fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult JsResult { Ok(Value::Undefined) } -fn dialog_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { +/// `this` as a window, and whether it is a palette. +fn this_window(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, bool)> { match kind_of(i, this)? { - Some((o, kind)) if kind == "dialog" => Ok(o), + Some((o, kind)) if is_window(&kind) => Ok((o, kind == "palette")), _ => Err(i.type_error(&format!("{what}: this is not a ScriptUI window"))), } } -/// `close([result])`: closes the dialog that is showing once the running handler returns. +/// `close([result])`: closes the dialog that is showing once the running handler returns, or the +/// palette at once. fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let o = dialog_of(i, &this, "close")?; + let (o, palette) = this_window(i, &this, "close")?; let result = match arg(args, 0) { Value::Undefined => 0.0, v => number_arg(i, &v, "close: the result")?, }; - if classes(i)?.showing == Some(o) { + if palette { + close_palette(i, o)?; + } else if classes(i)?.showing == Some(o) { set_slot(i, o, CLOSING, Value::Number(result))?; } Ok(Value::Undefined) } -/// `hide()`: closes the dialog that is showing with the result 0. +/// `hide()`: closes the dialog that is showing with the result 0, or hides the palette, which a +/// later `show()` shows again as it was. A palette's `visible` is false once the host hid it, and +/// true again once the host shows it. fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - close(i, this, &[], false) + let (o, palette) = this_window(i, &this, "hide")?; + if !palette { + return close(i, this, &[], false); + } + if let Value::Number(id) = slot(i, o, PALETTE_ID)? { + let f = host_fn(i, "paletteHide")?; + i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + set_slot(i, o, SHOWN, Value::Bool(false))?; + let hides = number_slot(i, o, HIDES)? + 1.0; + set_slot(i, o, HIDES, Value::Number(hides))?; + i.put(o, key("visible"), Value::Bool(false), true)?; + } + Ok(Value::Undefined) +} + +/// `update()` on a window: [`update_window`]. +fn update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let own = own_code(i); + let (o, palette) = this_window(i, &this, "update")?; + update_window(i, o, palette, own)?; + Ok(Value::Undefined) +} + +/// Whether the native running now was called from the script's own code in a run that can pause, +/// as the host's functions find whether a run can wait. +fn own_code(i: &Interp) -> bool { + i.in_slice && i.reentry == 0 +} + +/// `update()` on a `group` or a `panel`: [`update_window`] for the window that holds it. +fn control_update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let own = own_code(i); + let (o, kind) = element(i, &this, "update")?; + if !is_container(&kind) { + return Err(i.type_error("update: this is not a ScriptUI window or container")); + } + let win = window_of(i, o, "update")?; + let palette = matches!(slot(i, win, KIND)?, Value::String(s) if s.to_rust_string() == "palette"); + update_window(i, win, palette, own)?; + Ok(Value::Undefined) +} + +/// `update()` on the window `win`. On a shown palette: hands each event that waits for a palette of +/// the run's engine to its palette ([`take_waiting`]), and then, from the script's own code (`own`), +/// gives the host the palette's controls when the host draws it now (`paletteDraw`). The showing +/// dialog's controls go to the host when its handler returns, since a handler runs to its end in +/// one slice. Whether a palette shows is the host's, not its `visible` property. A window that is +/// not showing throws. +fn update_window(i: &mut Interp, win: ObjId, palette: bool, own: bool) -> JsResult<()> { + let showing = if palette { slot(i, win, SHOWN)?.truthy() } else { classes(i)?.showing == Some(win) }; + if !showing { + return Err(error(i, "update: the window is not showing")); + } + if !palette { + return Ok(()); + } + take_waiting(i)?; + if !own || !slot(i, win, SHOWN)?.truthy() { + return Ok(()); + } + let f = host_fn(i, "paletteDraw")?; + if i.call(&f, &Value::Undefined, &[])?.truthy() { + update_palette(i, win)?; + } + Ok(()) +} + +/// Hands each event the host's `paletteTake` gives, oldest first, to its palette, until none waits +/// (`palettePending`). Before each one the host gets every palette's controls as the script and the +/// handlers before it left them, as at the end of a run, and drops an event whose control has since +/// been disabled, hidden or removed. An `update()` that a getter or a handler calls meanwhile takes +/// no events: the `update()` already taking them goes on with the next one. +fn take_waiting(i: &mut Interp) -> JsResult<()> { + if i.script_ui.as_ref().is_some_and(|c| c.taking) { + return Ok(()); + } + set_taking(i, true); + let r = take_each(i); + set_taking(i, false); + r +} + +fn set_taking(i: &mut Interp, taking: bool) { + if let Some(c) = i.script_ui.as_mut() { + c.taking = taking; + } +} + +/// [`take_waiting`]'s loop. +fn take_each(i: &mut Interp) -> JsResult<()> { + let pending = host_fn(i, "palettePending")?; + let f = host_fn(i, "paletteTake")?; + loop { + if !i.call(&pending, &Value::Undefined, &[])?.truthy() { + return Ok(()); + } + update_palettes(i)?; + let answer = i.call(&f, &Value::Undefined, &[])?; + if answer.as_object().is_none() { + return Ok(()); + } + if let Err(e) = deliver(i, answer) { + // The host learns that the event's handlers have ended, as it does before the next + // event, when a handler's exception ends the loop. + if let Abrupt::Throw(v) = &e { + let v = v.clone(); + let _ = i.rooted(std::slice::from_ref(&v), |i| i.call(&pending, &Value::Undefined, &[])); + } + return Err(e); + } + } +} + +fn set_palettes(i: &mut Interp, f: impl FnOnce(&mut Vec)) { + if let Some(c) = i.script_ui.as_mut() { + f(&mut c.palettes); + } +} + +/// Closes the palette `win` once its `onClose` allows it: the host no longer shows it, its +/// `visible` is false and its handlers no longer run. A `close()` while its `onClose` runs does +/// nothing more. +fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + if slot(i, win, IN_CLOSE)?.truthy() { + return Ok(()); + } + if !may_close(i, win)? { + return Ok(()); + } + if let Value::Number(id) = slot(i, win, PALETTE_ID)? { + set_slot(i, win, PALETTE_ID, Value::Undefined)?; + set_slot(i, win, SHOWN, Value::Bool(false))?; + set_palettes(i, |p| p.retain(|o| *o != win)); + let f = host_fn(i, "paletteClose")?; + i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + // The host has closed it; a `visible` the script made read-only stays as it is. + i.put(win, key("visible"), Value::Bool(false), false)?; + } + Ok(()) +} + +/// Gives the host the controls of the palette `win` as they are now, when it shows the palette. A +/// palette that `hide()` hid is not read: `show()` gives its controls when it shows it again. +fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + let Value::Number(id) = slot(i, win, PALETTE_ID)? else { return Ok(()) }; + if !slot(i, win, SHOWN)?.truthy() { + return Ok(()); + } + let (desc, ..) = describe(i, win)?; + let f = host_fn(i, "paletteUpdate")?; + i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?; + Ok(()) +} + +/// [`update_palette`] after an `add` or a `remove` that has already changed the palette: what a +/// getter throws while the palette is read does not take the place of the change's result. The +/// host gets the controls at the next update, or when the run ends ([`refresh`]). +fn publish_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + match update_palette(i, win) { + // The exception no longer propagates, so a later error is reported at its own place. + Err(Abrupt::Throw(_)) => { + i.passing = Value::Undefined; + i.thrown_mark = None; + i.throw_site = None; + Ok(()) + } + r => r, + } +} + +/// Gives the host the controls of every palette it shows, after a handler may have changed them. +fn update_palettes(i: &mut Interp) -> JsResult<()> { + // A getter may close a later palette, which removes it from the rooted list, so the copy is + // rooted until the loop ends. + let palettes = classes(i)?.palettes; + let roots: Vec = palettes.iter().map(|&win| Value::Object(win)).collect(); + i.rooted(&roots, |i| { + for win in palettes { + update_palette(i, win)?; + } + Ok(()) + }) +} + +/// Gives the host the controls of every palette the realm keeps, as a run left them +/// ([`crate::Realm::refresh_script_ui`]). When the getters queued promise jobs, the jobs run and +/// the host gets the controls once more, and the jobs that second pass queues run too. An +/// `update()` that a getter or a job calls meanwhile takes no waiting event, which waits for a run +/// of its own. +pub(crate) fn refresh(i: &mut Interp) -> JsResult<()> { + let was = i.script_ui.as_ref().is_some_and(|c| c.taking); + set_taking(i, true); + let r = (|| { + refresh_palettes(i)?; + if i.jobs_waiting() { + i.drain_jobs(Value::Undefined)?; + refresh_palettes(i)?; + i.drain_jobs(Value::Undefined)?; + } + Ok(()) + })(); + set_taking(i, was); + r +} + +/// Gives the host the controls of every palette the realm keeps, or does nothing without palettes. +fn refresh_palettes(i: &mut Interp) -> JsResult<()> { + if i.script_ui.as_ref().is_none_or(|c| c.palettes.is_empty()) { + return Ok(()); + } + update_palettes(i) +} + +/// A palette's `show()`: the host shows its description at once, then `onShow` runs, and `show()` +/// returns `undefined` without waiting. +fn show_palette(i: &mut Interp, win: ObjId) -> JsResult { + let (desc, ..) = describe(i, win)?; + let id = slot(i, win, PALETTE_ID)?; + let f = host_fn(i, "paletteShow")?; + Ok(Pause { host: f, args: vec![desc, id], keep: vec![Value::Object(win)], resume: palette_shown, failed: None }) +} + +fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { + let Some(win) = arg(keep, 0).as_object() else { return Err(Abrupt::Internal("show lost its palette".into())) }; + let Value::Number(_) = id else { return Err(Abrupt::Internal("the host gave the palette no id".into())) }; + set_slot(i, win, PALETTE_ID, id)?; + if !classes(i)?.palettes.contains(&win) { + set_palettes(i, |p| p.push(win)); + } + set_slot(i, win, SHOWN, Value::Bool(true))?; + i.put(win, key("visible"), Value::Bool(true), true)?; + handler(i, win, "onShow")?; + update_palette(i, win)?; + Ok(Value::Undefined) +} + +/// `Window.__vcPaletteEvent()`, which the run of a palette's handler calls: takes the event from the +/// host's `paletteEvent` and gives it to the palette the way a dialog takes the person's event. The +/// host gets every palette's controls once the run ends ([`crate::Realm::refresh_script_ui`]). An +/// event for a palette that has closed does nothing. +fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + let f = host_fn(i, "paletteEvent")?; + let answer = i.call(&f, &Value::Undefined, &[])?; + // An `update()` that a handler calls while this event runs takes no waiting event, so a later + // event does not run before this one has finished. + let was = i.script_ui.as_ref().is_some_and(|c| c.taking); + set_taking(i, true); + let r = deliver(i, answer); + set_taking(i, was); + r?; + Ok(Value::Undefined) +} + +/// Gives the host's event `answer` (`{palette, event, id, value, element}`, or anything else for +/// none) to its palette the way a dialog takes the person's event. An event for a palette that has +/// closed does nothing. +fn deliver(i: &mut Interp, answer: Value) -> JsResult { + let Some(ev) = answer.as_object() else { return Ok(Value::Undefined) }; + let mark = i.temp_roots.len(); + i.temp_roots.push(answer.clone()); + let r = (|| { + let id = slot(i, ev, "palette")?; + let palettes = classes(i)?.palettes; + let mut win = None; + for p in palettes { + if matches!((slot(i, p, PALETTE_ID)?, &id), (Value::Number(a), Value::Number(b)) if a == *b) { + win = Some(p); + } + } + let Some(win) = win else { return Ok(Value::Undefined) }; + // A hide from here on, even one a later show() follows, ends the palette's hold on the event. + let hides = number_slot(i, win, HIDES)?; + set_slot(i, ev, HIDES, Value::Number(hides))?; + let event = match slot(i, ev, "event")? { + Value::String(s) => s.to_rust_string(), + _ => String::new(), + }; + if event == "close" { + close_palette(i, win)?; + } else { + let (desc, nodes, ..) = describe(i, win)?; + // A getter read in the description may have closed the palette. + if !still_takes(i, win, ev, None)? { + return Ok(Value::Undefined); + } + i.temp_roots.push(desc.clone()); + i.temp_roots.push(Value::Object(nodes)); + let held = list_values(i, nodes)?; + // The host gives the control's id, which is found again in the palette as it is now: a + // getter read in the description may have added or removed a control before it. + let at = match slot(i, ev, "element")? { + Value::Number(element) => { + let mut at = None; + for (n, v) in held.iter().enumerate().skip(1) { + if let Some(c) = v.as_object() + && number_slot(i, c, ID)? == element + { + at = Some(n); + break; + } + } + at + } + _ => match slot(i, ev, "id")? { + Value::Number(n) if n >= 1.0 && n.fract() == 0.0 => Some(n as usize), + _ => None, + }, + }; + // A getter read in the description may also have removed the control after the + // description listed it: no handler runs for it. + let gone = match at.filter(|&n| n >= 1 && n < held.len()) { + Some(n) => match held[n].as_object() { + Some(c) => !holds(i, win, c)?, + None => false, + }, + None => true, + }; + let Some(at) = at.filter(|_| !gone) else { + return Err(error(i, "a palette event names a control the palette no longer holds")); + }; + // A getter read in the description may have disabled or hidden the control, or a + // container above it: the event is dropped, as the host drops one for such a control. + if !live_in(i, &desc, at)? { + return Ok(Value::Undefined); + } + // A getter read later in the description may have disabled or hidden the control or a + // container above it after the description recorded it: read the states again without + // running a getter, and drop the event unless they are all live. + if !live_now(i, &desc, &held, at)? || !still_takes(i, win, ev, None)? || !holds_value(i, win, &held, at)? { + return Ok(Value::Undefined); + } + set_slot(i, ev, "id", Value::Number(at as f64))?; + take_event(i, win, nodes, ev, &event, None)?; + } + Ok(Value::Undefined) + })(); + i.temp_roots.truncate(mark); + r +} + +/// Whether the element at `at` in the description `desc` ([`describe`]) is enabled and visible, and +/// every container above it too. +fn live_in(i: &Interp, desc: &Value, at: usize) -> JsResult { + let Some(d) = desc.as_object() else { return Ok(false) }; + let Some(nodes) = slot(i, d, "nodes")?.as_object() else { return Ok(false) }; + let nodes = list_values(i, nodes)?; + let mut n = Some(at); + for _ in 0..=nodes.len() { + let Some(k) = n else { return Ok(true) }; + let Some(node) = nodes.get(k).and_then(Value::as_object) else { return Ok(false) }; + if !slot(i, node, "enabled")?.truthy() || !slot(i, node, "visible")?.truthy() { + return Ok(false); + } + n = match slot(i, node, "parent")? { + Value::Number(p) if p >= 0.0 && p < k as f64 => Some(p as usize), + _ => None, + }; + } + Ok(false) +} + +/// Whether the control at `at` in `held` (the description's controls, in its order) and every +/// container above it, by the parents in `desc`, are enabled and visible as they are now, read +/// without running a getter ([`plain_state`]). +fn live_now(i: &Interp, desc: &Value, held: &[Value], at: usize) -> JsResult { + let Some(d) = desc.as_object() else { return Ok(false) }; + let Some(nodes) = slot(i, d, "nodes")?.as_object() else { return Ok(false) }; + let nodes = list_values(i, nodes)?; + let mut n = Some(at); + for _ in 0..=nodes.len() { + let Some(k) = n else { return Ok(true) }; + let (Some(node), Some(o)) = (nodes.get(k).and_then(Value::as_object), held.get(k).and_then(Value::as_object)) else { + return Ok(false); + }; + if !plain_state(i, o, "enabled")? || !plain_state(i, o, "visible")? { + return Ok(false); + } + n = match slot(i, node, "parent")? { + Value::Number(p) if p >= 0.0 && p < k as f64 => Some(p as usize), + _ => None, + }; + } + Ok(false) +} + +/// The state `name` of `o`, its own or the one its prototypes give, read without running a getter; +/// `false` when a getter gives it or nothing does. +fn plain_state(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match i.find_ordinary_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value.truthy(), + _ => false, + }) +} + +/// Whether the palette `win` still holds the control at `at` in `held`. +fn holds_value(i: &mut Interp, win: ObjId, held: &[Value], at: usize) -> JsResult { + match held.get(at).and_then(Value::as_object) { + Some(c) => holds(i, win, c), + None => Ok(false), + } +} + +/// Whether the window `win` still takes the event `ev`: a dialog (`keep` is `Some`) always does, +/// and a palette only while the host shows it under the id the event names and it has not been +/// hidden since it took the event. A getter or a handler run for the event may have closed or +/// hidden the palette, and shown it again. +fn still_takes(i: &mut Interp, win: ObjId, ev: ObjId, keep: Option<&[Value]>) -> JsResult { + if keep.is_some() { + return Ok(true); + } + if !slot(i, win, SHOWN)?.truthy() || number_slot(i, ev, HIDES)? != number_slot(i, win, HIDES)? { + return Ok(false); + } + let id = slot(i, ev, "palette")?; + Ok(matches!((slot(i, win, PALETTE_ID)?, id), (Value::Number(a), Value::Number(b)) if a == b)) } fn host_fn(i: &mut Interp, name: &str) -> JsResult { @@ -1509,9 +2082,13 @@ fn set_showing(i: &mut Interp, showing: Option) { } } -/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). +/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). On a +/// palette: [`show_palette`]. fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { - let win = dialog_of(i, &this, "show")?; + let (win, palette) = this_window(i, &this, "show")?; + if palette { + return show_palette(i, win); + } match classes(i)?.showing { Some(o) if o == win => return Err(error(i, "show: this dialog is already showing")), Some(_) => return Err(error(i, "show: a dialog cannot open while another dialog is showing")), @@ -1569,10 +2146,14 @@ fn finish(i: &mut Interp, win: ObjId, result: f64) -> JsResult { Ok(Value::Number(result)) } -/// Runs `onClose`. → false when it returned `false`. A `close()` that `onClose` calls belongs to -/// the close it decides on, so after `false` the dialog waits for the next event. +/// Runs `onClose`, during which a `close()` of the same palette does nothing. → false when it +/// returned `false`. A `close()` of a dialog that `onClose` calls belongs to the close it decides +/// on, so after `false` the dialog waits for the next event. fn may_close(i: &mut Interp, win: ObjId) -> JsResult { - let closes = !matches!(handler(i, win, "onClose")?, Some(Value::Bool(false))); + set_slot(i, win, IN_CLOSE, Value::Bool(true))?; + let ran = handler(i, win, "onClose"); + set_slot(i, win, IN_CLOSE, Value::Undefined)?; + let closes = !matches!(ran?, Some(Value::Bool(false))); if !closes { set_slot(i, win, CLOSING, Value::Undefined)?; } @@ -1654,61 +2235,154 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { } return next(i, win); } - let id = match slot(i, ev, "id")? { - Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, - _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), - }; - let nodes = list_values(i, nodes)?; - let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { - return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); - }; - let value = slot(i, ev, "value")?; - match event.as_str() { - "click" => { - // A listener above the button that closed the dialog gives the result. - if !click_control(i, c, &kind)? && kind == "button" && matches!(slot(i, win, CLOSING)?, Value::Undefined) { - let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); - if is(2) { - set_slot(i, win, CLOSING, Value::Number(1.0))?; - } else if is(3) { - set_slot(i, win, CLOSING, Value::Number(2.0))?; - } - } - } - "change" => { - match kind.as_str() { - "edittext" => { - i.put(c, key("text"), value, true)?; - dispatch(i, c, "changing", "onChanging")?; - } - "slider" => { - i.put(c, key("value"), value, true)?; - dispatch(i, c, "changing", "onChanging")?; - } - _ => { - let n = match value { - Value::Number(n) => n, - _ => -1.0, - }; - // The index is into the items the person saw. - let shown = match arg(keep, 4).as_object() { - Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), - None => Value::Undefined, - }; - if !same(&slot(i, c, ITEMS)?, &shown) { - return Err(error(i, "show: a list's items changed before the person's choice was taken")); - } - set_slot(i, c, SELECTION, Value::Number(n))?; - } - } - dispatch(i, c, "change", "onChange")?; - } - _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), - } + take_event(i, win, nodes, ev, &event, Some(keep))?; next(i, win) }) } +/// A click or a change the host gave in `ev` for control `id` of `nodes` (a description's list of +/// elements): the control takes it and its handlers and listeners run ([`dispatch_for`]). A +/// dialog's button without `onClick` and without a `click` listener of its own asks to close it +/// with 1 when it is the default element and 2 when it is the cancel element, which `keep` +/// (`show()`'s kept values) names; a palette has no `keep`. No handler or listener of a palette +/// runs once a getter, a setter or an earlier handler of the event closed the palette or took the +/// control out of it. +fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, keep: Option<&[Value]>) -> JsResult<()> { + let id = match slot(i, ev, "id")? { + Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, + _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), + }; + let nodes = list_values(i, nodes)?; + let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { + return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); + }; + let value = slot(i, ev, "value")?; + let taker = if keep.is_none() { Some((win, ev, c)) } else { None }; + match event { + "click" => { + let Some(handled) = click_control_for(i, c, &kind, taker)? else { + return Ok(()); + }; + // A listener above the button that closed the dialog gives the result. + if !handled + && kind == "button" + && let Some(keep) = keep + && matches!(slot(i, win, CLOSING)?, Value::Undefined) + { + let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); + if is(2) { + set_slot(i, win, CLOSING, Value::Number(1.0))?; + } else if is(3) { + set_slot(i, win, CLOSING, Value::Number(2.0))?; + } + } + } + "change" => { + match kind.as_str() { + "edittext" => { + i.put(c, key("text"), value, true)?; + if dispatch_for(i, c, "changing", "onChanging", taker)?.is_none() { + return Ok(()); + } + } + "slider" => { + i.put(c, key("value"), value, true)?; + if dispatch_for(i, c, "changing", "onChanging", taker)?.is_none() { + return Ok(()); + } + } + _ => { + let n = match value { + Value::Number(n) => n, + _ => -1.0, + }; + match keep { + // The index is into the items the person saw. + Some(keep) => { + let shown = match arg(keep, 4).as_object() { + Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), + None => Value::Undefined, + }; + if !same(&slot(i, c, ITEMS)?, &shown) { + return Err(error(i, "show: a list's items changed before the person's choice was taken")); + } + } + // A palette's list may have changed while the event waited: the host gives + // the items the person saw and the list's revision then. + // The revision is read after the texts, whose getters may change the list. + None => { + let same = same_items(i, c, &slot(i, ev, "items")?)?; + let revised = match slot(i, ev, "revision")? { + Value::Number(r) => r != number_slot(i, c, REVISION)?, + _ => false, + }; + // An item's text getter may have closed the palette, and its `onClose` + // may have changed the list: the event is then dropped, not refused. + if !still_takes(i, win, ev, keep)? { + return Ok(()); + } + // A getter may have removed the list, which changes neither its + // revision nor the palette. + if !holds(i, win, c)? { + return Err(error(i, "a palette event names a control the palette no longer holds")); + } + // An item's text getter may have disabled or hidden the list, or a + // group above it: the event is then dropped, as for a click. + if !live_up(i, win, c)? { + return Ok(()); + } + if revised || !same || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { + return Err(error(i, "a palette's list changed before the person's choice was taken")); + } + } + } + set_slot(i, c, SELECTION, Value::Number(n))?; + } + } + // `onChanging` may have closed the palette. + dispatch_for(i, c, "change", "onChange", taker)?; + } + _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), + } + Ok(()) +} + +/// Does the list `c` hold items with the texts in `seen` (an array of strings), in that order? True +/// when `seen` is not an array. A text a later item's getter changes after it was compared counts +/// as a change, and so does a text that is not a plain value of the item's own. +fn same_items(i: &mut Interp, c: ObjId, seen: &Value) -> JsResult { + let Some(seen) = seen.as_object() else { return Ok(true) }; + let seen = list_values(i, seen)?; + let items = items_of(i, c)?; + if seen.len() != items.len() { + return Ok(false); + } + i.rooted(&items, |i| { + let mut texts = Vec::with_capacity(items.len()); + for (item, want) in items.iter().zip(&seen) { + let Some(item) = item.as_object() else { return Ok(false) }; + let text = get(i, item, "text")?; + let text = i.to_str(&text)?.to_rust_string(); + if text != i.to_str(want)?.to_rust_string() { + return Ok(false); + } + texts.push((item, text)); + } + // Read again without running getters. Only a text held as a plain value can be checked so: + // one a getter, an inherited property or an object gives cannot, and counts as a change. + for (item, text) in texts { + let now = match i.get_own_property(item, &key("text"))? { + Some(Prop::Data { value, .. }) if !matches!(value, Value::Object(_)) => value, + _ => return Ok(false), + }; + if i.to_str(&now)?.to_rust_string() != text { + return Ok(false); + } + } + Ok(true) + }) +} + fn text_of(i: &mut Interp, v: &Value, what: &str) -> JsResult { let s = i.to_str(v)?; let text = if s.len() > MAX_TEXT_BYTES { None } else { Some(s.to_rust_string()) }; @@ -1779,7 +2453,9 @@ fn bounds(i: &mut Interp, v: &Value) -> JsResult { Some(Data::Number(n)) => *n, _ => 0.0, }; - return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(n(0) + n(2)), Data::Number(n(1) + n(3))])); + // Two finite numbers can add up to infinity; the sum is kept finite. + let end = |a: f64, b: f64| (a + b).clamp(-f64::MAX, f64::MAX); + return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(end(n(0), n(2))), Data::Number(end(n(1), n(3)))])); } numbers(i, v, &["left", "top", "right", "bottom"], "bounds") } @@ -1888,6 +2564,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { stack.push((kid, index, depth + 1)); } } + let in_palette = order.first().is_some_and(|(_, kind, _)| kind == "palette"); let objects: Vec = order.iter().map(|(o, ..)| Value::Object(*o)).collect(); i.temp_roots.extend(objects.iter().cloned()); let mut nodes = Vec::with_capacity(order.len()); @@ -1909,15 +2586,22 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { let name = text_of(i, &name_v, "a control's name")?; let text_v = get(i, o, "text")?; let text = text_of(i, &text_v, "a control's text")?; + // A palette is described as a dialog is; the host knows which it shows. + let shown_kind = if kind == "palette" { "dialog" } else { kind.as_str() }; let mut d: Vec<(String, Data)> = vec![ - ("kind".into(), Data::String(kind.clone())), + ("kind".into(), Data::String(shown_kind.to_string())), ("id".into(), Data::Number(number_slot(i, o, ID)?)), ("parent".into(), Data::Number(*parent)), ("name".into(), Data::String(name.clone())), ("text".into(), Data::String(text.clone())), ]; - let enabled = get(i, o, "enabled")?.truthy(); - let visible = get(i, o, "visible")?.truthy(); + // In a palette, the states are read without running a getter, and a state that a getter + // gives counts as off, as when an event for the control is delivered ([`plain_state`]). + let (enabled, visible) = if in_palette { + (plain_state(i, o, "enabled")?, plain_state(i, o, "visible")?) + } else { + (get(i, o, "enabled")?.truthy(), get(i, o, "visible")?.truthy()) + }; // A control is enabled and visible only while every container above it is. let (above_enabled, above_visible) = if *parent >= 0.0 { live.get(*parent as usize).copied().unwrap_or((true, true)) } else { (true, true) }; live.push((enabled && above_enabled, visible && above_visible)); @@ -1948,7 +2632,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { d.push(("characters".into(), Data::Number(number_arg(i, &n, "show: a control's characters")?))); } } - if matches!(kind.as_str(), "dialog" | "group" | "panel") { + if is_container(kind) { let orientation = get(i, o, "orientation")?; d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase()))); let ac = get_kept(i, o, "alignChildren")?; @@ -2007,6 +2691,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { selected = number_slot(i, o, SELECTION)?; let sel = selection_index(i, o)?.filter(|n| *n < items.len()); d.push(("selection".into(), sel.map_or(Data::Null, |n| Data::Number(n as f64)))); + d.push(("revision".into(), Data::Number(number_slot(i, o, REVISION)?))); } _ => {} } @@ -2014,19 +2699,47 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { snapshot.push(listed); selections.push(selected); } - let target = |i: &mut Interp, name: &str, word: &str| -> JsResult { - let given = get(i, win, name)?; - if let Some(n) = objects.iter().position(|o| same(o, &given)) { - return Ok(n as f64); + // The default and cancel elements are read before the states below, since their getters may + // also change a control's state. + let given_def = get(i, win, "defaultElement")?; + i.temp_roots.push(given_def.clone()); + let given_cancel = get(i, win, "cancelElement")?; + i.temp_roots.push(given_cancel.clone()); + // A palette's states are read again once every getter above has run, since one may have + // changed a control's state after it was read. + if in_palette { + let mut live: Vec<(bool, bool)> = Vec::with_capacity(order.len()); + for (n, (o, kind, parent)) in order.iter().enumerate() { + let (enabled, visible) = (plain_state(i, *o, "enabled")?, plain_state(i, *o, "visible")?); + let (above_enabled, above_visible) = + if *parent >= 0.0 { live.get(*parent as usize).copied().unwrap_or((true, true)) } else { (true, true) }; + live.push((enabled && above_enabled, visible && above_visible)); + if let Some(entry) = names.get_mut(n) { + entry.0 = kind == "button" && enabled && visible && above_enabled && above_visible; + } + if let Some(Data::Object(d)) = nodes.get_mut(n) { + for (field, value) in d.iter_mut() { + match field.as_str() { + "enabled" => *value = Data::Bool(enabled), + "visible" => *value = Data::Bool(visible), + _ => {} + } + } + } + } + } + let target = |given: &Value, word: &str| -> f64 { + if let Some(n) = objects.iter().position(|o| same(o, given)) { + return n as f64; } if !matches!(given, Value::Undefined | Value::Null) { - return Ok(-1.0); + return -1.0; } let button = |by_name: bool| names.iter().position(|(c, n, t)| *c && (if by_name { n } else { t }).to_lowercase() == word); - Ok(button(true).or_else(|| button(false)).map_or(-1.0, |n| n as f64)) + button(true).or_else(|| button(false)).map_or(-1.0, |n| n as f64) }; - let def = target(i, "defaultElement", "ok")?; - let cancel = target(i, "cancelElement", "cancel")?; + let def = target(&given_def, "ok"); + let cancel = target(&given_cancel, "cancel"); if !lists_unchanged(i, &order, &snapshot, &selections)? || !tree_unchanged(i, &order, &tree)? || !texts_unchanged(i, &item_texts)? { return Ok(None); } @@ -2079,14 +2792,22 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul radio_get, radio_set, showing: None, + palettes: Vec::new(), + taking: false, dispatching: Vec::new(), above: Vec::new(), next_id: 0.0, }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; - // `Window.alert`, `Window.confirm` and `Window.prompt` are the host's global functions. + let event = native(i, "__vcPaletteEvent", palette_event, 0, NativeKind::Plain, false)?; + i.define(window, key("__vcPaletteEvent"), Prop::Data { value: Value::Object(event), flags: 0 })?; + // The run of a palette's handler calls the global one through `this`, under a name that is + // not an identifier: a script can neither replace nor delete it nor declare the name, so + // the palettes still take events after a script assigns to `Window`. let global = i.global; + i.define(global, key(PALETTE_EVENT_GLOBAL), Prop::Data { value: Value::Object(event), flags: 0 })?; + // `Window.alert`, `Window.confirm` and `Window.prompt` are the host's global functions. for name in ["alert", "confirm", "prompt"] { if let Some(Prop::Data { value, .. }) = i.get_own_property(global, &key(name))? && i.is_callable(&value) @@ -2104,12 +2825,14 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul method(i, window_proto, "close", close, 1)?; method(i, window_proto, "hide", hide, 0)?; method(i, window_proto, "center", nothing, 1)?; + method(i, window_proto, "update", update, 0)?; pausable_method(i, window_proto, "show", show, 0)?; method(i, control_proto, "removeAll", remove_all, 0)?; method(i, control_proto, "find", find, 1)?; method(i, control_proto, "notify", notify, 1)?; method(i, control_proto, "show", control_show, 0)?; method(i, control_proto, "hide", control_hide, 0)?; + method(i, control_proto, "update", control_update, 0)?; method(i, event_proto, "stopPropagation", event_stop, 0)?; method(i, event_proto, "preventDefault", nothing, 0)?; method(i, item_proto, "toString", item_to_string, 0)?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index dafe4dabc8..11bde4ca26 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -308,8 +308,10 @@ fn a_stop_from_end_when_show_fails_ends_the_run() { #[test] fn types_that_are_not_available_yet_throw_errors_that_say_so() { for (source, want) in [ - ("new Window('palette')", "Window: a window of type palette is not available yet; use dialog"), - ("new Window('palette { b: Button {} }')", "Window: a window of type palette is not available yet; use dialog"), + ("new Window('window')", "Window: a window of type window is not available yet; use dialog or palette"), + ("new Window('window { b: Button {} }')", "Window: a window of type window is not available yet; use dialog or palette"), + ("new Window('palette')", "Window: this host shows no palettes"), + ("new Window('palette { b: Button {} }')", "Window: this host shows no palettes"), ("new Window('dialog').add('p: TabbedPanel {}')", "add: the control type tabbedpanel is not available yet"), ("new Window('dialog').add('tabbedpanel')", "add: the control type tabbedpanel is not available yet"), ("new Window('dialog').add('wobble')", "add: there is no control type wobble"), @@ -706,6 +708,824 @@ fn a_show_that_waits_resumes_with_the_host_s_answer() { assert_eq!(seen.borrow().ends, vec![(1.0, true)]); } +/// What a palette host was asked: each call's name and its palette id (0 for none). +type Calls = Rc>>; + +/// A realm with palette host functions: `paletteShow` gives ids from 1, and `paletteEvent` gives +/// the events in `events`, in order, then `null`. +fn palette_realm(events: Vec) -> (Realm, Calls) { + palette_realm_with(events, Vec::new(), Vec::new()) +} + +/// [`palette_realm`], whose `paletteTake` also gives the events in `taken`, in order, then `null`, +/// whose `palettePending` says whether any of them is left, and whose `paletteDraw` gives the +/// answers in `draws`, in order, then `false`. +fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> (Realm, Calls) { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let calls: Calls = Rc::default(); + let events = Rc::new(RefCell::new(VecDeque::from(events))); + let id_of = |args: &[Data], at: usize| match args.get(at) { + Some(Data::Number(n)) => *n, + _ => 0.0, + }; + let record = |name: &'static str, at: usize| -> HostFunction { + let c = calls.clone(); + Rc::new(move |args| { + c.borrow_mut().push((name.to_string(), id_of(&args, at))); + Ok(Data::Undefined) + }) + }; + let c = calls.clone(); + let show: HostFunction = Rc::new(move |args| { + let given = id_of(&args, 1); + let id = if given > 0.0 { given } else { 1.0 + c.borrow().iter().filter(|(n, _)| n == "paletteShow").count() as f64 }; + c.borrow_mut().push(("paletteShow".into(), id)); + Ok(Data::Number(id)) + }); + let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null))); + let taken = Rc::new(RefCell::new(VecDeque::from(taken))); + let c = calls.clone(); + let left = taken.clone(); + let take: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("paletteTake".into(), 0.0)); + Ok(left.borrow_mut().pop_front().unwrap_or(Data::Null)) + }); + let c = calls.clone(); + let pending: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("palettePending".into(), 0.0)); + Ok(Data::Bool(!taken.borrow().is_empty())) + }); + let draws = RefCell::new(VecDeque::from(draws)); + let c = calls.clone(); + let draw: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("paletteDraw".into(), 0.0)); + Ok(Data::Bool(draws.borrow_mut().pop_front().unwrap_or(false))) + }); + let none: HostFunction = Rc::new(|_| Err(HostError::Error("no dialog here".into()))); + let items = vec![ + ("open".into(), HostItem::Function(none.clone())), + ("wait".into(), HostItem::Function(none.clone())), + ("end".into(), HostItem::Function(none)), + ("palette".into(), HostItem::Function(record("palette", 0))), + ("paletteShow".into(), HostItem::Function(show)), + ("paletteUpdate".into(), HostItem::Function(record("paletteUpdate", 1))), + ("paletteHide".into(), HostItem::Function(record("paletteHide", 0))), + ("paletteClose".into(), HostItem::Function(record("paletteClose", 0))), + ("paletteEvent".into(), HostItem::Function(event)), + ("paletteTake".into(), HostItem::Function(take)), + ("palettePending".into(), HostItem::Function(pending)), + ("paletteDraw".into(), HostItem::Function(draw)), + ]; + r.define_script_ui(items).unwrap(); + (r, calls) +} + +fn palette_event(palette: f64, event: Data) -> Data { + let Data::Object(mut fields) = event else { return Data::Null }; + fields.push(("palette".into(), Data::Number(palette))); + Data::Object(fields) +} + +fn names(calls: &Calls) -> Vec { + calls.borrow().iter().map(|(n, _)| n.clone()).collect() +} + +#[test] +fn a_palette_s_show_returns_at_once_and_its_events_run_its_handlers() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2)), palette_event(1.0, change(3, Data::String("typed".into())))]); + let made = r + .run( + "var p = new Window('palette', 'Tools'); var label = p.add('statictext', undefined, 'idle'); \ + var b = p.add('button', undefined, 'Go'); var t = p.add('edittext', undefined, ''); var log = []; \ + b.onClick = function () { log.push('click'); label.text = 'clicked'; }; \ + t.onChange = function () { log.push('change ' + t.text); }; String(p.show())", + ) + .unwrap(); + assert_eq!(made, JsValue::String("undefined".into()), "show() gives undefined without waiting"); + assert_eq!(names(&calls), ["palette", "paletteShow", "paletteUpdate"]); + r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("log.join('|') + '|' + label.text").unwrap(), JsValue::String("click|change typed|clicked".into())); + let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count(); + assert_eq!(updates(&calls), 1, "the handlers give the host nothing"); + r.refresh_script_ui().unwrap(); + assert_eq!(updates(&calls), 2, "the refresh after the run gives the host the new controls"); + assert_eq!(r.run("Window.__vcPaletteEvent(); 'nothing'").unwrap(), JsValue::String("nothing".into()), "no event left: nothing runs"); +} + +#[test] +fn a_palette_click_runs_no_handler_once_its_button_was_taken_out_of_the_palette() { + // The button's onClick getter takes it out of the palette and gives a function. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var log = []; \ + Object.defineProperty(b, 'onClick', {get: function () { p.remove(b); return function () { log.push('ran'); }; }}); p.show();", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "the getter's function does not run"); + // A capturing listener on the palette takes the button out before the button's own turn. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var log = []; \ + b.onClick = function () { log.push('click'); }; b.addEventListener('click', function () { log.push('listener'); }); \ + p.addEventListener('click', function () { log.push('capture'); p.remove(b); }, true); p.show();", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("capture".into())); +} + +#[test] +fn a_palette_click_is_dropped_when_a_getter_read_for_it_disables_its_button_or_a_group_above() { + for disable in ["b.enabled = false;", "g.enabled = false;", "g.visible = false;"] { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(3))]); + r.run(&format!( + "var armed = false, log = []; var p = new Window('palette'); var label = p.add('statictext', undefined, 'L'); \ + var g = p.add('group'); var b = g.add('button', undefined, 'Go'); b.onClick = function () {{ log.push('click'); }}; \ + Object.defineProperty(label, 'text', {{get: function () {{ if (armed) {{ armed = false; {disable} }} return 'L'; }}}}); \ + p.show(); armed = true;" + )) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "{disable}"); + } +} + +#[test] +fn a_palette_click_is_dropped_when_a_getter_read_after_its_button_disables_the_button_or_a_group_above() { + for disable in ["b.enabled = false;", "g.enabled = false;", "g.visible = false;"] { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run(&format!( + "var armed = false, log = []; var p = new Window('palette'); \ + var g = p.add('group'); var b = g.add('button', undefined, 'Go'); b.onClick = function () {{ log.push('click'); }}; \ + var label = p.add('statictext', undefined, 'L'); \ + Object.defineProperty(label, 'text', {{get: function () {{ if (armed) {{ armed = false; {disable} }} return 'L'; }}}}); \ + p.show(); armed = true;" + )) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "{disable}"); + } + // A getter that gives the button's state, and disables it while it says the button is visible. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var armed = false, log = []; var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); \ + b.onClick = function () { log.push('click'); }; p.add('statictext', undefined, 'L'); p.show(); \ + Object.defineProperty(b, 'visible', {get: function () { b.enabled = false; return true; }}); b.enabled = true;", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into())); + // Without a getter that disables anything, the same click runs its handler. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var log = []; var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); \ + b.onClick = function () { log.push('click'); }; p.add('statictext', undefined, 'L'); p.show();", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("click".into())); +} + +#[test] +fn a_palette_list_change_throws_when_an_item_s_text_comes_from_a_getter() { + let (mut r, _) = palette_realm(vec![seen_list_change(0.0), seen_list_change(0.0)]); + // The first item's getter gives `label`, which the second item's getter changes after the + // first was compared. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; var label = 'a', armed = false; \ + l.onChange = function () { got.push(String(l.selection)); }; \ + Object.defineProperty(l.items[0], 'text', {get: function () { return label; }}); \ + Object.defineProperty(l.items[1], 'text', {get: function () { if (armed) { label = 'z'; } return 'b'; }}); \ + p.show();", + ) + .unwrap(); + for arm in ["false", "true"] { + let e = r.run(&format!("armed = {arm}; label = 'a'; try {{ Window.__vcPaletteEvent(); 'none'; }} catch (e) {{ e.message; }}")).unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()), "armed {arm}"); + } + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); +} + +#[test] +fn update_asks_the_host_once_more_after_a_handler_s_exception() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new()); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); b.onClick = function () { throw new Error('broken'); }; p.show();", + ) + .unwrap(); + let thrown = r.run("try { p.update(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(thrown, JsValue::String("broken".into())); + let asked: Vec = names(&calls).into_iter().filter(|n| n == "palettePending" || n == "paletteTake").collect(); + assert_eq!(asked, ["palettePending", "paletteTake", "palettePending"], "the host learns the event's handlers ended"); +} + +#[test] +fn closing_a_palette_runs_on_close_which_can_keep_it_open() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, close()), palette_event(1.0, close()), palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; \ + var asked = 0; p.onClose = function () { asked++; p.close(); return asked > 1; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert!(!names(&calls).contains(&"paletteClose".to_string()), "the first onClose kept it open"); + assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(true), "a palette onClose kept open stays visible"); + r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[asked, clicks].join()").unwrap(), JsValue::String("2,0".into()), "a close inside onClose does not run it again"); + assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(false), "a closed palette is not visible"); + assert_eq!(calls.borrow().iter().filter(|(n, _)| n == "paletteClose").count(), 1); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +fn count(calls: &Calls, name: &str) -> usize { + calls.borrow().iter().filter(|(n, _)| n == name).count() +} + +#[test] +fn update_in_the_script_s_own_code_gives_the_controls_only_when_the_host_draws_the_palette() { + let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true, false, false, true]); + r.start( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 4); p.show(); \ + for (var k = 1; k <= 4; k++) { bar.value = k; p.update(); }", + ) + .unwrap(); + while r.advance(1_000_000).unwrap() == Progress::Paused {} + assert_eq!(count(&calls, "paletteDraw"), 4, "each update() asks whether the palette is drawn"); + assert_eq!(count(&calls, "paletteUpdate"), 1 + 2, "show(), then only the update() calls the host draws"); +} + +#[test] +fn update_in_a_handler_neither_asks_to_draw_the_palette_nor_gives_its_controls() { + let (mut r, calls) = palette_realm_with(vec![palette_event(1.0, click(2))], Vec::new(), vec![true; 3]); + r.run( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } }; p.show();", + ) + .unwrap(); + let before = count(&calls, "paletteUpdate"); + r.start("Window.__vcPaletteEvent();").unwrap(); + while r.advance(1_000_000).unwrap() == Progress::Paused {} + assert_eq!(count(&calls, "paletteDraw"), 0, "a handler cannot pause, so its update() is not drawn"); + assert_eq!(count(&calls, "paletteUpdate"), before, "the handler's update() calls give the host no controls"); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteUpdate") - before, 1, "the controls go to the host once the run ends"); +} + +#[test] +fn update_hands_a_waiting_click_to_the_palette_so_a_cancel_button_stops_a_loop() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(2))], Vec::new()); + let done = r + .run( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100); \ + var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; \ + cancel.onClick = function () { stopped = true; }; p.show(); \ + var k = 0; while (!stopped && k < 100) { k++; bar.value = k; p.update(); } k + ':' + stopped", + ) + .unwrap(); + assert_eq!(done, JsValue::String("1:true".into()), "the first update() runs the click's onClick"); + assert_eq!(count(&calls, "paletteTake"), 1, "update() takes events while one waits"); + assert!(count(&calls, "palettePending") >= 2, "update() asks again after each event"); + let order = names(&calls); + let take = order.iter().position(|n| n == "paletteTake"); + let last_update = order.iter().rposition(|n| n == "paletteUpdate"); + assert!(take.zip(last_update).is_some_and(|(t, u)| u < t), "the host gets the controls before the event is taken"); +} + +#[test] +fn an_update_a_getter_calls_while_a_click_waits_leaves_the_click_to_the_update_taking_it() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new()); + let done = r + .run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; var armed = false; \ + b.onClick = function () { clicks++; }; \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { reads++; p.update(); } return 'P'; }}); \ + p.show(); armed = true; p.update(); clicks + ':' + (reads > 0)", + ) + .unwrap(); + assert_eq!(done, JsValue::String("1:true".into()), "the getter's update() runs, and the click's onClick runs once"); + assert_eq!(count(&calls, "paletteTake"), 1); +} + +#[test] +fn update_throws_for_a_window_that_is_not_showing() { + let (mut r, _, _) = realm(vec![click(12)]); + let source = format!( + "{FORM} var before = 'none'; try {{ w.update(); }} catch (e) {{ before = e.message; }} var during = 'none'; \ + ok.onClick = function () {{ w.update(); during = 'ran'; w.close(1); }}; [w.show(), before, during].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|update: the window is not showing|ran".into())); + let (mut r, _) = palette_realm(Vec::new()); + let hidden = r + .run( + "var p = new Window('palette'); var log = []; try { p.update(); } catch (e) { log.push('before show'); } \ + p.show(); p.update(); p.hide(); try { p.update(); } catch (e) { log.push('hidden'); } log.join()", + ) + .unwrap(); + assert_eq!(hidden, JsValue::String("before show,hidden".into())); +} + +#[test] +fn update_on_a_showing_dialog_its_group_or_its_panel_runs_in_a_handler() { + let (mut r, _, _) = realm(vec![click(12)]); + let source = format!( + "{FORM} var done = 'none'; ok.onClick = function () {{ bar.value = 7; w.update(); g.update(); p.update(); done = 'ran'; w.close(1); }}; \ + [w.show(), done].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|ran".into())); +} + +#[test] +fn update_follows_whether_the_host_shows_a_palette_not_its_visible_property() { + let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true; 4]); + r.run("var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); p.show();").unwrap(); + let before = count(&calls, "paletteUpdate"); + r.start( + "var log = []; p.visible = false; p.update(); g.update(); log.push('shown'); \ + p.hide(); p.visible = true; try { p.update(); } catch (e) { log.push('hidden'); } \ + try { b.update(); } catch (e) { log.push(e.name); } log.join()", + ) + .unwrap(); + let log = loop { + if let Progress::Done(v) = r.advance(1_000_000).unwrap() { + break v; + } + }; + assert_eq!(log, JsValue::String("shown,hidden,TypeError".into())); + assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the palette and its group each give the host the controls while it shows"); +} + +#[test] +fn a_palette_list_change_after_its_items_changed_throws() { + let seen = |index: f64| { + let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null }; + fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())]))); + // The two items the list was made with. + fields.push(("revision".into(), Data::Number(2.0))); + Data::Object(fields) + }; + let (mut r, _) = palette_realm(vec![seen(1.0), seen(1.0), seen(1.0), seen(1.0)]); + r.run("var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; l.onChange = function () { got.push(String(l.selection)); }; p.show();") + .unwrap(); + r.run("Window.__vcPaletteEvent(); l.removeAll(); l.add('item', 'c'); l.add('item', 'd');").unwrap(); + let message = "a palette's list changed before the person's choice was taken"; + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "the same number of items, other texts"); + r.run("l.removeAll(); l.add('item', 'a');").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "fewer items"); + r.run("l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "new items with the same texts"); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("b".into())); +} + +/// A palette list change as the host gives it: the item index, the items the person saw (`a` and +/// `b`) and the revision of a list made with those two items. +fn seen_list_change(index: f64) -> Data { + let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null }; + fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())]))); + fields.push(("revision".into(), Data::Number(2.0))); + Data::Object(fields) +} + +#[test] +fn a_palette_list_change_after_an_item_s_text_changed_throws() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + r.run("var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; l.onChange = function () { got.push(String(l.selection)); }; p.show();") + .unwrap(); + r.run("l.items[1].text = 'z';").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()), "the same items, one with another text"); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); +} + +#[test] +fn a_palette_list_change_throws_when_an_item_s_text_getter_replaces_the_items() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The event reads the first item's text twice: for the palette's description, then to compare + // it with the items the person saw. The second read turns the getter back into a plain text and + // replaces the items with ones of the same texts, so only the list's revision tells them apart. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; var first = l.items[0]; \ + Object.defineProperty(first, 'text', {configurable: true, get: function () { if (reads >= 0 && ++reads == 2) { \ + Object.defineProperty(first, 'text', {value: 'a', writable: true, enumerable: true, configurable: true}); \ + l.removeAll(); l.add('item', 'a'); l.add('item', 'b'); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into())); + assert_eq!(r.run("[reads, got.join()].join()").unwrap(), JsValue::String("2,".into())); +} + +#[test] +fn a_palette_event_finds_its_control_by_its_id() { + let of = |id: usize, element: f64| { + let Data::Object(mut fields) = palette_event(1.0, click(id)) else { return Data::Null }; + fields.push(("element".into(), Data::Number(element))); + Data::Object(fields) + }; + // The palette is element 1, the group 2 and the button 3. The host's indexes are stale: 1 is + // the group, and after the group is removed, 2 is past the end. + let (mut r, _) = palette_realm(vec![of(1, 3.0), of(2, 3.0), of(1, 99.0)]); + r.run("var p = new Window('palette'); var g = p.add('group'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; p.show();") + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0), "the click reaches the control with its id"); + r.run("p.remove(g); Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(2.0), "the click follows the control after a control before it is removed"); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette event names a control the palette no longer holds".into()), "no control with the id"); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(2.0)); +} + +#[test] +fn a_palette_click_on_a_button_a_getter_removed_runs_no_handler_and_throws() { + // The palette is element 1, the label 2 and the button 3. + let Data::Object(mut fields) = palette_event(1.0, click(2)) else { panic!("an event is an object") }; + fields.push(("element".into(), Data::Number(3.0))); + let (mut r, _) = palette_realm(vec![Data::Object(fields)]); + r.run( + "var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \ + var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \ + Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.remove(b); } return 'idle'; }}); p.show();", + ) + .unwrap(); + // The event reads the label's text for the palette's description, which removes the button. + let given = r.run("armed = true; try { Window.__vcPaletteEvent(); 'given'; } catch (e) { e.message; }").unwrap(); + assert_eq!(given, JsValue::String("a palette event names a control the palette no longer holds".into())); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the removed button's handler does not run"); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_getter_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \ + var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \ + Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.close(); } return 'idle'; }}); p.show();", + ) + .unwrap(); + // The event reads the label's text for the palette's description, which closes the palette. + r.run("armed = true; Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the click is not given to a closed palette"); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +#[test] +fn a_palette_event_runs_no_more_listeners_once_one_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var later = 0; \ + b.addEventListener('click', function () { p.close(); }); b.addEventListener('click', function () { later++; }); \ + p.addEventListener('click', function () { later++; }); p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); + assert_eq!(r.run("later").unwrap(), JsValue::Number(0.0), "neither the next listener nor the palette's runs after the close"); +} + +#[test] +fn a_palette_list_change_does_not_run_on_change_once_an_item_s_text_getter_closed_the_palette() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The event reads the first item's text twice: for the palette's description, then to compare + // it with the items the person saw. The second read closes the palette. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into())); + assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into())); +} + +#[test] +fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_disabled_or_hid_the_list() { + for disable in ["l.enabled = false;", "l.visible = false;"] { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The second read of the first item's text, which compares it with the items the person + // saw, disables the list. + r.run(&format!( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () {{ got.push(String(l.selection)); }}; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {{get: function () {{ if (reads >= 0 && ++reads == 2) {{ {disable} }} return 'a'; }}}}); \ + p.show();" + )) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into()), "{disable}"); + assert_eq!(r.run("[got.join(), String(l.selection)].join()").unwrap(), JsValue::String(",null".into()), "{disable}"); + } +} + +#[test] +fn a_palette_click_does_not_turn_over_a_check_box_its_value_getter_disabled() { + // Whichever read of `value` disables the box, the click neither sets it nor runs its handler. + for read in 1..=4 { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run(&format!( + "var p = new Window('palette'); var c = p.add('checkbox', undefined, 'On'); var clicks = 0, on = false, reads = -1; \ + Object.defineProperty(c, 'value', {{get: function () {{ if (reads >= 0 && ++reads == {read}) {{ c.enabled = false; }} return on; }}, \ + set: function (v) {{ on = v; }}}}); c.onClick = function () {{ clicks++; }}; p.show(); reads = 0;" + )) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + let got = r.run(&format!("reads >= {read} ? [clicks, on].join() : 'not read'")).unwrap(); + assert!(got == JsValue::String("0,false".into()) || (read > 1 && got == JsValue::String("not read".into())), "read {read}: {got:?}"); + } +} + +#[test] +fn a_hidden_palette_is_not_described_after_the_run() { + let (mut r, calls) = palette_realm(Vec::new()); + r.run( + "var p = new Window('palette', 'T'); p.add('button', undefined, 'Go'); p.show(); p.hide(); \ + Object.defineProperty(p, 'text', {get: function () { throw new Error('read'); }});", + ) + .unwrap(); + let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, _)| n == "paletteUpdate").count(); + let before = updates(&calls); + r.refresh_script_ui().expect("a hidden palette's throwing title getter is not read"); + assert_eq!(updates(&calls), before, "the host is not given a hidden palette's controls"); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; \ + Object.defineProperty(b, 'onClick', {get: function () { reads++; p.close(); return function () { clicks++; }; }}); p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a closed palette does not run"); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_whose_getter_hid_the_palette() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; \ + Object.defineProperty(b, 'onClick', {get: function () { reads++; p.hide(); return function () { clicks++; }; }}); p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a hidden palette does not run"); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_listener_hid_and_showed_the_palette_again() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \ + p.addEventListener('click', function () { heard++; p.hide(); p.show(); }, true); \ + b.onClick = function () { clicks++; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!( + r.run("[heard, clicks, p.visible].join()").unwrap(), + JsValue::String("1,0,true".into()), + "a click the palette took before a hide is not its click after the palette shows again" + ); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_capturing_listener_disabled_its_group() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \ + g.addEventListener('click', function () { heard++; g.enabled = false; }, true); \ + b.onClick = function () { clicks++; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[heard, clicks].join()").unwrap(), JsValue::String("1,0".into()), "a control in a disabled group takes no click"); +} + +#[test] +fn a_palette_refresh_that_fails_reports_no_rejection() { + let (mut r, _) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }}); \ + p.show(); Promise.reject(new Error('early')); armed = true;", + ) + .unwrap(); + assert_eq!(r.unhandled_rejection_count(), 1, "the run left the rejection unhandled"); + assert!(r.refresh_script_ui().is_err()); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "a failed refresh reports no rejection"); +} + +#[test] +fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_the_list() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The second read of the first item's text, which compares it with the items the person saw, + // removes the list from the palette. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.remove(l); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette event names a control the palette no longer holds".into())); + assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into())); +} + +#[test] +fn a_palette_list_change_throws_when_a_later_item_s_text_getter_changes_an_earlier_item_s_text() { + let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]); + // The second read of the second item's text, which compares it with the items the person saw, + // changes the first item's text, which that comparison already took. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[1], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.items[0].text = 'z'; } return 'b'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into())); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); +} + +#[test] +fn an_add_whose_palette_update_a_getter_breaks_still_returns_the_control() { + let (mut r, _) = palette_realm(Vec::new()); + r.run( + "var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var armed = false; \ + Object.defineProperty(label, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'idle'; }}); \ + var list = p.add('listbox', undefined, ['a']); p.show();", + ) + .unwrap(); + let added = r + .run( + "armed = true; var c, d, m = []; try { c = p.add('button', undefined, 'New'); } catch (e) { m.push(e.message); } \ + try { d = list.add('item', 'b'); } catch (e) { m.push(e.message); } \ + try { list.remove(0); } catch (e) { m.push(e.message); } \ + try { p.remove(c); } catch (e) { m.push(e.message); } armed = false; \ + [String(c && c.text), String(d && d.text), list.items.length, p.children.length, m.length].join()", + ) + .unwrap(); + assert_eq!(added, JsValue::String("New,b,1,2,0".into()), "each change is made once and gives its result"); + // A later error is at its own line, not at the getter's. + let e = r.run("armed = true;\np.add('button', undefined, 'Other');\narmed = false;\nthrow new Error('later');").unwrap_err(); + assert_eq!((e.message.contains("later"), e.line), (true, 4), "{e:?}"); +} + +#[test] +fn promise_jobs_a_palette_getter_queues_while_the_palette_is_refreshed_run() { + let (mut r, calls) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var ran = 0, armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \ + Promise.resolve().then(function () { ran++; b.text = 'Done'; }); Promise.reject(new Error('late')); } return 'P'; }}); \ + p.show(); armed = true;", + ) + .unwrap(); + let before = count(&calls, "paletteUpdate"); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the host gets the controls again after the jobs ran"); + assert_eq!(r.unhandled_rejections().len(), 1, "the job's rejection is the run's"); + assert_eq!(r.run("[ran, b.text].join()").unwrap(), JsValue::String("1,Done".into()), "the job the getter queued ran with the refresh"); +} + +#[test] +fn a_run_s_rejection_that_a_palette_getter_handles_during_the_refresh_is_not_reported() { + let (mut r, _) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var armed = false, caught = 0; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \ + early.catch(function () { caught++; }); } return 'P'; }}); \ + p.show(); var early = Promise.reject(new Error('early')); armed = true;", + ) + .unwrap(); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (1, 1), "the run left the rejection unhandled"); + r.refresh_script_ui().unwrap(); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "the getter gave it a handler"); +} + +#[test] +fn a_rejection_a_palette_getter_makes_while_a_failed_run_is_refreshed_is_not_reported() { + let (mut r, _) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \ + Promise.reject('late'); } return 'P'; }}); p.show();", + ) + .unwrap(); + assert!(r.run("armed = true; throw new Error('failed');").is_err()); + r.refresh_script_ui_after_error(); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "a failed run reports no rejection"); +} + +#[test] +fn promise_jobs_a_palette_getter_queues_on_every_refresh_run_without_another_refresh() { + let (mut r, calls) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var n = 0, reads = 0; var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); \ + Object.defineProperty(p, 'text', {get: function () { reads++; \ + Promise.resolve().then(function () { n++; }); return 'Title'; }});", + ) + .unwrap(); + let before = count(&calls, "paletteUpdate"); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the host gets the controls again once after the jobs run"); + assert_eq!(r.run("reads > 0 && n === reads").unwrap(), JsValue::Bool(true), "every getter read's job runs before the refresh returns"); +} + +#[test] +fn promise_jobs_a_palette_getter_queues_during_refresh_leave_waiting_clicks_queued() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new()); + r.add_es2015(); + r.run( + "var clicks = 0, jobs = 0, armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { clicks++; }; \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { \ + Promise.resolve().then(function () { jobs++; p.update(); }); } return 'P'; }}); \ + p.show(); armed = true;", + ) + .unwrap(); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteTake"), 0, "the refresh leaves the waiting click queued"); + assert_eq!(r.run("jobs > 0 && clicks === 0").unwrap(), JsValue::Bool(true), "the promise jobs run without dispatching the click"); + assert_eq!(r.run("armed = false; p.update(); clicks").unwrap(), JsValue::Number(1.0), "a later update takes the waiting click"); + assert_eq!(count(&calls, "paletteTake"), 1, "the refresh restores the event-taking guard"); +} + +#[test] +fn an_object_on_close_throws_stays_whole_while_the_close_ends() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, close())]); + r.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.onClose = function () { throw {tag: 'kept'}; }; p.show();").unwrap(); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let thrown = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { String(e.tag); }"); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(thrown.unwrap(), JsValue::String("kept".into())); +} + +#[test] +fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_closed_the_palette_and_on_close_changed_the_list() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The second read of the first item's text closes the palette, and its `onClose` adds an item. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + p.onClose = function () { l.add('item', 'c'); }; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into()), "the event for a closed palette is dropped without an error"); + assert_eq!(r.run("[reads >= 2, l.items.length, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("true,3,,null".into())); +} + +#[test] +fn a_palette_s_visible_follows_hide_and_show() { + let (mut r, _) = palette_realm(Vec::new()); + let v = r + .run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); var a = p.visible; p.hide(); var b = p.visible; p.show(); [a, b, p.visible].join()") + .unwrap(); + assert_eq!(v, JsValue::String("true,false,true".into())); +} + +#[test] +fn a_close_inside_a_dialog_s_on_close_does_nothing() { + let (mut r, seen, _) = realm(vec![close(), click(13)]); + let source = format!( + "{FORM} var asked = 0; w.onClose = function () {{ asked++; if (asked == 1) {{ w.close(5); return false; }} return true; }}; [w.show(), asked].join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("2,2".into()), "the dialog waited for the click on Cancel"); + assert_eq!(seen.borrow().ends, vec![(2.0, true)]); +} + +#[test] +fn bounds_whose_ends_add_up_past_the_largest_number_stay_finite() { + let (mut r, seen, _) = realm(vec![close()]); + r.run("var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); b.bounds = {x: 1e308, y: 0, width: 1e308, height: 20}; w.show()") + .unwrap(); + let described = nodes(&seen.borrow().descriptions[0]); + let want = Data::Array(vec![Data::Number(1e308), Data::Number(0.0), Data::Number(f64::MAX), Data::Number(20.0)]); + assert_eq!(field(&described[1], "bounds"), &want); +} + +#[test] +fn hide_keeps_the_palette_and_show_shows_it_again_with_the_same_id() { + let (mut r, calls) = palette_realm(Vec::new()); + r.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); p.hide(); p.show();").unwrap(); + let shows: Vec = calls.borrow().iter().filter(|(n, _)| n == "paletteShow" || n == "paletteHide").map(|(_, id)| *id).collect(); + assert_eq!(shows, [1.0, 1.0, 1.0]); +} + #[test] fn findelement_items_and_selection_follow_the_list() { let (mut r, _, _) = realm(Vec::new()); diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 7ebcacbbc2..5c083d7acd 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -157,7 +157,9 @@ pub(crate) struct WellKnown { pub(crate) has_instance: Sym, pub(crate) to_primitive: Sym, pub(crate) to_string_tag: Sym, - /// The five as values, for the collector. + pub(crate) unscopables: Sym, + pub(crate) is_concat_spreadable: Sym, + /// The Symbols as values, for the collector. values: Vec, } @@ -171,8 +173,14 @@ impl WellKnown { make("Symbol.toPrimitive"), make("Symbol.toStringTag"), ); - let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag].into_iter().cloned().map(Value::Symbol).collect(); - WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, values } + let unscopables = make("Symbol.unscopables"); + let is_concat_spreadable = make("Symbol.isConcatSpreadable"); + let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag, &unscopables, &is_concat_spreadable] + .into_iter() + .cloned() + .map(Value::Symbol) + .collect(); + WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, unscopables, is_concat_spreadable, values } } } @@ -543,7 +551,7 @@ impl Interp { /// the heap for the list is checked first. A proxy's Symbols come from its `ownKeys` trap. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { if self.is_proxy(id) { - return Ok(self.proxy_own_keys(id)?.syms); + return Ok(self.proxy_own_keys(id, false)?.syms); } let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index fa81397b00..9581ebc0ac 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -31,7 +31,8 @@ //! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`, //! arrow functions, templates, default and rest parameters, classes, `super` and `new.target`, //! and from ECMAScript 2020 optional chains and `??`) without and with that option, and -//! prints both counts; its failures with the option go to `es2015-failures.txt`. A sixth test runs +//! prints both counts; its failures with the option, and the runs without it that panicked, go to +//! `es2015-failures.txt`. A sixth test runs //! the module tests under `test/language/module-code`, `import` and `export` as modules, reading //! the fixture files they import from the suite, and as scripts for comparison; its failures as //! modules go to `module-failures.txt`. @@ -56,8 +57,8 @@ //! Another test runs the tests under `test/built-ins/Promise` in realms with `Options::es2015`: //! those whose feature tags name only `Promise`, `Promise.allSettled` and //! `Promise.prototype.finally`, whose code parses and uses only the built-ins present. `async` tests -//! run with the suite's `doneprintHandle.js` and pass when they print the completion line. Its -//! failures go to `promise-failures.txt`. +//! run with the suite's `doneprintHandle.js` and pass when they print the completion line and no +//! line that starts with the failure prefix. Its failures go to `promise-failures.txt`. //! //! Another test runs the tests of `Symbol`, `Object.getOwnPropertySymbols` and the iterators of //! arrays and strings (the folders [`SYMBOL_BUILT_INS`] names) in a realm with @@ -473,7 +474,7 @@ fn uses_missing_builtin(lists: &[Vec], missing: &HashSet<&str>) -> bool { let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens)); lists.iter().flatten().any(|t| match &t.kind { TokenKind::Ident(name) => missing.contains(name.as_str()), - TokenKind::String(units) => { + TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => { let text = String::from_utf16_lossy(units); missing.contains(text.as_str()) || (strings_are_code && text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')).any(|word| missing.contains(word))) @@ -483,12 +484,12 @@ fn uses_missing_builtin(lists: &[Vec], missing: &HashSet<&str>) -> bool { } /// The tokens can run a string as code: they name `eval`, `Function` or a `constructor` property, -/// as an identifier or as a string key (`this["eval"]`), called directly or through an alias. +/// as an identifier or as a string or template key (`this["eval"]`), called directly or through an alias. /// `Function.prototype` alone does not count. fn runs_strings_as_code(tokens: &[Token]) -> bool { const RUNNERS: [&str; 3] = ["eval", "Function", "constructor"]; tokens.iter().enumerate().any(|(i, t)| match &t.kind { - TokenKind::String(units) => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())), + TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())), TokenKind::Ident(name) if name == "eval" || name == "constructor" => true, TokenKind::Ident(name) if name == "Function" => { let prototype = tokens.get(i + 1).is_some_and(|d| d.is_punct(Punct::Dot)) @@ -883,14 +884,26 @@ struct Es2015Counts { failures: String, } +impl Es2015Counts { + /// The failures of the run with the option, then each run without it that panicked, marked + /// with `without`. + fn report(after: &Es2015Counts, before: &Es2015Counts, without: &str) -> String { + let mut report = after.failures.clone(); + for line in before.failures.lines().filter(|l| l.ends_with(": PANIC")) { + report.push_str(&format!("{line} ({without})\n")); + } + report + } +} + /// Runs the ES2015 subset: the tests under `test/language/` in [`ES2015_FOLDERS`], under /// `test/built-ins/` in [`ES2015_BUILT_INS`] and those [`es2015_name_test`] picks, whose feature /// tags are all in [`ES2015_FEATURES`], and the tests elsewhere under `test/language/` with feature /// tags that are all in it. Negative parse tests must give a `SyntaxError`; the other tests run in a /// new realm after the harness, as [`run_tests`] runs them, skipping module and asynchronous tests /// and those that need a missing built-in. Each test is read twice, without and with -/// [`Options::es2015`], and the counts of both are printed; the failures with it go to -/// `es2015-failures.txt`. +/// [`Options::es2015`], and the counts of both are printed; the failures with it, and the runs +/// without it that panicked, go to `es2015-failures.txt`. fn run_es2015(dir: &Path) { let language = or_fail(inside(dir, "test/language")); assert!(language.is_dir(), "{} is not a test262 checkout", dir.display()); @@ -974,7 +987,7 @@ fn run_es2015(dir: &Path) { assert!(selected > 0, "no ES2015 tests under {}", language.display()); let [before, after] = counts; let report = dir.join("es2015-failures.txt"); - if let Err(e) = std::fs::write(&report, &after.failures) { + if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "without Options::es2015")) { println!("could not write {}: {e}", report.display()); } let line = |c: &Es2015Counts| { @@ -1338,23 +1351,26 @@ fn promise_builtins_run() { #[test] fn promise_async_completion_requires_an_exact_print_argument() { - assert!(run_promise_one("print('not Test262:AsyncTestComplete');", None, true).is_err()); - assert!(run_promise_one("print('Test262:AsyncTestComplete suffix');", None, true).is_err()); - assert!(run_promise_one("print('message', 'Test262:AsyncTestComplete');", None, true).is_ok()); - assert!(run_promise_one("print('Test262:AsyncTestComplete');", None, true).is_ok()); + let es2015 = Options { es2015: true, ..Options::default() }; + assert!(run_promise_one("print('not Test262:AsyncTestComplete');", None, true, &es2015).is_err()); + assert!(run_promise_one("print('Test262:AsyncTestComplete suffix');", None, true, &es2015).is_err()); + assert!(run_promise_one("print('message', 'Test262:AsyncTestComplete');", None, true, &es2015).is_ok()); + assert!(run_promise_one("print('Test262:AsyncTestComplete');", None, true, &es2015).is_ok()); } #[test] fn promise_async_failure_checks_each_print_argument() { - assert!(run_promise_one("print('Test262:AsyncTestComplete', 'Test262:AsyncTestFailure: failed');", None, true).is_err()); - assert!(run_promise_one("print('not Test262:AsyncTestFailure'); print('Test262:AsyncTestComplete');", None, true).is_ok()); + let es2015 = Options { es2015: true, ..Options::default() }; + assert!(run_promise_one("print('Test262:AsyncTestComplete', 'Test262:AsyncTestFailure: failed');", None, true, &es2015).is_err()); + assert!(run_promise_one("print('not Test262:AsyncTestFailure'); print('Test262:AsyncTestComplete');", None, true, &es2015).is_ok()); } -/// Runs one Promise test with a global `print` that collects every argument. An `async` test -/// needs an exact `Test262:AsyncTestComplete` argument and no `Test262:AsyncTestFailure` prefix. -fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> { - let options = Options { es2015: true, ..Options::default() }; - let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); +/// Runs one test that may be asynchronous in a new realm made with `options` and a global `print` +/// that collects every argument; an `async` test without a runtime negative needs an exact +/// `Test262:AsyncTestComplete` argument and no `Test262:AsyncTestFailure` prefix, and one with a +/// runtime negative must throw that error. +fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool, options: &Options) -> Result<(), String> { + let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); let printed = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); let out = printed.clone(); realm.define_function("print", move |args| { @@ -1439,7 +1455,8 @@ fn run_promise(dir: &Path) { let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; let script = if strict { format!("\"use strict\";\n{body}") } else { body }; let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); - match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous)) { + let es2015 = Options { es2015: true, ..Options::default() }; + match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous, &es2015)) { Ok(Ok(())) => counts.passed += 1, Ok(Err(why)) => { counts.failed += 1; @@ -1740,6 +1757,125 @@ fn run_tagged_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, options: & counts } +/// The folders under `test/language/` that hold tests of async functions and `await`. +const ASYNC_FOLDERS: &[&str] = &["expressions/async-function", "statements/async-function", "expressions/await", "expressions/async-arrow-function"]; + +/// The feature tags an async-function test may carry and still run: [`ES2015_FEATURES`], +/// `async-functions` and `Promise`. +const ASYNC_FEATURES: &[&str] = &["async-functions", "Promise"]; + +#[test] +fn async_functions_run() { + let Some(dir) = suite_dir() else { + println!("test262 async functions: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_async_functions(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests in [`ASYNC_FOLDERS`] whose feature tags are all in [`ES2015_FEATURES`] or +/// [`ASYNC_FEATURES`], twice: with [`Options::es2015`] alone and with [`Options::es2017`]. Negative +/// parse tests must not parse; the others run as [`run_promise`] runs them, `async` tests +/// included, skipping module tests and those that need a missing built-in. Prints the counts of +/// both and writes the failures with [`Options::es2017`], and the runs with [`Options::es2015`] +/// alone that panicked, to `async-function-failures.txt`. +fn run_async_functions(dir: &Path) { + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let done = harness("doneprintHandle.js"); + let missing = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]); + let es2015 = Options { es2015: true, ..Options::default() }; + let es2017 = Options { es2015: true, es2017: true, ..Options::default() }; + let editions = [es2015, es2017.clone()]; + let mut counts = [Es2015Counts::default(), Es2015Counts::default()]; + let (mut selected, mut skipped, mut other_features) = (0usize, 0usize, 0usize); + for folder in ASYNC_FOLDERS { + let root = or_fail(inside(dir, &format!("test/language/{folder}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + for path in or_fail(test_files(&root)) { + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if meta.features.iter().any(|f| !ES2015_FEATURES.contains(&f.as_str()) && !ASYNC_FEATURES.contains(&f.as_str())) { + other_features += 1; + continue; + } + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + if has("module") || meta.negative_phase.as_deref() == Some("resolution") { + skipped += 1; + continue; + } + let asynchronous = has("async"); + let expect_error = meta.negative_phase.as_deref() == Some("parse"); + let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if asynchronous { + includes.push_str(&done); + includes.push('\n'); + } + if !expect_error && needs_missing_builtin_in(&[&source, &includes], &missing, &es2017) { + skipped += 1; + continue; + } + selected += 1; + for (options, counts) in editions.iter().zip(counts.iter_mut()) { + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let outcome = if expect_error { + let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() }; + if parse(&text, options).is_err() { + counts.parse_passed += 1; + continue; + } + counts.parse_failed += 1; + "parsed; a SyntaxError was expected".to_string() + } else { + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous, options)) { + Ok(Ok(())) => { + counts.run_passed += 1; + continue; + } + Ok(Err(why)) => { + counts.run_failed += 1; + why + } + Err(_) => { + counts.run_failed += 1; + counts.panicked += 1; + "PANIC".to_string() + } + } + }; + counts.failures.push_str(&format!("{rel} ({mode}): {outcome}\n")); + } + } + } + } + assert!(selected > 0, "no async-function tests under {}", dir.display()); + let [before, after] = counts; + let report = dir.join("async-function-failures.txt"); + if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "with Options::es2015 alone")) { + println!("could not write {}: {e}", report.display()); + } + let line = |c: &Es2015Counts| { + format!( + "negative parse runs {} passed, {} failed; other runs {} passed, {} failed ({} panicked)", + c.parse_passed, c.parse_failed, c.run_passed, c.run_failed, c.panicked + ) + }; + println!( + "test262 async functions: {selected} tests. With Options::es2015 alone: {}. With Options::es2017: {}. Skipped {skipped} module \ + or missing-built-in tests and {other_features} tests with other feature tags. Failures: {}", + line(&before), + line(&after), + report.display() + ); + assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display()); +} + /// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing. fn skips(sources: &[&str]) -> bool { let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect(); @@ -1769,6 +1905,18 @@ fn a_source_that_does_not_tokenize_as_es2015_is_run_and_not_skipped() { assert!(needs_missing_builtin_in(&[unreadable, "var m = new Map();"], &missing, &modern)); } +#[test] +fn a_missing_name_in_a_template_that_can_run_as_code_skips() { + let missing: HashSet<&str> = ["Map"].into_iter().collect(); + let modern = Options { es2015: true, ..Options::default() }; + assert!(needs_missing_builtin_in(&[r#"eval("new Map()");"#], &missing, &modern)); + assert!(needs_missing_builtin_in(&["eval(`new Map()`);"], &missing, &modern)); + // A template key names the runner, as a string key does. + assert!(needs_missing_builtin_in(&["this[`eval`](`new Map()`);"], &missing, &modern)); + assert!(needs_missing_builtin_in(&[r#"var F = this[`Function`]; F("return new Map()")();"#], &missing, &modern)); + assert!(!needs_missing_builtin_in(&["assert(true, `a Map`);"], &missing, &modern)); +} + #[test] fn a_missing_name_in_code_skips() { assert!(skips(&["var m = new Map();"])); diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index efc9d44830..7e104e85f2 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -13,6 +13,7 @@ //! //! Entry points: [`Server::serve`] (stdio loop) and [`Server::handle_line`] (one message). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod backend; mod headless; diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 8dfdfd28e3..618c9d7529 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -261,6 +261,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle drawing the gaps of the selected Live Paint groups (those livePaint.info lists) in each group's Gap Preview Color while edges show → true when on", ), + ( + "view.curvatureComb", + "Show Curvature Comb", + "", + "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", + ), ( "type.hiddenCharacters", "Show Hidden Characters", @@ -1018,7 +1024,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", @@ -1543,7 +1549,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", @@ -1591,7 +1597,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.hyphenation", "Hyphenation…", "", - "{} open Hyphenation (the Paragraph panel menu's Hyphenation…) on the paragraphs the Paragraph panel acts on, filled in with the values it shows (dialog `hyphenation`: hyphenate, wordsLongerThan 1..25, afterFirst 1..15, beforeLast 1..15, hyphenLimit 0..25 (0: no limit), hyphenationZone (pt), hyphenateCapitalized): OK runs text.setFormat with the values that changed, as one undo step; an error with no type selected", + "{} open Hyphenation (the Paragraph panel menu's Hyphenation…) on the paragraphs the Paragraph panel acts on, filled in with the values it shows (dialog `hyphenation`: hyphenate, wordsLongerThan 1..25, afterFirst 1..15, beforeLast 1..15, hyphenLimit 0..25 (0: no limit), hyphenationZone (pt), hyphenateCapitalized; the fields after hyphenate take input only while it is true, and hyphenationZone, which only a single-line composer uses, never while every paragraph uses another composer): OK runs text.setFormat with the values that changed, as one undo step; an error with no type selected", ), ( "ui.tateChuYokoSettings", @@ -1768,7 +1774,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.placementOptionsDialog", "Placement Options…", "", - "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions", + "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo or Redo there (reopen the dialog)", ), ( "ui.relinkDialog", @@ -1991,7 +1997,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", + "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}", ), ( "print.printers", diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index df23cbb073..66f3c4327b 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -26,6 +26,7 @@ //! formats. //! //! The app walks its document and maps its drawing operations to the shared writers. +#![doc(test(attr(deny(unsafe_code))))] #[cfg(test)] mod bytes; diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index da7960af0f..0190233191 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -5,6 +5,7 @@ //! Béziers, and the pieces it splits curves into are refitted afterwards so results carry few //! anchors. See the crate README for the API overview. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod boolean; diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index b3b5de36a4..a093ecc9c0 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -1,5 +1,7 @@ use std::collections::HashMap; +use vectorcraft_geom::Vec2; + use super::exporter::{UNDECODED, address, blend, color, constant_mask, cover, in_range, norm, rects_overlap, rule, to_path, writable, xf}; use super::{ Affine, AppearanceItem, BezPath, BlendMode, Document, Exporter, Fill, FillRule, GradientKind, LineCap, LineJoin, Mark, Node, NodeKind, @@ -19,6 +21,37 @@ fn brushed(b: Option, reach: f64) -> Option { if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b } } +/// Can the patch shade its own outline without folding across it? The differences of adjacent +/// tensor control points bound each directional derivative in a convex cone. If every pair of +/// derivatives has the same strict orientation, averaging them along any segment keeps them +/// independent, so distinct parameter points cannot map to the same point. +fn unfolded_patch(points: [(f32, f32); 12]) -> bool { + let p = points.map(|(x, y)| Vec2::new(f64::from(x), f64::from(y))); + let top = [p[0], p[11], p[10], p[9]]; + let bottom = [p[3], p[4], p[5], p[6]]; + let left = [p[0], p[1], p[2], p[3]]; + let right = [p[9], p[8], p[7], p[6]]; + // Raise the linear blending terms of the Coons surface to cubic degree in each direction. + let net: [[Vec2; 4]; 4] = std::array::from_fn(|row| { + let v = row as f64 / 3.0; + std::array::from_fn(|col| { + let u = col as f64 / 3.0; + let bilinear = (p[0] * (1.0 - u) + p[9] * u) * (1.0 - v) + (p[3] * (1.0 - u) + p[6] * u) * v; + top[col] * (1.0 - v) + bottom[col] * v + left[row] * (1.0 - u) + right[row] * u - bilinear + }) + }); + let du: [[Vec2; 3]; 4] = std::array::from_fn(|row| std::array::from_fn(|col| net[row][col + 1] - net[row][col])); + let dv: [[Vec2; 4]; 3] = std::array::from_fn(|row| std::array::from_fn(|col| net[row + 1][col] - net[row][col])); + let orientation = du[0][0].cross(dv[0][0]).signum(); + du.into_iter().flatten().all(|u| { + dv.iter().flatten().all(|v| { + let cross = u.cross(*v) * orientation; + // Keep near-parallel directions on the existing clipped path through PDF quantization. + cross > 0.0 && cross * cross > 1e-12 * u.hypot2() * v.hypot2() + }) + }) +} + #[cfg(test)] std::thread_local! { /// The objects this thread has measured for the walk and for the links (tests). @@ -542,7 +575,7 @@ impl Exporter<'_> { } } - /// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading filling its outline (ISO 32000-1, + /// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading (ISO 32000-1, /// 8.7.4.5.7): each patch blends its corner colours bilinearly, as the canvas draws it, and /// the viewer or RIP does so smoothly at its own resolution. Cutting the mesh into flat quads /// instead banded, left seams between them, and made files with many meshes very large. @@ -560,7 +593,6 @@ impl Exporter<'_> { if !writable(s, Affine::IDENTITY, bounds) { return false; } - let Some(path) = to_path(s, &m.outline().to_bezpath()) else { return false }; let page: Vec = m.points.iter().map(|p| self.page_color(&p.color)).collect(); let mixed = page.windows(2).any(|w| w[0].model() != w[1].model()); let rgb = page.iter().any(|c| matches!(c, vectorcraft_color::Color::Rgb { .. } | vectorcraft_color::Color::Lab { .. })); @@ -584,6 +616,14 @@ impl Exporter<'_> { patches.push(krilla::paint::MeshPatch { points, colors, opacities: [NormalizedF32::ONE; 4] }); } } + // An unfolded single patch shades its own outline. Filling that exact outline makes some + // readers antialias it twice and leave seams where patches touch. Keep the outline for + // folded geometry and for meshes with more than one patch, which can overlap themselves. + let bounds_path = match patches.as_slice() { + [patch] if unfolded_patch(patch.points) => to_path(s, &bounds.inflate(1.0, 1.0).to_path(0.1)), + _ => None, + }; + let Some(path) = bounds_path.or_else(|| to_path(s, &m.outline().to_bezpath())) else { return false }; let mesh = krilla::paint::MeshGradient { patches, transform: xf(Affine::IDENTITY), anti_alias: false }; s.set_stroke(None); s.set_fill(Some(Fill { paint: mesh.into(), opacity: NormalizedF32::ONE, rule: krilla::paint::FillRule::NonZero })); diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 0cfb8ea805..64da7fb8d5 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -1098,7 +1098,7 @@ impl<'p> Builder<'p> { a.data, ) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = super::state::png(&raw)?; let blob = ImageBlob::new("image/png", png); let k = blob.content_key(); self.images.insert(k.clone(), blob); diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 629113680c..c85f36bd7f 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -378,19 +378,25 @@ pub(super) fn bounds(nodes: &[Arc]) -> Option { nodes.iter().try_fold(None, |acc, n| n.visual_bounds().map(|b| Some(acc.map_or(b, |a: Rect| a.union(b)))))? } +/// `img` as a PNG with fast compression, which keeps opening a file with large images quick. +pub(super) fn png(img: &craft_image_codecs::Image) -> Option> { + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + craft_image_codecs::encode(img, craft_image_codecs::Format::Png, &opts).ok() +} + pub(super) fn rgba_png(rgba: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn rgb_png(rgb: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn gray_png(gray: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn resize_alpha(a: &LumaData, w: u32, h: u32) -> Vec { diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 2dc6f1ec0a..a7118fd37a 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -42,6 +42,7 @@ //! security handler, the algorithm following the compatibility ([`Encryption`]); either password //! opens an encrypted file. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod editing; mod encrypt; diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index ef20585154..fc9f306ffe 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -331,6 +331,56 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() { assert!(masked(&r.document)[0].1.is_none()); } +/// A masked CMYK image drawn twice, at two sizes, carries its opacity mask both times: the same +/// mask image, fitted to each drawing. Drawn twice with a mask that hides nothing, it has no mask +/// either time. +#[test] +fn a_masked_cmyk_image_drawn_twice_keeps_its_mask_both_times() { + let z = |data: &[u8]| crate::output::deflate(data).unwrap(); + let file = |mask: &[u8]| { + let content = "q 50 0 0 50 10 10 cm /Im0 Do Q q 30 0 0 20 100 40 cm /Im0 Do Q"; + pdf_of(&[ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >>".to_vec(), + stream("", content.as_bytes()), + stream( + &format!("/Type /XObject /Subtype /Image {}", cmyk_dict(2, 2, "/SMask 6 0 R /Filter /FlateDecode")), + &z(&flat([0, 102, 255, 0], 4)), + ), + stream("/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8", mask), + ]) + }; + let images = |d: &Document| { + let NodeKind::Layer { children, .. } = &d.layers[0].kind else { panic!() }; + children.iter().filter(|n| matches!(n.kind, NodeKind::Image(_))).cloned().collect::>() + }; + let r = import_with_report(&file(&[255, 128, 255, 128]), &ImportOptions::default()).unwrap(); + let drawn = images(&r.document); + assert_eq!(drawn.len(), 2); + let mut keys = vec![]; + for n in &drawn { + let mask = n.extras().mask.as_ref().expect("an opacity mask on each drawing"); + let NodeKind::Image(a) = &mask.art.kind else { panic!("mask art is an image: {:?}", mask.art.kind) }; + assert_eq!((a.width, a.height), (2, 2)); + assert!(near(n.geometric_bounds(), mask.art.geometric_bounds()), "{:?} {:?}", n.geometric_bounds(), mask.art.geometric_bounds()); + keys.push(a.key.clone()); + } + assert_eq!(keys[0], keys[1], "one mask image"); + assert!(drawn[0].geometric_bounds() != drawn[1].geometric_bounds(), "two sizes"); + let r = import_with_report(&file(&[255; 4]), &ImportOptions::default()).unwrap(); + let drawn = images(&r.document); + assert_eq!(drawn.len(), 2); + assert!(drawn.iter().all(|n| n.extras().mask.is_none()), "a mask that hides nothing adds none, either time"); +} + +fn near(a: Option, b: Option) -> bool { + match (a, b) { + (Some(a), Some(b)) => [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-6), + _ => false, + } +} + /// Every image blob a document's art uses (mask art included). fn all_images(d: &Document) -> Vec<&ImageBlob> { let mut keys = vec![]; diff --git a/crates/pdf/src/tests/import_color.rs b/crates/pdf/src/tests/import_color.rs index 086b711aec..a7e83e56f3 100644 --- a/crates/pdf/src/tests/import_color.rs +++ b/crates/pdf/src/tests/import_color.rs @@ -560,3 +560,63 @@ fn rgb_numbers_stand_in_editor_documents_only() { assert!(near(color(true), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(true)); assert!(!near(color(false), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(false)); } + +/// The space the scan of a page holding colour spaces `spaces` finds for a Gold Separation (tint +/// transform [`GOLD_TINT`]). +fn gold_space(spaces: &str) -> Space { + use craft::pdf::interpret::Function; + use craft::pdf::syntax::object::{FromBytes, Object}; + let key = format!("{:?}", Function::new(&Object::from_bytes(GOLD_TINT.as_bytes()).unwrap()).unwrap()); + let pdf = craft::pdf::syntax::Pdf::new(pdf(&[page_with(spaces, &[])], None)).unwrap(); + Colors::new(&pdf, vec![]).space_of(&format!("ColorSpace(Separation(Separation {{ tint_transform: {key} }}))"), 1, None) +} + +const GOLD_TINT: &str = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>"; + +/// The scan for ink spaces looks 32 levels into an object and no deeper. +#[test] +fn ink_spaces_nested_past_the_scan_depth_are_not_found() { + let gold = format!("[/Separation /Gold /DeviceCMYK {GOLD_TINT}]"); + let nested = |levels: usize| format!("/A {}{gold}{}", "[".repeat(levels), "]".repeat(levels)); + assert_eq!(gold_space(&nested(20)), Space::Inks(0)); + assert_eq!(gold_space(&nested(40)), Space::Other); +} + +/// The scan keeps 4,096 ink spaces: a space after that many others is not found. +#[test] +fn ink_spaces_past_the_scan_count_are_not_found() { + let filler = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 0 0] /N 1 >>"; + let spaces = |n: usize| -> String { + let fillers: String = (0..n).map(|i| format!("[/Separation /Ink{i} /DeviceCMYK {filler}]")).collect(); + format!("/A [{fillers}[/Separation /Gold /DeviceCMYK {GOLD_TINT}]]") + }; + assert_eq!(gold_space(&spaces(4095)), Space::Inks(4095)); + assert_eq!(gold_space(&spaces(4096)), Space::Other); +} + +/// A one-ink image of more pixels than a CMYK image may have is refused before its samples are +/// decoded; the same samples read at a smaller size are not. +#[test] +fn one_ink_images_past_the_pixel_cap_are_refused() { + use std::io::Write; + let side = 8193u32; + let row = (side as usize).div_ceil(8); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + z.write_all(&vec![0u8; row * side as usize]).unwrap(); + let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02x}")).collect(); + let image = format!( + "<< /Type /XObject /Subtype /Image /Width {side} /Height {side} /BitsPerComponent 1 /ColorSpace [/Separation /Gold /DeviceCMYK {GOLD_TINT}] /Filter [/ASCIIHexDecode /FlateDecode] /Length {} >>\nstream\n{hex}>\nendstream", + hex.len() + 1 + ); + let file = craft::pdf::syntax::Pdf::new(pdf_with(&[PdfPage::new(10.0, 10.0, "")], &[&image], None)).unwrap(); + let st = file + .objects() + .into_iter() + .find_map(|o| match o { + craft::pdf::syntax::object::Object::Stream(s) if s.dict().contains_key(b"Width") => Some(s), + _ => None, + }) + .unwrap(); + assert_eq!(crate::import_image::tint_gray(&st, side, side).map(|g| g.len()), Err(crate::import_image::UNREAD_TINTS)); + assert_eq!(crate::import_image::tint_gray(&st, 16, 2), Ok(vec![255; 32])); +} diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 5fdafeb5fc..ea74b0dc2d 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Knockout, LineCap, LineJoin, Node, NodeId, NodeKind, OpacityMask}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, ImageBlob, Knockout, LineCap, LineJoin, Node, NodeId, NodeKind, OpacityMask}; use vectorcraft_geom::{Rect, shapes}; use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; @@ -147,6 +147,56 @@ fn a_luminosity_soft_mask_of_an_image_keeps_the_images_colour() { assert_eq!(mask_image_pixels("Luminosity"), [[0, 0, 0, 255], [0, 0, 0, 0]]); } +/// Whether PNG `png` stores its pixels at the fastest level a zlib header names (RFC 1950 §2.2, +/// FLEVEL 0). +fn fastest_png(png: &[u8]) -> bool { + let mut at = 8; + while let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) { + if kind == b"IDAT" { + return png.get(at + 9).is_some_and(|flg| flg >> 6 == 0); + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + } + panic!("a PNG with image data: {png:?}"); +} + +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image with a soft mask, the soft mask of a CMYK image as its opacity +/// mask, a gray image and an image mask painted in a color. +#[test] +fn imported_images_are_stored_with_fast_compression() { + let g = first_extra(1); + let image = |space: &str, data: &str| { + stream( + &format!( + "/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /{space} /BitsPerComponent 8 /Filter /ASCIIHexDecode /SMask {} 0 R", + g + 4 + ), + data, + ) + }; + let rgb = image("DeviceRGB", "FF000000FF00>"); + let cmyk = image("DeviceCMYK", "0A141E28 00667F08>"); + let gray = + stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "2080>"); + let stencil = stream("/Type /XObject /Subtype /Image /Width 8 /Height 1 /ImageMask true /BitsPerComponent 1 /Filter /ASCIIHexDecode", "F0>"); + let smask = + stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "FF40>"); + let bytes = one_page( + "q 40 0 0 40 0 0 cm /Im0 Do Q q 40 0 0 40 50 0 cm /Im1 Do Q q 40 0 0 40 0 50 cm /Im2 Do Q 0 0 1 rg q 40 0 0 40 50 50 cm /Im3 Do Q", + &format!("/XObject << /Im0 {g} 0 R /Im1 {} 0 R /Im2 {} 0 R /Im3 {} 0 R >>", g + 1, g + 2, g + 3), + &[&rgb, &cmyk, &gray, &stencil, &smask], + ); + let d = open(&bytes); + let masks = all(&d).iter().filter(|n| n.extras().mask.is_some()).count(); + assert_eq!(masks, 1, "the CMYK image's soft mask as an opacity mask"); + let pngs: Vec<&ImageBlob> = d.images.values().filter(|b| b.mime == "image/png").collect(); + assert_eq!(pngs.len(), 4, "the RGB image, the CMYK image's mask, the gray image and the image mask: {:?}", d.images.keys()); + for b in pngs { + assert!(fastest_png(&b.bytes), "{:?}", &b.bytes[..b.bytes.len().min(48)]); + } +} + #[test] fn a_luminosity_soft_mask_becomes_an_opacity_mask() { let d = open(&masked("/S /Luminosity", "1 1 1 rg 0 0 50 100 re f")); @@ -320,6 +370,53 @@ fn tiling_patterns_become_pattern_swatches() { assert_eq!(colors, vec![Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]); } +/// Links in the chains of nested patterns and soft masks below: more than are read. +const CHAIN: usize = 12; + +/// The warnings of opening a page drawing `content` with `resources`, plus `objects`. +fn warnings_of(objects: &[String], resources: &str, content: &str) -> Vec { + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + open_with(&one_page(content, resources, &extra), |_| {}).warnings +} + +/// Tiling patterns whose cells fill with the next pattern are read only so many levels deep: a +/// chain of them opens, with a warning. +#[test] +fn patterns_nested_too_deeply_stop_with_a_warning() { + let first = first_extra(1); + let cells: Vec = (0..CHAIN) + .map(|i| { + let (resources, content) = if i + 1 < CHAIN { + (format!("/Pattern << /P0 {} 0 R >>", first + i + 1), "/Pattern cs /P0 scn 0 0 5 5 re f") + } else { + (String::new(), "1 0 0 rg 0 0 5 5 re f") + }; + let cell = "/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10"; + stream(&format!("{cell} /Resources << {resources} >>"), content) + }) + .collect(); + let w = warnings_of(&cells, &format!("/Pattern << /P0 {first} 0 R >>"), "/Pattern cs /P0 scn 0 0 100 100 re f"); + assert!(w.iter().any(|w| w.contains("tiling patterns nested too deeply")), "{w:?}"); +} + +/// Soft masks whose groups draw through the next mask are read only so many levels deep: a chain +/// of them opens, with a warning. +#[test] +fn soft_masks_nested_too_deeply_stop_with_a_warning() { + let first = first_extra(1); + let mask = |i: usize| format!("/ExtGState << /GS0 << /SMask << /Type /Mask /S /Luminosity /G {} 0 R >> >> >>", first + i); + let groups: Vec = (0..CHAIN) + .map(|i| { + let (resources, content) = + if i + 1 < CHAIN { (mask(i + 1), "/GS0 gs 1 1 1 rg 0 0 100 100 re f") } else { (String::new(), "1 1 1 rg 0 0 100 100 re f") }; + let group = "/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /CS /DeviceRGB >>"; + stream(&format!("{group} /Resources << {resources} >>"), content) + }) + .collect(); + let w = warnings_of(&groups, &mask(0), "/GS0 gs 1 0 0 rg 0 0 100 100 re f"); + assert!(w.iter().any(|w| w.contains("soft masks nested too deeply")), "{w:?}"); +} + // ---------- text ---------- const HELVETICA: &str = @@ -662,6 +759,85 @@ fn a_mesh_shading_of_thousands_of_patches_becomes_gradient_meshes() { assert_eq!(all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Mesh(_))).count(), 5000); } +/// The gradient meshes a page drawing shading `sh` (`/Sh0 sh`) comes in as, with the import's +/// warnings. +fn meshes_of(sh: &str) -> (Vec, Vec) { + let s = first_extra(1); + let r = open_with(&one_page("/Sh0 sh", &format!("/Shading << /Sh0 {s} 0 R >>"), &[sh]), |_| {}); + let meshes = all(&r.document).into_iter().filter_map(|n| if let NodeKind::Mesh(m) = n.kind { Some(m) } else { None }).collect(); + (meshes, r.warnings) +} + +/// A tensor-product patch mesh shading's dictionary for [`tensor_patch`] data. +const TENSOR_MESH: &str = "/ShadingType 7 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode"; + +/// One tensor patch over the same boundary as [`coons_patch`], with its four inner points far +/// outside it at (250, 250). +fn tensor_patch() -> Vec { + let mut data = coons_patch(); + let colors = data.split_off(1 + 24); + data.extend([250; 8]); + data.extend(colors); + data +} + +/// A triangle mesh shading's dictionary (types 4 and 5 share their vertex layout). +const TRIANGLE_MESH: &str = "/ShadingType 4 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode"; + +/// One triangle: red at (10, 10), green at (90, 10), blue at (50, 90), each vertex with flag 0. +fn triangle() -> Vec { + [[0, 10, 10, 255, 0, 0], [0, 90, 10, 0, 255, 0], [0, 50, 90, 0, 0, 255]].concat() +} + +/// A tensor-product patch mesh (type 7) comes in as the gradient mesh of its boundary, the same +/// mesh a Coons patch over that boundary gives: its inner points do not move it. +#[test] +fn a_tensor_patch_mesh_becomes_the_gradient_mesh_of_its_boundary() { + let (tensor, warnings) = meshes_of(&stream(TENSOR_MESH, &hex(&tensor_patch()))); + let [m] = tensor.as_slice() else { panic!("one mesh: {tensor:?} {warnings:?}") }; + assert_eq!((m.rows, m.cols), (1, 1)); + let at = |r, c| &m.points[m.idx(r, c)]; + assert!((at(0, 0).p - kurbo::Point::new(10.0, 90.0)).hypot() < 0.01, "{:?}", at(0, 0).p); + assert!((at(1, 1).p - kurbo::Point::new(90.0, 10.0)).hypot() < 0.01, "{:?}", at(1, 1).p); + assert_eq!(at(0, 0).color.to_rgb(), [1.0, 0.0, 0.0]); + assert_eq!(at(1, 0).color.to_rgb(), [0.0, 1.0, 0.0]); + assert_eq!(at(1, 1).color.to_rgb(), [0.0, 0.0, 1.0]); + assert_eq!(at(0, 1).color.to_rgb(), [1.0, 1.0, 1.0]); + let (coons, _) = meshes_of(&stream(COONS_MESH, &hex(&coons_patch()))); + assert_eq!(Some(m), coons.first(), "the mesh of a Coons patch over the same boundary"); +} + +/// A triangle mesh (types 4 and 5) comes in as one gradient mesh per triangle, a patch whose last +/// two corners are the triangle's third vertex, each corner in its vertex's color. +#[test] +fn a_triangle_mesh_becomes_a_gradient_mesh() { + let (meshes, warnings) = meshes_of(&stream(TRIANGLE_MESH, &hex(&triangle()))); + let [m] = meshes.as_slice() else { panic!("one mesh: {meshes:?} {warnings:?}") }; + assert_eq!((m.rows, m.cols), (1, 1)); + let at = |r, c| &m.points[m.idx(r, c)]; + // PDF y 10 is page y 90. + let want = [((0, 0), (10.0, 90.0), [1.0, 0.0, 0.0]), ((1, 0), (90.0, 90.0), [0.0, 1.0, 0.0]), ((1, 1), (50.0, 10.0), [0.0, 0.0, 1.0])]; + for ((r, c), (x, y), color) in want { + assert!((at(r, c).p - kurbo::Point::new(x, y)).hypot() < 0.01, "({r}, {c}): {:?}", at(r, c).p); + assert_eq!(at(r, c).color.to_rgb(), color, "({r}, {c})"); + } + assert_eq!(at(0, 1).p, at(1, 1).p, "the third vertex closes the patch"); +} + +/// A tensor patch or triangle mesh of more patches than the importer reads is not a gradient mesh: +/// it comes in as a flat gray, with a warning. +#[test] +fn a_tensor_or_triangle_mesh_over_the_patch_limit_is_a_flat_gray() { + let over = 16_385; + let tensor: Vec = std::iter::repeat_n(tensor_patch(), over).flatten().collect(); + let triangles: Vec = std::iter::repeat_n(triangle(), over).flatten().collect(); + for (name, sh) in [("tensor", stream(TENSOR_MESH, &hex(&tensor))), ("triangle", stream(TRIANGLE_MESH, &hex(&triangles)))] { + let (meshes, warnings) = meshes_of(&sh); + assert!(meshes.is_empty(), "{name}: {} meshes", meshes.len()); + assert!(warnings.iter().any(|w| w.contains("flat grey")), "{name}: {warnings:?}"); + } +} + /// A stroke painted with a mesh shading (how Illustrator writes a freeform gradient on a stroke) /// is the mesh clipped to the area the stroke paints, dashes included, not a flat grey. #[test] diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index 33ada6d549..3badde2181 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -506,3 +506,50 @@ fn art_deep_in_tags_inside_a_layer_reaches_it() { let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]); } + +/// Art marked with a membership dictionary is skipped by its policy over its groups, by the page's +/// walk as by the interpreter, so each shown path keeps the ink the walk found it painted in: with +/// "Shapes" on and "Hidden" off, AllOn and AllOff over both are hidden, AnyOff and the default +/// AnyOn show. Groups named by a single reference, not an array, count the same: AllOff over +/// "Hidden" alone shows and AllOff over "Shapes" alone is hidden. +#[test] +fn membership_dictionaries_show_art_by_their_policy() { + let (objs, catalog, [a, b]) = groups(1, "/OFF [{B}]"); + let both = format!("[{a} 0 R {b} 0 R]"); + let runs = [ + ("AllOn", format!("{both} /P /AllOn")), + ("AnyOff", format!("{both} /P /AnyOff")), + ("AllOff", format!("{both} /P /AllOff")), + ("AnyOn", both.clone()), + ("OffAlone", format!("{b} 0 R /P /AllOff")), + ("OnAlone", format!("{a} 0 R /P /AllOff")), + ]; + let memberships: Vec = runs.iter().map(|(_, m)| format!("<< /Type /OCMD /OCGs {m} >>")).collect(); + let first = first_extra(1) + 2; + // Every ink has the same tint transform: only the walk tells the interpreter's paths apart. + let tint = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>"; + let mut content = String::new(); + let (mut props, mut spaces) = (String::new(), String::new()); + for (i, (ink, _)) in runs.iter().enumerate() { + content += &format!("/OC /M{i} BDC /CS{i} cs 1 scn {} 10 5 5 re f EMC ", 10 * i); + props += &format!("/M{i} {} 0 R ", first + i); + spaces += &format!("/CS{i} [/Separation /{ink} /DeviceCMYK {tint}] "); + } + let page = PdfPage { resources: format!("/Properties << {props}>> /ColorSpace << {spaces}>>"), ..PdfPage::new(100.0, 100.0, &content) }; + let mut extra: Vec<&str> = vec![&objs[0], &objs[1]]; + extra.extend(memberships.iter().map(String::as_str)); + let options = ImportOptions { layers: false, ..Default::default() }; + let r = import_with_report(&pdf_with_catalog(&[page], &extra, &catalog, None), &options).unwrap(); + assert_eq!(names(&r.document), ["Page 1"]); + let inks: Vec> = r.document.layers[0] + .children() + .unwrap() + .iter() + .map(|n| match n.appearance.fill().map(|f| &f.paint) { + Some(vectorcraft_color::Paint::Solid { swatch, .. }) => swatch.clone(), + _ => None, + }) + .collect(); + let shown = ["AnyOff", "AnyOn", "OffAlone"].map(|s| Some(s.to_string())); + assert_eq!(inks, shown, "{:?}", r.warnings); +} diff --git a/crates/pdf/src/tests/mesh_export.rs b/crates/pdf/src/tests/mesh_export.rs index b2e8ecb2f6..b36926da21 100644 --- a/crates/pdf/src/tests/mesh_export.rs +++ b/crates/pdf/src/tests/mesh_export.rs @@ -2,12 +2,16 @@ //! viewer blends each patch's corner colours smoothly, instead of the mesh being cut into small //! flat-coloured paths that band, show seams and make the file large. +use craft::pdf::syntax::content::{TypedIter, ops::TypedInstruction}; +use craft::pdf::syntax::object::{Name, Object}; use vectorcraft_color::Color; use vectorcraft_doc::live::{GradientMesh, MeshAppearance}; use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; use vectorcraft_testkit::raster::{assert_similar, render_artboard}; +use super::import_fidelity::stream; use crate::*; /// A 200 × 200 pt document with a 2 × 2 mesh over (20, 20)–(180, 180), its nine points coloured @@ -44,6 +48,76 @@ fn kinds(d: &Document) -> (usize, usize) { (meshes, paths) } +fn import_patches(boundaries: &[[(u8, u8); 12]]) -> Document { + use std::fmt::Write as _; + let mut data = String::new(); + for boundary in boundaries { + data.push_str("00"); // Every patch supplies all its vertices. + for (x, y) in boundary { + write!(data, "{x:02X}{y:02X}").unwrap(); + } + data.push_str(&"28465A".repeat(4)); + } + data.push('>'); + let shading = stream( + "/ShadingType 6 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 \ + /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode", + &data, + ); + let page = PdfPage { + resources: format!("/Shading << /Mesh {} 0 R >>", first_extra(1)), + ..PdfPage::new(100.0, 100.0, "q 0.8 0 0 0.8 10 10 cm /Mesh sh Q") + }; + let imported = import(&pdf_with(&[page], &[&shading], None)).unwrap(); + assert_eq!(kinds(&imported).0, boundaries.len()); + imported +} + +fn has_curved_outline(bytes: &[u8]) -> bool { + let output = crate::pages::open(bytes, None).unwrap(); + let pages = output.pages(); + let has_curve = |content: &[u8]| { + let mut ops = TypedIter::new(content); + while let Some(op) = ops.next() { + if matches!(op, TypedInstruction::CubicTo(_) | TypedInstruction::CubicStartTo(_) | TypedInstruction::CubicEndTo(_)) { + return true; + } + } + false + }; + if has_curve(pages.iter().next().unwrap().page_stream().unwrap()) { + return true; + } + output.objects().into_iter().any(|object| match object { + Object::Stream(form) if form.dict().get::>(b"Subtype").is_some_and(|name| name.as_ref() == b"Form") => { + has_curve(&form.decoded().unwrap()) + } + _ => false, + }) +} + +#[test] +fn joined_opaque_pdf_meshes_keep_their_shading_edges_on_export() { + // The same cubic, in opposite directions, is the two patches' inner edge. + let imported = import_patches(&[ + [(10, 95), (10, 65), (10, 35), (10, 5), (25, 5), (40, 5), (55, 5), (61, 30), (41, 70), (45, 95), (35, 95), (22, 95)], + [(45, 95), (41, 70), (61, 30), (55, 5), (68, 5), (82, 5), (90, 5), (90, 35), (90, 65), (90, 95), (75, 95), (60, 95)], + ]); + let bytes = export(&imported, &PdfOptions::default()).unwrap(); + assert!(!has_curved_outline(&bytes), "the writer must leave the shared curved edge to the shading itself"); + let reimported = import(&bytes).unwrap(); + assert_eq!(kinds(&reimported).0, 2, "both patches still export as vector shadings"); + assert_similar(&render_artboard(&imported), &render_artboard(&reimported), 6.0, 0.01); +} + +#[test] +fn folded_pdf_mesh_still_uses_its_outline() { + let imported = + import_patches(&[[(10, 95), (92, 65), (93, 35), (10, 5), (25, 5), (40, 5), (90, 5), (4, 30), (3, 70), (90, 95), (65, 95), (42, 95)]]); + let bytes = export(&imported, &PdfOptions::default()).unwrap(); + assert!(has_curved_outline(&bytes), "a rectangle would expose folded paint outside the intended outline"); +} + #[test] fn a_gradient_mesh_is_written_as_a_smooth_patch_shading() { let d = doc(rgb, 1.0); diff --git a/crates/pdf/src/tests/textstroke.rs b/crates/pdf/src/tests/textstroke.rs index 109685c9c7..01b4035be5 100644 --- a/crates/pdf/src/tests/textstroke.rs +++ b/crates/pdf/src/tests/textstroke.rs @@ -556,6 +556,25 @@ fn a_glyph_stroked_again_where_it_was_drawn_stays_one_type_object() { } } +/// The last glyph of a run stroked again where it was drawn, in another stroke color, splits off +/// into its own run with that stroke; the glyphs before it keep theirs. +#[test] +fn the_last_glyph_stroked_again_in_another_color_splits_off_with_that_stroke() { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + // Helvetica's A is 667 units wide, so in 48-point type B stands at 20 + 32.016. + let content = "0 0 0 RG 1 1 0.8 rg 3 w BT /F1 48 Tf 1 0 0 1 20 80 Tm 2 Tr (AB) Tj 1 0 0 RG 1 Tr 1 0 0 1 52.016 80 Tm (B) Tj 0 Tr ET"; + let resources = "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>"; + let d = import(&pdf(&[PdfPage { resources: resources.into(), ..PdfPage::new(300.0, 200.0, content) }], None)).unwrap(); + let mut types = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + types.push(t.runs.iter().map(|r| (r.text.clone(), !r.style.fill.is_none(), r.style.stroke.color())).collect::>()); + } + }); + let want = [vec![("A".to_string(), true, Some(Color::BLACK)), ("B".to_string(), true, Some(Color::rgb(1.0, 0.0, 0.0)))]]; + assert_eq!(types, want); +} + /// A stroke pass longer than the importer holds at once ([`MAX_HELD`] strokes) goes over its own /// operator's glyphs, filled right before it, also when an operator before it filled the same /// glyphs at the same places: `A` and 4,095 `B`s filled, then `A` and 4,096 `B`s filled and diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index aecb0bd533..621f5e79bc 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -44,7 +44,3 @@ vectorcraft-plugins = { path = ".", features = ["test-steady"] } [features] # `vectorcraft_plugins::steady` for other crates' tests (dev-dependencies only). test-steady = [] - -# For CI's test selection: `tests/grant_sites.rs` reads the sources of every crate. -[package.metadata.craft] -reads-every-member = true diff --git a/crates/plugins/src/events.rs b/crates/plugins/src/events.rs new file mode 100644 index 0000000000..53a5ad2a2a --- /dev/null +++ b/crates/plugins/src/events.rs @@ -0,0 +1,94 @@ +//! Events a plug-in may react to, from plug-in API level 2 on: its manifest's `events` names them +//! ([`Event`]) and lists the `events` permission, and the module exports +//! `vc_event(event_ptr: i32, event_len: i32) -> i32`. After a change has finished, the host calls +//! `vc_event` in a fresh instance with a small JSON object that names the event and the document +//! ([`crate::Plugin::run_event`]). A handler only reads: the host applies nothing it returns, and +//! a command call that would change a document is refused ([`crate::host`]). +//! +//! The limits are VectorCraft's own values: [`EVENT_FUEL`] instructions and +//! [`EVENT_WALL_TIME_MS`] for one handler, an event of at most [`MAX_EVENT_BYTES`], and +//! [`MAX_EVENT_IDS`] selected ids in a `selection.changed` event. + +/// The plug-in API level that adds `events`, the `events` permission and `vc_event`. +pub const EVENTS_API: u32 = 2; + +/// Instructions one handler may use, or the plug-in's own budget when that is smaller. +pub const EVENT_FUEL: u64 = 5_000_000; + +/// Wall-clock budget of one handler, in milliseconds, or the plug-in's own when that is shorter. +pub const EVENT_WALL_TIME_MS: u64 = 200; + +/// Largest event JSON the host hands a handler, in bytes. +pub const MAX_EVENT_BYTES: usize = 64 * 1024; + +/// Most selected object ids a `selection.changed` event lists; a larger selection sends the first +/// ones with `truncated: true` and its whole `count`. That many ids of the largest value still fit +/// in [`MAX_EVENT_BYTES`]. +pub const MAX_EVENT_IDS: usize = 2048; + +/// Failed handlers in a row after which the host stops calling a plug-in's handler until the app +/// starts again. +pub const MAX_EVENT_FAILURES: u32 = 3; + +/// One thing a plug-in may react to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Event { + /// The selection in a document changed: other objects, anchors or segments, or nothing. + SelectionChanged, + /// A file opened as a document (File › Open, a recent file, New from Template). + DocumentOpened, + /// A document was saved to its own file (Save, Save As). + DocumentSaved, + /// The current layer changed, or a layer was added, deleted, moved or given other options. + LayerChanged, +} + +impl Event { + /// Every event, in the order the docs list them. + pub const ALL: [Event; 4] = [Event::SelectionChanged, Event::DocumentOpened, Event::DocumentSaved, Event::LayerChanged]; + + /// Its name in a manifest's `events`, which is also the event's `type`. + pub fn name(self) -> &'static str { + match self { + Event::SelectionChanged => "selection.changed", + Event::DocumentOpened => "document.opened", + Event::DocumentSaved => "document.saved", + Event::LayerChanged => "layer.changed", + } + } + + /// The event named `name`. + pub fn parse(name: &str) -> Option { + Event::ALL.into_iter().find(|e| e.name() == name) + } + + /// Whether the event is still delivered when its document has closed before the delivery: + /// an open or a save is, a selection or layer change is not. + pub fn outlives_document(self) -> bool { + matches!(self, Event::DocumentOpened | Event::DocumentSaved) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_round_trip() { + for e in Event::ALL { + assert_eq!(Event::parse(e.name()), Some(e)); + } + assert_eq!(Event::parse("selection.change"), None); + assert_eq!(Event::parse(""), None); + } + + /// A `selection.changed` event that lists the most ids, each of the largest value, fits in the + /// largest event a handler is given. + #[test] + fn the_largest_selection_event_fits() { + let ids = vec![u64::MAX; MAX_EVENT_IDS]; + let event = serde_json::json!({"type": "selection.changed", "document": u64::MAX, "count": u64::MAX, "ids": ids, "truncated": true}); + let len = serde_json::to_vec(&event).unwrap().len(); + assert!(len <= MAX_EVENT_BYTES, "{len} bytes"); + } +} diff --git a/crates/plugins/src/js.rs b/crates/plugins/src/js.rs index a8fa158c41..b10506011f 100644 --- a/crates/plugins/src/js.rs +++ b/crates/plugins/src/js.rs @@ -460,6 +460,8 @@ mod tests { assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}"); let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]}))); assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}"); + let e = refused(bundle("test.js.events", ok, json!({"api": 2, "permissions": ["events"], "events": ["selection.changed"]}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("can't list the permission `events`")), "{e:?}"); let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"}))); assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}"); let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"}))); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 8e0c603f71..4f79939c62 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -34,17 +34,20 @@ //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A //! filter or a live effect may also add menu commands of its own ([`Command`]), which the host //! runs through `vc_run` with the command's id in `_context`. Its name, command labels and -//! parameter text may come in other languages too ([`translations`]). The web build checks modules and -//! runs filters in a worker of its own ([`worker`]). +//! parameter text may come in other languages too ([`translations`]). Any kind may also react to the +//! [`events`] its manifest names, through `vc_event`, without changing the document. The web +//! build checks modules and runs filters in a worker of its own ([`worker`]). //! //! An object filter may also be written in JavaScript ([`js`]): its manifest gives //! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each //! run, with the same input, output, permissions and budgets. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod deferred; pub mod dialog; pub mod effect; +pub mod events; pub mod export; pub mod generate; pub mod host; @@ -66,6 +69,7 @@ pub mod wat; pub mod worker; pub use dialog::ParamUi; +pub use events::Event; pub use host::{LogLevel, LogLine, Report}; pub use manifest::{ Budget, Command, ContextMenu, ContextPlace, ContextSection, ContextWhen, InputKind, Kind, Manifest, MenuPlace, OutputKind, Param, ParamSpec, diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index ec71f7a4a5..7fb9b8b515 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; +use crate::events::{EVENTS_API, Event}; use crate::permissions::{self, API_LEVEL, APPEARANCE_API, CONTEXT_API, INPUTS_API, OUTPUT_KINDS_API, PROGRESS_API, Permission, WRITES_API}; use crate::translations::Translations; use crate::{Error, Result}; @@ -723,6 +724,11 @@ pub struct Manifest { /// lists any ([`Manifest::validate`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_allowlist: Vec, + /// The events it reacts to, by [`Event::name`]: only a module at `api` 2 or later whose + /// `permissions` list `events` lists any, and it exports `vc_event` ([`crate::events`]). Left + /// out or empty, it reacts to none. + #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "event_names")] + pub events: Vec, /// What runs its code: WebAssembly when left out, or `"js"` for a JavaScript filter. #[serde(default, skip_serializing_if = "Runtime::is_wasm")] pub runtime: Runtime, @@ -783,6 +789,7 @@ impl Manifest { appearance_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + events: Vec::new(), runtime: Runtime::Wasm, translations: Translations::default(), } @@ -897,12 +904,47 @@ impl Manifest { self.validate_params()?; self.validate_commands()?; self.validate_allowlist()?; + self.validate_events()?; self.validate_translations()?; self.validate_runtime() } + /// `events` names each [`Event`] at most once, and a list needs `api` 2 or later and the + /// permission `events`, which needs a list. + fn validate_events(&self) -> Result<()> { + for (i, name) in self.events.iter().enumerate() { + let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD); + if Event::parse(name).is_none() { + return Err(Error::Manifest(format!( + "`events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed" + ))); + } + if self.events.get(..i).is_some_and(|before| before.contains(name)) { + return Err(Error::Manifest(format!("`events` lists `{shown}` twice"))); + } + } + let listed = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::Events.name())); + if self.events.is_empty() == listed { + return Err(Error::Manifest("`events` needs the permission `events`, and `events` needs a list of `events`".into())); + } + if listed && self.api < EVENTS_API { + return Err(Error::Manifest(format!("`events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API}"))); + } + Ok(()) + } + + /// The events it reacts to (`events`). + pub fn event_kinds(&self) -> Vec { + self.events.iter().filter_map(|n| Event::parse(n)).collect() + } + + /// Does it react to `event`? + pub fn reacts_to(&self, event: Event) -> bool { + self.events.iter().any(|n| n == event.name()) + } + /// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions - /// it lists only `progress`: its realm has no settings, cache or command calls. + /// it lists only `progress`: its realm has no settings, cache, command calls or `vc_event`. fn validate_runtime(&self) -> Result<()> { if self.runtime == Runtime::Wasm { return Ok(()); @@ -912,7 +954,7 @@ impl Manifest { return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\""))); } let listed = self.permissions.as_deref().unwrap_or_default(); - for p in [Permission::Settings, Permission::Cache, Permission::Commands] { + for p in [Permission::Settings, Permission::Cache, Permission::Commands, Permission::Events] { if listed.iter().any(|n| n == p.name()) { let name = p.name(); return Err(Error::Manifest(format!( @@ -1326,6 +1368,17 @@ fn write_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { + let wrong = || serde::de::Error::custom("`events` must be a list of event names, such as selection.changed"); + match Value::deserialize(d)? { + Value::Null => Ok(Vec::new()), + Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(), + _ => Err(wrong()), + } +} + /// Reads `context`: a list of names (`null`: none). Anything else is the error /// [`Manifest::validate_context`] gives a wrong entry. fn context_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { @@ -2359,6 +2412,52 @@ mod tests { assert!(Manifest::parse(manifest(MAX_PARAMS + 1, MAX_PARAMS).as_bytes()).is_err(), "too many in all"); } + /// Any kind at `api` 2 that lists the permission `events` names the events it reacts to; an + /// unknown or repeated name, a list without the permission or the permission without a list, + /// and a list at `api` 1 are refused, and the error names the fault. + #[test] + fn events_are_listed_with_their_permission_at_api_2() { + let m = Manifest::parse( + br#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","selection.changed"]}"#, + ) + .unwrap(); + assert_eq!(m.event_kinds(), [Event::LayerChanged, Event::SelectionChanged]); + assert!(m.reacts_to(Event::SelectionChanged) && !m.reacts_to(Event::DocumentSaved)); + assert_eq!(m.permissions(), [Permission::Events]); + assert_eq!(serde_json::to_value(&m).unwrap()["events"], json!(["layer.changed", "selection.changed"])); + let effect = + br#"{"id":"a","name":"x","kind":"effect","api":2,"permissions":["doc.read","effect.render","events"],"events":["document.saved"]}"#; + assert_eq!(Manifest::parse(effect).unwrap().event_kinds(), [Event::DocumentSaved]); + let importer = + br#"{"id":"a","name":"x","kind":"importer","api":2,"extensions":["q"],"permissions":["import.read","events"],"events":["document.opened"]}"#; + assert!(Manifest::parse(importer).is_ok()); + let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter","events":null}"#).unwrap(); + assert!(plain.events.is_empty() && serde_json::to_value(&plain).unwrap().get("events").is_none()); + for (bad, says) in [ + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["selection.change"]}"#, + "unknown event `selection.change`", + ), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","layer.changed"]}"#, + "lists `layer.changed` twice", + ), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"events":["layer.changed"]}"#, "needs the permission `events`"), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"events":["layer.changed"]}"#, + "needs the permission `events`", + ), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"]}"#, "needs the permission `events`"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[]}"#, "needs the permission `events`"), + (r#"{"id":"a","name":"x","kind":"filter","permissions":["events"],"events":["layer.changed"]}"#, "needs plug-in API level 2"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":"layer.changed"}"#, "must be a list"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[1]}"#, "must be a list"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + #[test] fn rejects_bad_manifests() { for bad in [ diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index f7cf875a6c..ad417630f2 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -7,7 +7,8 @@ //! `permissions` gets the ones its kind implies ([`Permission::implied`]): what every plug-in of //! that kind could do before manifests listed them. `progress`, `settings`, `cache` and `commands`, //! which let a plug-in use the host imports of API level 2 ([`crate::host`]), are never implied: a -//! manifest lists them. +//! manifest lists them. Nor is `events`, which lets a plug-in of any kind react to the events its +//! manifest names ([`crate::events`]). use serde::{Deserialize, Serialize}; @@ -96,10 +97,14 @@ pub enum Permission { /// ([`crate::host::IMPORTS`]): a filter only. #[serde(rename = "commands")] Commands, + /// Run on its own after the changes its manifest's `events` names ([`crate::events`]), with + /// `vc_event`: any kind. + #[serde(rename = "events")] + Events, } /// Every permission this host grants, in the order prompts list them. -pub const ALL: [Permission; 10] = [ +pub const ALL: [Permission; 11] = [ Permission::DocRead, Permission::DocWrite, Permission::State, @@ -110,6 +115,7 @@ pub const ALL: [Permission; 10] = [ Permission::Settings, Permission::Cache, Permission::Commands, + Permission::Events, ]; /// The permissions of the host imports, which any kind may list and none implies; each needs plug-in @@ -131,6 +137,7 @@ impl Permission { Permission::Settings => "settings", Permission::Cache => "cache", Permission::Commands => "commands", + Permission::Events => "events", } } @@ -152,13 +159,14 @@ impl Permission { Permission::Settings => "Keep settings of its own", Permission::Cache => "Keep a cache of its own, which you can clear", Permission::Commands => "Run these commands", + Permission::Events => "Run on its own when the selection, a document or a layer changes", } } /// May a plug-in of `kind` that declares `commands` or not list it: one [`Permission::allowed`] - /// gives it, or one of the host imports' ([`HOST`]), which any kind may list. + /// gives it, one of the host imports' ([`HOST`]) or `events`, which any kind may list. pub fn applies(self, kind: Kind, commands: bool) -> bool { - HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self) + self == Permission::Events || HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self) } /// The permissions a manifest of `kind` without `permissions` gets. A manifest may also list @@ -301,7 +309,7 @@ impl Grant { /// A [`Grant`] that [`crate::registry::grant`] records. The engine makes one where it records what /// a person approved and where it loads the grants kept in its plug-in folder; tests that set up a -/// grant use the same constructors. `tests/grant_sites.rs` fails when other shipped code makes one. +/// grant use the same constructors. `cargo xtask grant-sites` fails when other shipped code makes one. /// Native code linked into the app can still call these constructors, so the token does not /// protect against such code. #[derive(Debug)] diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 56c8787b8e..6d371dd6b2 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -333,6 +333,9 @@ fn wasm_err(e: wasmi::Error) -> Error { /// `vc_run(input_ptr, input_len, params_ptr, params_len) -> len << 32 | ptr` (negative: error). type RunArgs = (i32, i32, i32, i32); +/// `vc_event(event_ptr, event_len) -> 0` (anything else: the handler failed). +type EventArgs = (i32, i32); + /// The manifest in the module's [`MANIFEST_SECTION`] custom section, or `None` when it has none. /// A module with more than one is refused, and so is a section longer than [`MAX_MANIFEST_BYTES`], /// which [`Manifest::parse`] checks before it decodes the bytes. The manifest in the section must @@ -395,8 +398,9 @@ fn check_tables(bytes: &[u8]) -> Result<()> { } /// Checks the exports a run needs without instantiating `module`: its memory as `memory`, whose -/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types. -fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> { +/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types, and +/// `vc_event` with its type when `events` is set (the manifest lists events). +fn check_exports(module: &Module, max_memory_bytes: usize, events: bool) -> Result<()> { use ValType::{I32, I64}; let export = |name: &str| module.exports().find(|e| e.name() == name).map(|e| e.ty().clone()); let Some(ExternType::Memory(memory)) = export("memory") else { @@ -414,6 +418,9 @@ fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> { return Err(Error::Abi(format!("the module must export `{name}` with the type {signature}"))); } } + if events && !matches!(export("vc_event"), Some(ExternType::Func(f)) if f.params() == [I32, I32] && f.results() == [I32]) { + return Err(Error::Abi("the module lists `events`, so it must export `vc_event` with the type (param i32 i32) (result i32)".into())); + } Ok(()) } @@ -449,6 +456,9 @@ impl Plugin { // The other exports must exist with the right types. live.func::("vc_alloc")?; live.func::("vc_run")?; + if !p.manifest.events.is_empty() { + live.func::("vc_event")?; + } Ok(p) } @@ -475,6 +485,10 @@ impl Plugin { return Err(Error::Abi("the module must export its linear memory as `memory`".into())); } p.read(manifest.to_vec(), &imports)?; + if !p.manifest.events.is_empty() { + let Code::Wasm { module, .. } = &p.code else { return Ok(p) }; + exports_func(module, "vc_event", &[ValType::I32; 2], &[ValType::I32])?; + } Ok(p) } @@ -498,7 +512,7 @@ impl Plugin { return Ok(false); }; self.take(manifest, text, imports)?; - check_exports(&module, self.limits.max_memory_bytes)?; + check_exports(&module, self.limits.max_memory_bytes, !self.manifest.events.is_empty())?; check_tables(bytes)?; Ok(true) } @@ -646,6 +660,12 @@ impl Plugin { /// A new instance for `run`, with the host imports of the permissions `granted` linked. When the /// module's start function fails, what it reported through the host imports goes to `report`. fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result { + self.instantiate_with(run, granted, report, self.limits.fuel_base) + } + + /// [`Plugin::instantiate`] with the start function given at most `start_fuel` instructions; + /// the instance's store holds what it left. + fn instantiate_with(&self, run: Run, granted: &[Permission], report: &mut Report, start_fuel: u64) -> Result { let Code::Wasm { engine, module } = &self.code else { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())) }; let limits = StoreLimitsBuilder::new() .memory_size(self.limits.max_memory_bytes) @@ -658,7 +678,7 @@ impl Plugin { store.limiter(|h| &mut h.limits); // The start function (if any) runs on one slice of fuel: it runs before `call` can check // the deadline or a cancel between slices, so a heavy budget would let it run for minutes. - store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?; + store.set_fuel(start_fuel.min(FUEL_SLICE)).map_err(wasm_err)?; let linker = host::linker(engine, granted); let instance = match linker.instantiate_and_start(&mut store, module) { Ok(instance) => instance, @@ -703,6 +723,37 @@ impl Plugin { slice(live, left, start) } + /// Calls `f` on at most `budget` instructions, which holds what the call left unused when it + /// returns `Ok`, for the next call to share. With `bridge`, each command call `vc_call` asks + /// for is made with it while the call waits ([`Plugin::answer`]); without it one fails the call. + fn call_budget( + live: &mut Live, + f: &TypedFunc, + params: P, + budget: &mut u64, + deadline: &Deadline, + mut bridge: Option<&mut Bridge<'_>>, + ) -> Result { + let mut call = Self::first_slice(live, budget, |store| f.call_resumable(store, params))?; + loop { + match Self::drive(live, budget, deadline, call)? { + Driven::Finished(r) => { + *budget = budget.saturating_add(live.store.get_fuel().map_err(wasm_err)?); + return Ok(r); + } + Driven::Call(command, args, paused) => { + let Some(bridge) = bridge.as_deref_mut() else { + return Err(Error::Trap("unexpected host trap".into())); + }; + // A panic making the call fails the handler, as one in the runtime does. + let answer = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| bridge(&command, &args))) + .map_err(|_| Error::Trap("the runtime panicked".into()))?; + call = Self::answer(live, budget, deadline, &command, answer, paused)?; + } + } + } + } + /// Goes on with `call` slice by slice ([`Plugin::call`]) until it finishes or pauses for a /// command call that `vc_call` asked for ([`host::Run::pending`]). Each command call costs /// [`host::CALL_FUEL`] instructions and one for every 64 bytes of its arguments, and the deadline @@ -937,4 +988,75 @@ impl Plugin { } live.read_packed(packed, "the output", limits.max_output_bytes) } + + /// Its limits for one event handler: at most [`crate::events::EVENT_FUEL`] instructions and + /// [`crate::events::EVENT_WALL_TIME_MS`], or its own budgets when they are smaller, and every + /// other limit as it is. + pub fn event_limits(&self) -> Limits { + Limits { + fuel_base: self.limits.fuel_base.min(crate::events::EVENT_FUEL), + wall_time_ms: self.limits.wall_time_ms.min(crate::events::EVENT_WALL_TIME_MS), + ..self.limits.clone() + } + } + + /// Calls `vc_event` with `event` (the event JSON) in a fresh instance under + /// [`Plugin::event_limits`] → `Ok` when it returned 0, and what it reported through the host + /// imports. With `bridge`, each `vc_call` of a command its `commandAllowlist` names is made with + /// it; a failed call fails the handler. A module that doesn't react to events, an event past + /// [`crate::events::MAX_EVENT_BYTES`] and Safe Mode run nothing. + pub fn run_event(&self, event: &[u8], bridge: Option<&mut Bridge<'_>>) -> (Result<()>, Report) { + let mut report = Report::default(); + if let Err(e) = crate::safe_mode::check() { + return (Err(e), report); + } + if self.manifest.events.is_empty() { + return (Err(Error::Abi("the module reacts to no events".into())), report); + } + if event.len() > crate::events::MAX_EVENT_BYTES { + let (len, max) = (event.len(), crate::events::MAX_EVENT_BYTES); + return (Err(Error::Limit(format!("event size ({len} bytes, limit {max})"))), report); + } + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.event_inner(event, &mut report, bridge))); + (run.map_err(|_| Error::Trap("the runtime panicked".into())).and_then(|r| r), report) + } + + fn event_inner(&self, event: &[u8], report: &mut Report, bridge: Option<&mut Bridge<'_>>) -> Result<()> { + let limits = self.event_limits(); + let deadline = Deadline::new(limits.wall_time_ms); + let m = &self.manifest; + let run = Run::new(&m.id, false, true, deadline).with_storage(crate::registry::storage(&m.id)); + let mut live = self.instantiate_with(run, &m.permissions(), report, limits.fuel_base)?; + // The start function, `vc_alloc` and `vc_event` share the one budget. + let mut budget = live.store.get_fuel().map_err(wasm_err)?; + if bridge.is_some() { + live.store.data_mut().run.allow_calls(m.command_allowlist.clone()); + } + let out = (|| { + let alloc: TypedFunc = live.func("vc_alloc")?; + let handler: TypedFunc = live.func("vc_event")?; + // The start function may have used the time: neither call runs past it. + deadline.check()?; + let ptr = Self::call_budget(&mut live, &alloc, event.len().max(1) as i32, &mut budget, &deadline, None)? as u32 as usize; + if ptr == 0 { + return Err(Error::Failed("vc_alloc returned 0 (out of memory)".into())); + } + let outside = || Error::Abi("vc_alloc returned a block outside memory".into()); + let end = ptr.checked_add(event.len()).ok_or_else(outside)?; + live.memory.data_mut(&mut live.store).get_mut(ptr..end).ok_or_else(outside)?.copy_from_slice(event); + deadline.check()?; + let code = Self::call_budget(&mut live, &handler, (ptr as i32, event.len() as i32), &mut budget, &deadline, bridge)?; + deadline.check()?; + if code != 0 { + return Err(Error::Failed(format!("vc_event returned {code}"))); + } + Ok(()) + })(); + let state = &mut live.store.data_mut().run; + *report = std::mem::take(&mut state.report); + match (state.call_failure.take(), out) { + (Some(e), _) => Err(e), + (None, out) => out, + } + } } diff --git a/crates/plugins/src/wat.rs b/crates/plugins/src/wat.rs index a00821c720..9c003ed65c 100644 --- a/crates/plugins/src/wat.rs +++ b/crates/plugins/src/wat.rs @@ -82,6 +82,18 @@ pub fn with_field(module: &str, field: &str) -> Option { /// A `vc_run` body returning the input unchanged. pub const ECHO: &str = "(i64.or (i64.shl (i64.extend_i32_u (local.get $il)) (i64.const 32)) (i64.extend_i32_u (local.get $in)))"; +/// A plug-in that reacts to events ([`crate::events`]): `manifest` (JSON that lists `events`), the +/// module fields `imports` before the others, a `vc_event` whose body is `handler` (parameters +/// `$ep $el`, result i32) and a `vc_run` that returns its input. +pub fn reacting(manifest: &str, imports: &str, handler: &str) -> String { + let extra = format!(r#"{imports} (func (export "vc_event") (param $ep i32) (param $el i32) (result i32) {handler})"#); + module(manifest, ECHO, &extra, 1) +} + +/// A `vc_event` body that writes the event it is given as an information log line (with +/// [`HOST_IMPORTS`]) and returns 0. +pub const LOG_EVENT: &str = "(drop (call $vc_log (i32.const 2) (local.get $ep) (local.get $el))) (i32.const 0)"; + /// A plug-in that always returns `output` (whatever it is given). pub fn returning(manifest: &str, output: &str) -> String { then_returning(manifest, "", output) diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 0a7416d124..206faa721e 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1247,6 +1247,96 @@ fn a_plugin_reaches_only_its_own_storage() { registry::set_storage("test.storage.theirs", None); } +/// The manifest of an event plug-in `id` that writes log lines and reacts to `events` (JSON list). +fn reacting_manifest(id: &str, events: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":{events}}}"#) +} + +/// A module that lists `events` needs a `vc_event` export of the right type; one that lists none +/// may leave it out. +#[test] +fn an_event_plugin_exports_vc_event() { + let manifest = reacting_manifest("test.events.export", r#"["selection.changed"]"#); + let e = Plugin::load(&build(&tpl::reporting(&manifest, "", INPUT)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let wrong = format!(r#"{} (func (export "vc_event") (param i32) (result i32) (i32.const 0))"#, tpl::HOST_IMPORTS); + let e = Plugin::load(&build(&tpl::module(&manifest, tpl::ECHO, &wrong, 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + assert!(Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).is_ok()); + assert!(Plugin::load(&ok_module(tpl::ECHO), Limits::default()).is_ok(), "no events, no vc_event"); + // A module whose manifest is in its custom section is checked without being instantiated. + let section = + r#"{"id":"test.events.section","name":"T","kind":"filter","api":2,"permissions":["events"],"events":["selection.changed"],"abi":1}"#; + let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, "", 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let one_param = r#"(func (export "vc_event") (param i32) (result i32) (i32.const 0))"#; + let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, one_param, 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let handler = r#"(func (export "vc_event") (param i32 i32) (result i32) (i32.const 0))"#; + assert!(Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, handler, 1)), Limits::default()).is_ok()); +} + +/// `vc_event` is given the event JSON in its own memory and returns 0; anything else, a trap and a +/// handler past its instruction budget fail it. A module without events runs no handler. +#[test] +fn vc_event_is_given_the_event_and_its_code_is_checked() { + let manifest = reacting_manifest("test.events.run", r#"["layer.changed"]"#); + let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).unwrap(); + let event = br#"{"type":"layer.changed","document":7}"#; + let (r, report) = p.run_event(event, None); + r.unwrap(); + assert_eq!(report.lines.iter().map(|l| l.text.as_str()).collect::>(), [std::str::from_utf8(event).unwrap()]); + for (handler, says) in [ + ("(i32.const 3)", "vc_event returned 3"), + ("unreachable", "trapped"), + // The instruction budget, or the time budget on a loaded machine. + ("(loop $l (br $l)) (i32.const 0)", "budget"), + ] { + let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, handler)), Limits::default()).unwrap(); + let e = p.run_event(event, None).0.unwrap_err().to_string(); + assert!(e.contains(says), "{handler}: {e}"); + } + let e = p.run_event(&vec![b' '; vectorcraft_plugins::events::MAX_EVENT_BYTES + 1], None).0.unwrap_err(); + assert!(e.to_string().contains("event size"), "{e}"); + let plain = Plugin::load(&ok_module(tpl::ECHO), Limits::default()).unwrap(); + assert!(plain.run_event(event, None).0.is_err()); + let limits = p.event_limits(); + assert_eq!((limits.fuel_base, limits.wall_time_ms), (vectorcraft_plugins::events::EVENT_FUEL, vectorcraft_plugins::events::EVENT_WALL_TIME_MS)); +} + +/// The start function, `vc_alloc` and `vc_event` share one event budget: work that fits it in the +/// handler alone fits it no longer when the start function has done as much first. The budget is +/// 200,000 instructions, which run in far less than the 200 ms an event is given, so the run that +/// fails is stopped by its instruction budget. +#[test] +fn a_handler_and_its_start_function_share_the_event_budget() { + let manifest = reacting_manifest("test.events.shared", r#"["layer.changed"]"#); + let burn = r#"(func $burn (param $k i32) (block $b (loop $l + (br_if $b (i32.eqz (local.get $k))) + (local.set $k (i32.sub (local.get $k) (i32.const 1))) + (br $l))))"#; + let plugin = |start: u32, handler: u32| { + let imports = format!("{} {burn} (func $s (call $burn (i32.const {start}))) (start $s)", tpl::HOST_IMPORTS); + let body = format!("(call $burn (i32.const {handler})) (i32.const 0)"); + Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits { fuel_base: 200_000, ..Limits::default() }).unwrap() + }; + let event = br#"{"type":"layer.changed","document":1}"#; + // The most loop turns, doubling, that fit the budget in the handler alone: twice as many run out + // of instructions. + let mut k = 1u32 << 8; + let e = loop { + match plugin(0, k * 2).run_event(event, None).0 { + Ok(()) => k *= 2, + Err(e) => break e.to_string(), + } + assert!(k < 1 << 30, "a handler that never runs out of its budget"); + }; + assert!(e.contains("instruction budget"), "{e}"); + assert!(plugin(0, k).run_event(event, None).0.is_ok()); + let e = plugin(k, k).run_event(event, None).0.unwrap_err().to_string(); + assert!(e.contains("instruction budget"), "{e}"); +} + /// A heavy filter installs once the user agrees, which loading a folder doesn't ask: it is skipped /// and reported. #[test] diff --git a/crates/plugins/tests/grant_sites.rs b/crates/plugins/tests/grant_sites.rs deleted file mode 100644 index 7e96ef397d..0000000000 --- a/crates/plugins/tests/grant_sites.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! The shipped code that records a plug-in grant: only the engine's install approval and its load -//! of the plug-in folder's grants file make a `GrantToken` and call `registry::grant`, -//! `registry::install_checked` or `registry::install_for_load`. A new call site fails this test until -//! it is added to the list. It checks the source, not what native code can do at run time. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; - -/// `(text, file, how many times)` for every place shipped code may name it. -const EXPECTED: &[(&str, &str, usize)] = &[ - ("GrantToken::after_engine_approval", "crates/engine/src/cmd/plugin.rs", 1), - ("GrantToken::from_engine_grants_file", "crates/engine/src/store.rs", 2), - ("registry::grant", "crates/engine/src/store.rs", 1), - ("registry::install_checked", "crates/engine/src/cmd/plugin.rs", 1), - ("registry::install_for_load", "crates/engine/src/store.rs", 2), -]; - -/// The names the audit counts. -const NAMES: [&str; 5] = [ - "GrantToken::after_engine_approval", - "GrantToken::from_engine_grants_file", - "registry::grant", - "registry::install_checked", - "registry::install_for_load", -]; - -/// Every `.rs` file under `dir`, without test files and folders. -fn sources(dir: &Path, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { return }; - for entry in entries.flatten() { - let path = entry.path(); - let name = entry.file_name().to_string_lossy().to_string(); - if path.is_dir() { - if !matches!(name.as_str(), "tests" | "benches" | "examples" | "target" | "fuzz") { - sources(&path, out); - } - } else if name.ends_with(".rs") && name != "tests.rs" && !name.starts_with("tests_") && !name.ends_with("_tests.rs") { - out.push(path); - } - } -} - -/// The lines of `text` that ship: not comments, and nothing from a top-level `#[cfg(test)] mod x {` -/// on. -fn shipped(text: &str) -> Vec<&str> { - let lines: Vec<&str> = text.lines().collect(); - let opens_test_module = |i: usize| { - lines[i] == "#[cfg(test)]" - && lines[i + 1..].iter().find(|l| !l.trim().is_empty()).is_some_and(|l| l.starts_with("mod ") && l.trim_end().ends_with('{')) - }; - let end = (0..lines.len()).find(|&i| opens_test_module(i)).unwrap_or(lines.len()); - lines[..end].iter().copied().filter(|l| !l.trim_start().starts_with("//")).collect() -} - -/// How many times `name` occurs in `line` as a whole path (`registry::grant`, not `registry::granted`). -fn count(line: &str, name: &str) -> usize { - line.match_indices(name).filter(|(at, _)| !line[at + name.len()..].starts_with(|c: char| c.is_alphanumeric() || c == '_')).count() -} - -#[test] -fn grant_token_call_sites_are_limited() { - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); - let mut files = Vec::new(); - for top in ["crates", "apps", "xtask"] { - sources(&root.join(top), &mut files); - } - assert!(files.len() > 100, "found only {} source files under {}", files.len(), root.display()); - let mut found: BTreeMap<(&str, String), usize> = BTreeMap::new(); - for file in &files { - let text = std::fs::read_to_string(file).unwrap(); - let rel = file.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/"); - for line in shipped(&text) { - for name in NAMES { - let n = count(line, name); - if n > 0 { - *found.entry((name, rel.clone())).or_default() += n; - } - } - } - } - let expected: BTreeMap<(&str, String), usize> = EXPECTED.iter().map(|&(name, file, n)| ((name, file.to_string()), n)).collect(); - assert_eq!(found, expected, "shipped code that makes a grant token or records a grant"); -} - -/// The audit's own filters: a test module and comments are left out, a longer name isn't counted. -#[test] -fn the_audit_skips_test_code_and_comments() { - let text = "fn a() { registry::grant(t); }\n// registry::grant(t)\nfn b() { registry::granted(id); }\n\n#[cfg(test)]\n\nmod tests {\n registry::grant(t);\n}\n"; - let lines = shipped(text); - assert_eq!(lines.iter().map(|l| count(l, "registry::grant")).sum::(), 1, "{lines:?}"); -} diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index ef282e5b4d..c0efa55a0b 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -99,12 +99,22 @@ impl crate::Renderer { // Trim View clips each draw when blending reaches the page and clips one composited // layer otherwise. Changing modes can change unchanged art at an artboard edge. if opts.trim && !old.artboards.is_empty() { + // `children_blend` caches the groups it reads in `blends`, which holds their nodes, + // so this counts as a measurement for `finish_measurement_only`. + self.measuring = true; let before = crate::proof::prepare(old, opts, &mut self.proof_art); let after = crate::proof::prepare(new, opts, &mut self.proof_art); if self.children_blend(&before.layers) != self.children_blend(&after.layers) { return Changed::Everything; } } + // A change outside the layers (symbol definitions among them) redraws everything without + // measuring anything here; the caches still age so that bounds kept for the old + // definitions expire. + if new.pattern_edit.is_some() || !old.same_outside_layers(new) { + self.measuring = true; + return Changed::Everything; + } let renderer = (!crate::proof::overprints(opts)).then_some(self); changed_with(old, new, renderer, opts) } @@ -249,7 +259,11 @@ impl Diff<'_, '_> { Side::New => new, }; match renderer { - Some(r) => r.bounds_of(symbols, n), + Some(r) => { + // Only a measurement ages the renderer's caches in `finish_measurement_only`. + r.measuring = true; + r.bounds_of(symbols, n) + } None => crate::brush_fx::cull_bounds(symbols, n), } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 544438d96f..f2b76c525d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5,6 +5,7 @@ //! (multiple fills/strokes, opacity, blend modes, stroke alignment, dashes), clip groups, //! gradients, images and text (via `vectorcraft-text` glyph outlines). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod brush_fx; @@ -182,6 +183,9 @@ pub struct Renderer { /// ([`lru::MEASURED_BUDGET`]). measured_bytes: usize, measured_budget: usize, + /// [`Renderer::changed`] measured through this renderer since its last frame began or since + /// [`Renderer::finish_measurement_only`] last aged its caches. + measuring: bool, /// The export bounds of the objects measured without their hidden members /// (`encode::drawn_bounds`), by the object they were made from: kept for a pass over artboards, /// let go when a frame ends. diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 065055f96c..fdf7847412 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -76,6 +76,7 @@ impl Renderer { measured: PtrMap::default(), measured_bytes: 0, measured_budget: lru::MEASURED_BUDGET, + measuring: false, pass_bounds: PtrMap::default(), three_d_bounds: PtrMap::default(), three_d_kept: 0, @@ -244,6 +245,7 @@ impl Renderer { /// Start a frame: cache entries used from now on are marked with its stamp. fn begin_frame(&mut self) { self.stamp += 1; + self.measuring = false; self.inline_depth = 0; // Nothing is drawn offscreen yet (even if an earlier frame stopped part way). (self.offscreen_live, self.offscreen_budget) = (0, 0); @@ -267,7 +269,12 @@ impl Renderer { /// Finish measuring an edit whose frame is drawn elsewhere or needs no pixel update. /// Age the measurement caches and keep the previous draw's effect rasters available. + /// Without a [`Self::changed`] since the last frame or the last call, nothing changes: + /// the paths of the last frame stay for this renderer's next frame. pub fn finish_measurement_only(&mut self) { + if !std::mem::take(&mut self.measuring) { + return; + } self.stamp += 1; self.sweep_node_geometry(); let g = self.stamp; diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 99ee9a5f0c..9ee678965c 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1730,6 +1730,33 @@ fn a_kept_decoded_image_is_drawn_without_decoding_it() { assert!(!image_cached(&cmyk)); } +/// Pixels [`keep_decoded_image`] refuses (here, pixels past the decode allowance) are not +/// kept anywhere: the first render that draws the image decodes it, as for any image. +#[test] +fn a_refused_decoded_image_is_decoded_when_first_drawn() { + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; + // Pixels no other test uses, since every test shares the store. + let img = image::RgbaImage::from_fn(29, 17, |x, y| image::Rgba([(x * 5) as u8, (y * 13) as u8, 41, 255])); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let blob = ImageBlob::new("image/png", png.clone()); + paint::TEST_ALLOWANCE.with(|c| c.set(Some(64))); + let kept = keep_decoded_image(&blob, image::load_from_memory(&png).unwrap()); + paint::TEST_ALLOWANCE.with(|c| c.set(None)); + assert!(!kept, "past the allowance: the pixels are refused"); + assert!(!image_cached(&blob)); + let mut d = Document::new(29.0, 17.0); + d.images.insert("refused".into(), blob); + let id = d.alloc_id(); + let im = + ImageObject { key: "refused".into(), width: 29, height: 17, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + let decodes = image_decodes(); + let r = Renderer::new().render(&d, 29, 17, Affine::IDENTITY, &RenderOptions::default()); + assert_eq!(image_decodes(), decodes + 1, "the first draw decodes the image"); + assert!(r.pixel(14, 8)[3] > 0, "the image is drawn"); +} + /// A CMYK image's inks and the pixels shown from them are admitted against the decode allowance /// before either is made: past it, the image is read as other images are (reduced), not whole. #[test] diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 8579c314b8..023a62bad3 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -34,6 +34,54 @@ fn geometry_from_measurement_only_frames_releases_old_node_versions() { assert!(oldest.upgrade().is_none(), "obsolete measured nodes must be released without a full draw"); } +/// The canvas finishes a measurement in every frame that waits for another renderer's frame, also +/// when it measured nothing (a zoom or a pan). Those frames keep the paths this renderer drew, so +/// its next frame, the next step of a pan, does not build them all again. +#[test] +fn finishing_without_a_measurement_keeps_the_drawn_paths() { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let path = Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(layer), 0, path).unwrap(); + let drawn = Arc::as_ptr(&doc.layers[0].children().unwrap()[0]) as usize; + let mut renderer = Renderer::new(); + renderer.render(&doc, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + assert!(renderer.geom.contains_key(&drawn), "the frame keeps the path it drew"); + for _ in 0..8 { + renderer.finish_measurement_only(); + } + assert!(renderer.geom.contains_key(&drawn), "frames that measured nothing keep the drawn path"); +} + +/// Comparing a document with itself measures nothing, so the frames that follow keep the paths +/// this renderer drew. +#[test] +fn an_unchanged_document_keeps_the_drawn_paths() { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let path = Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(layer), 0, path).unwrap(); + let drawn = Arc::as_ptr(&doc.layers[0].children().unwrap()[0]) as usize; + let mut renderer = Renderer::new(); + let opts = RenderOptions::default(); + renderer.render(&doc, 100, 100, Affine::IDENTITY, &opts); + for _ in 0..4 { + assert!(matches!(renderer.changed(&doc, &doc, &opts), Changed::Nothing)); + renderer.finish_measurement_only(); + } + assert!(renderer.geom.contains_key(&drawn), "frames that measured nothing keep the drawn path"); +} + /// A `w`×`h` PNG whose pixels depend on `seed` (each test its own image: the store is shared by /// the tests running alongside). fn png(w: u32, h: u32, seed: u8) -> Vec { diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 4e9a9bf2e3..2c0d944099 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -56,6 +56,9 @@ pub(crate) struct Known { /// A file gives names values the analysis doesn't read ([`Declared::unsure`]): no object counts /// as a Folder object whatever the path names. pub unsure: bool, + /// The script includes another file ([`Declared::includes`]), whose code may give a file's + /// variables values the scan of that file does not read. + pub others: bool, } impl Known { @@ -75,6 +78,7 @@ impl Known { /// object only when both sides say so; otherwise it may hold a File object. pub fn add(&mut self, other: Known, entries: usize) { self.unsure |= other.unsure; + self.others |= other.others; for (name, chain) in other.bound { if self.bound.len() < entries || self.bound.contains_key(&name) { self.bound.entry(name).or_insert(chain); @@ -286,8 +290,8 @@ struct ObjectValue { /// key's whole value, a bit each ([`Analyzer::writers`]). bits: u8, /// It is the value of the first name a `var` statement declares, and the statement is directly - /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or - /// a loop's parentheses: only then does the variable hold `bits` after it. + /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do`, a + /// loop's parentheses or a label: only then does the variable hold `bits` after it. whole: bool, /// The bit of the method whose value is being read, and how far that value has been read. value: Option<(u8, Value)>, @@ -696,6 +700,8 @@ struct Analyzer<'s, 'a, 'l> { /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, + /// The script includes another file ([`Known::others`]): no variable joins [`Analyzer::writers`]. + others: bool, /// The variables that may get another value when code read elsewhere runs: assigned inside a /// function body that does not declare them, or as a property of `this` ([`Analyzer::reassigned_later`]). /// None of them joins [`Analyzer::writers`]. @@ -783,6 +789,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { objects: vec![], closed: None, index_receiver: 0, + others: known.others || declared.includes, later: HashSet::new(), later_full: false, unsure: known.unsure || declared.unsure, @@ -1518,10 +1525,21 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins /// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t` /// closes a function body, so a literal given to the body's own variable stays inside the body. - /// Calls inside a loop that assigns the variable use [`Declared::looped`] to classify its methods. + /// No variable joins when code the scan does not follow at that point may give it another value: + /// a function body that assigns its name ([`Declared::body_assigned`], [`Analyzer::later`]), a + /// member assignment of a property of that name, which may be the global object's + /// ([`Declared::rebound`]), a function body that assigns a `saveAs` or `exportFile` property of + /// any object ([`Declared::body_writer_assigned`]), code given as text or a `with` statement + /// ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). Calls inside a loop that + /// assigns the variable use [`Declared::looped`] to classify its methods. fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && !self.unsure + && !self.others + && !self.declared.rebound.contains(&name) + && !self.declared.body_assigned.contains(name.as_str()) + && !self.declared.body_writer_assigned && !self.later_full && !self.later.contains(&name) && !self.declared.looped_full @@ -1855,7 +1873,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } // A variable that any assignment gave a value that may be a File object leaves as one. let folders = self.folders.iter().filter(|name| self.folder(name)).cloned().collect(); - let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders, unsure: self.unsure }; + let known = Known { + bound: std::mem::take(&mut self.bound), + files: std::mem::take(&mut self.files), + folders, + unsure: self.unsure, + others: self.others, + }; (std::mem::take(&mut self.includes), module, known) } } diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index ca4ac99823..ffb7fbe295 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -2,7 +2,10 @@ use std::collections::{HashMap, HashSet}; -use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word}; +use super::{ + Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark, + unquote, word, +}; /// The names that give variables values the analysis doesn't read: a `with` statement makes an /// object's properties stand for names in its body (ECMA-262 3rd edition, section 12.10), and `eval`, @@ -67,6 +70,19 @@ pub(crate) struct Declared<'s> { /// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be /// the global object, so a variable of that name may get a value the analysis doesn't read. pub(super) rebound: HashSet, + /// The names a function body assigns by name (`d = …`, `d += …`, `d++`, `for (d in …)`) other than + /// in a `var` statement's declarations, unless a body around the assignment declared the name with + /// `var` before it. The function may run at any time after it is defined, + /// also before its body in the text when it is a declaration, so a variable of that name may lose + /// the value an assignment the analysis read gave it. + pub(super) body_assigned: HashSet<&'s str>, + /// A function body assigns a property named as one of [`catalog::DOM_FILE_WRITES`] + /// (`o.saveAs = …`, `this['exportFile'] = …`). The function may run at any time after it is + /// defined, and the object may be any variable's, so no variable's method of that name stays + /// the script's own. + pub(super) body_writer_assigned: bool, + /// The file has an `#include` line: the included file's code may give its variables values. + pub(super) includes: bool, /// The variables assigned inside a loop, its parentheses included (`name = …`), each by the /// offset of the `{` of the function body that declares it (`None`: the global code's), with the /// outermost loops that assign it, entries of `loop_spans`. @@ -197,7 +213,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { for t in lexer.by_ref() { match breaks.read(&t) { Read::Skip => {} - Read::Directive => d.directive(), + Read::Directive => d.directive(&t), Read::Token(sig) => d.token(sig), } } @@ -270,9 +286,43 @@ impl<'s> Declarations<'s, '_, '_> { if t.word("function") && !member_mark(h0) && !word(h0, "function") { self.function = Some(depth); } + if !self.bodies.is_empty() || self.untracked.is_some() { + self.body_assignment(&t, depth); + } self.h = [Some(t), h0, h1]; } + /// `t` inside a function body at bracket depth `depth`: the name it assigns, when it assigns one + /// by name outside a `var` statement's declarations, joins [`Declared::body_assigned`]. + fn body_assignment(&mut self, t: &Sig<'s>, depth: usize) { + let [h0, h1, _] = self.h; + let name = |s: Option>| s.filter(|s| s.kind == T::Ident).map(|s| s.text); + let declares = word(h1, "var") || (is(h1, ",") && self.var_depth == Some(depth)); + let assigned = if t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")) { + // `d = …`, `d += …` and `d++`, not `o.d = …` (a member: [`Declared::rebound`]) or `var d = …`. + name(h0).filter(|_| !member_mark(h1) && !(t.text == "=" && declares)) + } else if t.kind == T::Ident && (is(h0, "++") || is(h0, "--")) { + // `++d`. + Some(t.text) + } else if t.word("in") && (is(h1, "(") || word(h1, "var")) { + // `for (d in …)`. + name(h0) + } else { + None + }; + // A name the innermost body around `t` has declared with `var` before it is that body's own. A + // name only an outer body declared is that body's variable, which a nested function may assign + // before a call in the outer body runs. + let own = |name: &str| self.untracked.is_none() && self.bodies.last().is_some_and(|b| b.names.contains(name)); + if let Some(name) = assigned.filter(|n| !own(n)) { + if self.out.body_assigned.contains(name) || self.acc.room(self.out.body_assigned.len()) { + self.out.body_assigned.insert(name); + } else { + self.out.unsure = true; + } + } + } + /// `t`, a token before the brackets are followed past it: the body of the innermost loop starts /// at it, and `for`, `while` and `do` start a loop. Past [`crate::Limits::nesting`] loops, any /// variable may be assigned in one ([`Declared::looped_full`]). @@ -507,6 +557,9 @@ impl<'s> Declarations<'s, '_, '_> { None }; if let Some(name) = property { + if (!self.bodies.is_empty() || self.untracked.is_some()) && catalog::DOM_FILE_WRITES.contains(&name.as_str()) { + self.out.body_writer_assigned = true; + } if self.out.rebound.contains(&name) || self.acc.room(self.out.rebound.len()) { self.out.rebound.insert(name); } else { @@ -613,7 +666,10 @@ impl<'s> Declarations<'s, '_, '_> { /// A preprocessor line ends the statement before it, as in [`Analyzer::directive`]. Inside a /// property's name in brackets it hides the tokens before the name (`this[`, a line, `'eval']`), /// so the name may be any. - fn directive(&mut self) { + fn directive(&mut self, t: &Token<'s>) { + if directives::parse(t.text).known == Some("include") { + self.out.includes = true; + } if self.keys.iter().any(|k| k.member) { self.out.unsure = true; } diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 9fdf4d73ce..a929c47d44 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -77,7 +77,7 @@ pub(crate) const REFLECT: &str = "reflect"; pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; // Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ -pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "saveAs"]; +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "imageCapture", "saveAs"]; // Application methods that read the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_FILE_READS: &[&str] = &["open"]; @@ -235,7 +235,7 @@ features! { Reflection "reflection" Language, ScriptuiDialog "scriptui.dialog" Dialogs, ScriptuiDrawing "scriptui.drawing" Dialogs, - ScriptuiPalette "scriptui.palette" HostOnly, + ScriptuiPalette "scriptui.palette" Dialogs, ScriptuiWindow "scriptui.window" Dialogs, SelectTool "selectTool" Dom, Socket "socket" HostOnly, diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index 9075c53517..868752339a 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -22,6 +22,7 @@ //! keeps open brackets and the levels of an XML literal on capped stacks. Its work is linear in the //! input's size, and no input can overflow the stack. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod analyze; mod catalog; @@ -120,8 +121,8 @@ pub enum Need { MenuCommands, /// Dialogs and windows of its own. Dialogs, - /// Features only the reference app has (palettes, messages to other apps, network - /// connections, native code, actions). + /// Features only the reference app has (messages to other apps, network connections, native + /// code, actions). HostOnly, } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1edd1480f6..eec8e0e03f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -550,6 +550,21 @@ fn save_as_and_export_file_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// A document's `imageCapture` writes the file it is given, with or without bounds and options, and +/// called by its name in brackets; `rasterize` stays inside the document. +#[test] +fn image_capture_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument.imageCapture(f);\n", + "var d = app.activeDocument; d.imageCapture(f, [0, 0, 10, 10], new ImageCaptureOptions());\n", + "d['imageCapture'](f);\n", + "d.rasterize(d.pageItems[0]);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[2, 3, 4][..])]); +} + /// A document's `exportVariables` writes the file it is given; `importVariables` only reads one. #[test] fn export_variables_writes_a_file() { @@ -868,7 +883,8 @@ fn try_clauses_and_else_after_a_nested_do_loop_are_in_the_loop() { /// A literal after a label's line break may not run, a `this` assignment in a function whose own /// variable hides the global one changes the global, and a property `d` of another object is not -/// the variable `d`. +/// the variable `d`. A member assignment of a property `g` (`holder.this.g = …`) may be the global +/// object's, so `g.saveAs` writes a file. #[test] fn labels_hidden_globals_and_other_objects_keep_writes_known() { let r = report(concat!( @@ -893,7 +909,7 @@ fn labels_hidden_globals_and_other_objects_keep_writes_known() { "function other() { var g; holder.this.g = app.activeDocument; holder.this['g'] = 1; }\n", "other(); g.saveAs(f);\n", )); - assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17][..])); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17, 20][..])); } /// Only a `var` statement directly in a function body or the global code that gives its first name @@ -925,6 +941,61 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); } +/// A literal's `saveAs` stays the script's own only while no code the check does not follow may give +/// the variable another value: a declaration after a label, which `if` may skip, a function body that +/// assigns the variable (its own method's, or a declaration's that runs before its text), a member +/// assignment of a property of that name, which may be the global object's, a function body that +/// assigns a `saveAs` or `exportFile` property of any object, code given as text, a `with` statement +/// and an included file each leave the write reported. A function that declares its own variable of the +/// name, or assigns another property of it, leaves it the script's own. A nested function that assigns +/// a variable its enclosing body declared leaves the write reported too. +#[test] +fn a_save_as_other_code_may_replace_writes_a_file() { + let cases: [(&str, &[usize]); 16] = [ + ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), + ( + "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", + &[10], + ), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nswap();\nd.saveAs(f);\nfunction swap() { d = app.activeDocument; }\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nthis.d = app.activeDocument;\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\neval(s);\nd.saveAs(f);\n", &[4]), + ("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\n#include \"other.jsx\"\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nwith ({d: app.activeDocument}) {\n d.saveAs(f);\n}\n", &[4]), + ( + "var f = new File(p);\nfunction replace() { d.saveAs = app.activeDocument.saveAs; }\nvar d = {saveAs: function () {}};\nreplace();\nd.saveAs(f);\n", + &[5], + ), + ( + "var f = new File(p);\nfunction replace(o) { o['exportFile'] = w; }\nvar d = {exportFile: function () {}};\nreplace(d);\nd.exportFile(f);\n", + &[5], + ), + ("var f = new File(p);\nfunction note() { d.n = 1; }\nvar d = {saveAs: function () {}};\nnote();\nd.saveAs(f);\n", &[]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d = app.activeDocument; }\n}\nrun();\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d += 1; }\n}\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d++; }\n}\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { for (d in o) {} }\n}\n", + &[5], + ), + ]; + for (src, lines) in cases { + let r = report(src); + assert_eq!(feature(&r, "file.write").map_or(&[][..], |f| f.lines.as_slice()), lines, "{src}"); + } +} + #[test] fn writer_calls_after_many_assignment_loops_have_bounded_work() { for reinitialize in [false, true] { @@ -2092,6 +2163,12 @@ fn declarations_past_a_limit_hold_from_where_they_stand() { assert_eq!(notify(five, &Limits::default()).0, Vec::::new()); } +#[test] +fn palettes_need_dialogs() { + let r = report("#targetengine tools\nvar w = new Window('palette');\nw.show();\n"); + assert_eq!(r.needs, [Need::Language, Need::Dialogs]); +} + #[test] fn application_methods_are_features_not_members() { let r = report("app.executeMenuCommand('acmecopyall');\napp.selectTool('acme');\n"); diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 76069d802a..d37715f9b9 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -539,8 +539,11 @@ impl Rules<'_> { /// A stroke as a border: weight, style (dashed; dotted for round dots) and colour. fn border(&mut self, s: &StrokeLayer, bounds: Rect, art: &mut Art) { - // Aligned strokes still draw as borders; arrowheads, profiles, brushes and fitted dashes don't. - if !vectorcraft_effects::stroke::is_plain(&StrokeLayer { align: StrokeAlign::Center, ..s.clone() }) { + // Aligned strokes still draw as borders, and evenly spaced round dots as `dotted`; + // arrowheads, profiles, brushes and fitted dashes don't. + let dots = s.dash.as_ref().is_some_and(|d| d.is_dashed() && s.cap == LineCap::Round && !d.align_corners && even_dots(&d.pattern)); + let dash = if dots { None } else { s.dash.clone() }; + if !vectorcraft_effects::stroke::is_plain(&StrokeLayer { align: StrokeAlign::Center, dash, ..s.clone() }) { art.unsupported("arrowheads, width profiles, brushes or dashes fitted to corners"); } let style = match &s.dash { @@ -553,6 +556,11 @@ impl Rules<'_> { Paint::Solid { color, .. } => art.props.push(("border", format!("{width} {style} {}", color_css(color, s.opacity)))), Paint::Gradient(g) => match self.gradient(g, s.paint_bounds(bounds), s.opacity) { Some(css) => { + // A border image takes the place of the border's style + // (https://www.w3.org/TR/css-backgrounds-3/#border-images). + if style != "solid" { + art.unsupported("dashes or dots on a gradient border"); + } art.props.push(("border", format!("{width} {style}"))); art.props.push(("border-image", format!("{css} 1"))); } @@ -803,6 +811,13 @@ fn corners(path: &PathData, live: Option<&LiveShape>) -> Option { } } +/// Whether `pattern` (dash, gap, dash, gap…) draws evenly spaced dots: every dash has zero length +/// and every gap is the same. An odd-length pattern repeats with dashes and gaps swapped, so its +/// dashes can't all be zero unless the whole pattern is. +fn even_dots(pattern: &[f64]) -> bool { + pattern.len().is_multiple_of(2) && pattern.chunks(2).all(|c| c.first() == Some(&0.0) && c.get(1) == pattern.get(1)) +} + /// One closed subpath of four straight sides along the axes. fn is_upright_rectangle(path: &PathData) -> bool { let ([sp], Some(b)) = (path.subpaths.as_slice(), path.bounds()) else { return false }; diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index e8c84530d5..140b94e183 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -85,9 +85,8 @@ fn physical_num(v: f64) -> String { return "0".into(); } let leading_zeros = (-v.log10().floor() as i32).max(0); - let decimals = (leading_zeros + 3).clamp(3, 14) as u8; - let s = fmt_num(v, decimals); - if s == "0" && v > 0.0 { format!("{v:.16}").trim_end_matches('0').trim_end_matches('.').to_string() } else { s } + let decimals = (leading_zeros + 3).max(3); + if decimals > 14 { format!("{v:e}") } else { fmt_num(v, decimals as u8) } } /// `doc` as SVG with `opts`, the native file `native` embedded for Preserve Editing, its generated @@ -186,7 +185,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: .join(nl); svg.doctype_internal("svg", &entities, nl); } - let (ww, hh) = (w.num(rect.width()), w.num(rect.height())); + // A positive pixel size that the chosen decimals round to 0 is written with enough digits to stay positive. + let nonzero = |v: f64, s: String| if v > 0.0 && s == "0" { physical_num(v) } else { s }; + let (ww, hh) = (nonzero(rect.width(), w.num(rect.width())), nonzero(rect.height(), w.num(rect.height()))); let mut root = svg.root().attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); for (ns, prefix) in &w.foreign_ns { root = root.attr(&format!("xmlns:{prefix}"), ns); @@ -197,7 +198,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: if !opts.responsive { // Explicit SVG Options override the document unit; absence keeps its native save behavior. if let Some(unit) = opts.units { - let (width, height) = (unit.length(rect.width(), opts.decimals), unit.length(rect.height(), opts.decimals)); + // Pixels are written bare at one per point. + let (width, height) = + (nonzero(rect.width(), unit.length(rect.width(), opts.decimals)), nonzero(rect.height(), unit.length(rect.height(), opts.decimals))); root = root.attr("width", &width).attr("height", &height); } else if let Some((unit, suffix)) = doc.units.svg_unit().and_then(|u| Some((u, u.svg_suffix()?))) { let w_val = physical_num(unit.from_pt(rect.width())); @@ -207,9 +210,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: root = root.attr("width", &ww).attr("height", &hh); } } - let vb_w = if rect.width() > 0.0 && ww == "0" { physical_num(rect.width()) } else { ww.clone() }; - let vb_h = if rect.height() > 0.0 && hh == "0" { physical_num(rect.height()) } else { hh.clone() }; - root.attr("viewBox", format_args!("0 0 {vb_w} {vb_h}")).open(); + root.attr("viewBox", format_args!("0 0 {ww} {hh}")).open(); let mut out = svg.as_str().to_string(); out.push_str(nl); let css = opts.styling == Styling::InternalCss && !w.classes.is_empty(); diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 222b90b25c..109b3a938a 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -100,6 +100,7 @@ //! letter and word spacing become character attributes (line breaks, kerning, baseline shift, //! rotation and style names). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use craft_svg::tree::usvg; mod css; diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index 9c1cac5890..4a9e0050e2 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -1126,6 +1126,25 @@ fn weights_spacing_and_decoration() { assert_eq!(style('a').kerning, None); } +/// Font-size keywords scale `medium` (12), `larger` and `smaller` scale the parent's size by 1.2, +/// and `bolder` and `lighter` step from the parent's weight as CSS's relative-weight table says. +#[test] +fn font_size_keywords_and_relative_weights_follow_the_parent() { + let d = open( + r#"abcdefghijklm"#, + ); + let t = only_text(&d); + let style = |c: char| t.runs.iter().find(|r| r.text.contains(c)).unwrap().style.clone(); + let size = |c: char| style(c).size; + assert!(close(size('b'), 18.0, 1e-9), "x-large is 3/2 of medium: {}", size('b')); + assert!(close(size('d'), 12.0, 1e-9), "larger than 10: {}", size('d')); + assert!(close(size('e'), 10.0 / 1.2, 1e-9), "smaller than 10: {}", size('e')); + assert_eq!(style('g').font_style, "Bold", "bolder than 500 is 700"); + assert_eq!(style('i').font_style, "Black", "bolder than 600 is 900"); + assert_eq!(style('k').font_style, "Regular", "lighter than 700 is 400"); + assert_eq!(style('m').font_style, "Bold", "lighter than 900 is 700"); +} + /// `font-variation-settings` becomes the characters' Variable Font settings, inherited as CSS /// inherits it; `normal` and `initial` set none, and `unset` and a value CSS ignores leave the /// inherited settings. diff --git a/crates/svg/tests/it/import_units.rs b/crates/svg/tests/it/import_units.rs index 91138d8a93..1c17c156fe 100644 --- a/crates/svg/tests/it/import_units.rs +++ b/crates/svg/tests/it/import_units.rs @@ -3,7 +3,7 @@ use vectorcraft_doc::{Document, Node, NodeKind, Unit}; use vectorcraft_geom::Rect; -use vectorcraft_svg::{ExportOptions, export, import}; +use vectorcraft_svg::{ExportOptions, SizeUnit, export, import}; fn art(d: &Document) -> Vec<&Node> { let mut v = Vec::new(); @@ -191,6 +191,28 @@ fn export_physical_units_writes_unit_suffixes() { // Re-importing preserved physical units let back = import(&s).unwrap(); assert_eq!(back.units, Unit::Millimeters); + + // A small positive size in pixels keeps a nonzero width and height, with the document unit + // and with Pixels chosen in the SVG options + for (w, h) in [(0.0004, 0.0002), (1e-17, 2e-17), (5.1e-17, 1e-17), (5.1e-15, 4.9e-15)] { + let mut d = Document::new(w, h); + d.units = Unit::Pixels; + for opts in [ExportOptions::default(), ExportOptions { units: Some(SizeUnit::Px), ..Default::default() }] { + let s = export(&d, &opts); + let num = |name: &str| -> f64 { root_attr(&s, name).and_then(|v| v.parse().ok()).unwrap_or_else(|| panic!("{name}: {s}")) }; + let view: Vec = root_attr(&s, "viewBox").unwrap_or_default().split(' ').filter_map(|v| v.parse().ok()).collect(); + for (got, want) in [(num("width"), w), (num("height"), h), (view[2], w), (view[3], h)] { + assert!((got - want).abs() <= want * 1e-3, "{got} for {want}: {s}"); + } + } + } +} + +/// The value of attribute `name` on `svg`'s root element. +fn root_attr<'a>(svg: &'a str, name: &str) -> Option<&'a str> { + let start = svg.find("').next()?; + tag.split(&format!(" {name}=\"")).nth(1)?.split('"').next() } /// The `width` of `svg`'s root as a length in points, read by the SVG and CSS absolute units diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index fa7b39aa9d..fd86ad3c89 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -22,6 +22,7 @@ // apply here. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ai; pub mod ase; diff --git a/crates/text/build.rs b/crates/text/build.rs index 7863efe464..99eb1587f3 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -103,7 +103,8 @@ fn from_workspace(dir: PathBuf) -> PathBuf { return dir; } let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default()); - crate_dir.join("../..").join(dir) + // The workspace root is two levels above `crates/text`. + crate_dir.ancestors().nth(2).unwrap_or(&crate_dir).join(dir) } /// The one craft-fonts face web builds embed (family, style). diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index f2a7e4835e..80d1230994 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -100,8 +100,11 @@ pub struct FontDb { colours: Mutex, /// The installed fonts: the system font scan's faces, found by any of their names /// ([`FontDb::catalog`]). Lookups by family name wait for its first scan, so what they find - /// never depends on what ran before them. + /// never depends on what ran before them. The bundled faces join it on the first call of + /// [`FontDb::catalog`], so its faces are read through that call. catalog: Arc, + /// The bundled faces were added to [`Self::catalog`]. + bundled_cataloged: std::sync::Once, /// Fonts files carried for their type ([`vectorcraft_doc::FileFonts`]): apart from the faces, /// so no family name, font menu, fallback or PostScript name lookup finds them. pub(super) file_faces: RwLock, @@ -190,6 +193,40 @@ mod alias_tests { assert!(!sys.misses.contains(&'\u{E000}'), "an unsearched character is not a remembered miss"); } + /// The file search for a character no loaded font covers skips font files over 40 MiB + /// without reading them, and loads the same font at its own length. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_file_search_skips_font_files_over_40_mib() { + use crate::{FileFontInfo, FileGlyph, build_file_font}; + use kurbo::Shape; + let pua = '\u{E123}'; + let info = FileFontInfo { family: "Fallback Size Limit Regression".into(), style: "Regular".into(), ..Default::default() }; + let glyph = FileGlyph { ch: pua, outline: kurbo::Rect::new(0.0, 0.0, 500.0, 700.0).to_path(0.1), advance: 600.0 }; + let font = build_file_font(&info, &[glyph]).unwrap(); + // Removes the folder when dropped, so a panic part way through does not leave the 41 MiB file behind. + struct TempDir(std::path::PathBuf); + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let search = |name: &str, bytes: &[u8]| { + let dir = TempDir(std::env::temp_dir().join(format!("vc-fallback-size-{}-{name}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir(&dir.0).unwrap(); + std::fs::write(dir.0.join("Pua.ttf"), bytes).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.0.clone()]); + let found = db.system_fallback(pua); + std::fs::remove_dir_all(&dir.0).unwrap(); + found + }; + assert!(search("small", &font), "a font at its own length is loaded"); + let mut padded = font.clone(); + padded.resize(41 << 20, 0); + assert!(!search("padded", &padded), "the same font padded to 41 MiB is skipped"); + } + #[test] fn a_collection_lists_at_most_max_faces() { let mut font = name_font(&[(3, 0x0409, 1, "Fam"), (3, 0x0409, 2, "Regular")]); @@ -353,6 +390,28 @@ mod race_tests { } } +#[cfg(all(test, feature = "bundled-fonts"))] +mod bundled_catalog_tests { + use super::*; + + fn bundled_in_catalog(catalog: &Catalog) -> usize { + catalog.faces().iter().filter(|f| f.source == craft::font_catalog::Source::Bundled).count() + } + + #[test] + fn the_bundled_fonts_join_the_catalog_when_it_is_first_read() { + let db = FontDb::with_font_dirs(Vec::new()); + assert!(!db.read_faces().is_empty(), "the database draws with its bundled faces from the start"); + assert_eq!(bundled_in_catalog(&db.catalog), 0, "making the database copies no bundled font into the catalog"); + // A lookup that only the catalog answers finds a bundled face. + assert_eq!(db.by_postscript_name("SourceSans3-Bold"), Some(("Source Sans 3".to_string(), "Bold".to_string()))); + let added = bundled_in_catalog(&db.catalog); + assert!(added > 0, "the first read of the catalog adds the bundled fonts"); + assert!(db.catalog().families().iter().any(|f| f == "Inter"), "font pickers list a bundled family"); + assert_eq!(bundled_in_catalog(db.catalog()), added, "later reads add them no second time"); + } +} + #[cfg(test)] mod image_cache_tests { use super::*; diff --git a/crates/text/src/fontdb/added.rs b/crates/text/src/fontdb/added.rs index 2b0dc8e2e0..00d491924f 100644 --- a/crates/text/src/fontdb/added.rs +++ b/crates/text/src/fontdb/added.rs @@ -31,7 +31,7 @@ impl FontDb { /// is dated by the file the link leads to. Fonts loaded from bytes and the bundled fonts are /// never listed. Empty on wasm, which has no installed fonts. pub fn recently_added(&self, now: SystemTime) -> RecentlyAdded { - let faces = self.catalog.faces(); + let faces = self.catalog().faces(); // Each file's creation time once for all its faces (a collection or a variable font's // named instances share one). let mut created: HashMap<&Path, Option> = HashMap::new(); diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 474198cad6..b65dbab4f2 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -20,6 +20,14 @@ static NEXT_ID: AtomicU64 = AtomicU64::new(0); /// [`FontDb::global`]. static GLOBAL: std::sync::OnceLock = std::sync::OnceLock::new(); +/// The fonts a database starts with: the bundled fonts first, then explicitly supplied craft-fonts +/// faces: Japanese (Mincho first), Arabic, Thai, then remaining faces in manifest order. Existing +/// script fallback priorities stay ahead of the additional families users can now pick by name. +fn bundled_fonts() -> impl Iterator { + let craft = crate::craft_fonts::document_fonts().into_iter().map(|f| f.bytes); + BUNDLED.iter().copied().chain(craft) +} + impl FontDb { /// A database holding the bundled fonts, whose system font scan reads `font_dirs` (folders, /// read with their subfolders, and font files) and nothing else. @@ -44,15 +52,7 @@ impl FontDb { #[cfg(not(target_arch = "wasm32"))] catalog.set_confined_dirs(confined_font_dirs()); let mut faces = Vec::new(); - // Bundled fonts first, then explicitly supplied craft-fonts faces: Japanese (Mincho - // first), Arabic, Thai, then remaining faces in manifest order. Existing script fallback - // priorities stay ahead of the additional families users can now pick by name. - let craft = crate::craft_fonts::document_fonts().into_iter().map(|f| f.bytes); - for data in BUNDLED.iter().copied().chain(craft) { - // Font pickers list the catalog's families: the fonts the app carries are in it as bundled faces. - if let Err(e) = catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default()) { - log::warn!("a bundled font is not in the font catalog: {e}"); - } + for data in bundled_fonts() { for (i, spec) in enumerate_faces(data) { if let Some(f) = make_face(FontBytes::Static(data), i, spec, None) { faces.push(Arc::new(f)); @@ -65,6 +65,7 @@ impl FontDb { images: Mutex::new(GlyphCache::default()), colours: Mutex::new(GlyphCache::default()), catalog: Arc::new(catalog), + bundled_cataloged: std::sync::Once::new(), file_faces: RwLock::new(super::FileFaces::default()), canonical_cache: Mutex::new(CanonicalNames::new()), #[cfg(not(target_arch = "wasm32"))] @@ -119,7 +120,20 @@ impl FontDb { /// The installed fonts this database finds by name, shared with the framework's font menus and /// pickers. Its lookups wait for its first scan ([`FontDb::scan_in_background`]). + /// + /// The first call adds the bundled fonts to it as [`Source::Bundled`] faces, so font pickers + /// list them. A run that never looks a font up in the catalog, such as exporting a file without + /// type, does not hold the catalog's copies of their bytes. + // The catalog keeps its own copy of the bytes it is given. Adding the bundled fonts on first use + // can go once the catalog takes static bytes without copying them (craft-libs#4888). pub fn catalog(&self) -> &Arc { + self.bundled_cataloged.call_once(|| { + for data in bundled_fonts() { + if let Err(e) = self.catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default()) { + log::warn!("a bundled font is not in the font catalog: {e}"); + } + } + }); &self.catalog } @@ -164,7 +178,7 @@ impl FontDb { /// [`FontDb::families`], shared: cheap to call every frame. pub fn family_list(&self) -> Arc<[String]> { // The catalog's list is the same `Arc` until it rescans (here or in its watch). - let installed = self.catalog.families(); + let installed = self.catalog().families(); let mut cache = self.family_cache.lock().unwrap_or_else(|e| e.into_inner()); if let Some((from, list)) = cache.as_ref() && Arc::ptr_eq(from, &installed) @@ -238,7 +252,7 @@ impl FontDb { } // An installed family's, from its names in other languages, as a loaded face's is chosen // (every face of a family has the same names: one is enough). - let native = self.catalog.resolve(&family, "").and_then(|(f, _)| { + let native = self.catalog().resolve(&family, "").and_then(|(f, _)| { let names: Vec<(Option, String)> = f.localized_families.into_iter().map(|n| (n.language, n.name)).collect(); pick_native_label(&f.family, &names) }); @@ -256,7 +270,7 @@ impl FontDb { v.push((f.italic, f.weight, f.style.clone())); } } - for f in self.catalog.styles(family) { + for f in self.catalog().styles(family) { if !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&f.style)) { v.push((f.italic, f.weight, f.style)); } @@ -282,7 +296,7 @@ impl FontDb { for f in self.read_faces().iter().filter(|f| f.family.eq_ignore_ascii_case(family)) { consider(&mut best, f.weight, f.italic, &f.style); } - for f in self.catalog.styles(family) { + for f in self.catalog().styles(family) { consider(&mut best, f.weight, f.italic, &f.style); } best.map(|(_, style)| style) @@ -347,7 +361,7 @@ impl FontDb { /// folders, any other waits for that scan to finish, as every catalog lookup does. #[cfg(any(test, feature = "test-fonts"))] pub(crate) fn ensure_catalog(&self) { - let _ = self.catalog.families(); + let _ = self.catalog().families(); } /// Catalog the installed fonts on a background thread, so the first lookup by family name @@ -370,14 +384,14 @@ impl FontDb { let _change = self.catalog.is_ready().then(crate::test_fonts::font_change); // The first scan, or a rescan once it is done (never both at once). The count is of the installed faces: the // catalog's less the bundled faces no installed file also has. - let cataloged = self.catalog.rescan(); - let bundled_only = self.catalog.faces().iter().filter(|f| f.source == Source::Bundled && self.catalog.versions(f).len() == 1).count(); + let catalog = self.catalog(); + let cataloged = catalog.rescan(); + let bundled_only = catalog.faces().iter().filter(|f| f.source == Source::Bundled && catalog.versions(f).len() == 1).count(); let n = cataloged.saturating_sub(bundled_only); // Files may have been installed since: other versions are looked for again, in the catalog // the rescan published. A version lookup made during the scan read the previous one. self.version_scanned.write().unwrap_or_else(|e| e.into_inner()).clear(); - let installed: std::collections::HashSet = - self.catalog.faces().iter().flat_map(|f| self.catalog.versions(f)).filter_map(|f| f.path).collect(); + let installed: std::collections::HashSet = catalog.faces().iter().flat_map(|f| catalog.versions(f)).filter_map(|f| f.path).collect(); // Faces loaded from a file this scan did not catalog, as a face or a version of one (the font was removed, or its folder // is no longer read) are dropped with their outlines. A family with no face left and no // cataloged file leaves the lists, and type set in it resolves to the fallback font. A face diff --git a/crates/text/src/fontdb/installed.rs b/crates/text/src/fontdb/installed.rs index 05ec64bccb..01b04f1a99 100644 --- a/crates/text/src/fontdb/installed.rs +++ b/crates/text/src/fontdb/installed.rs @@ -30,13 +30,12 @@ impl FontDb { // The catalog first: the first scan takes the faces' lock, which a guard held here would block. // The bundled faces have no file to read. The catalog lists a bundled face ahead of an // installed file of the same face, so each face's file is its first installed version. - let cataloged: Vec<(String, String, PathBuf)> = self - .catalog + let catalog = self.catalog(); + let cataloged: Vec<(String, String, PathBuf)> = catalog .faces() .iter() .filter_map(|f| { - let path = - self.catalog.versions(f).into_iter().filter(|v| v.source != craft::font_catalog::Source::Bundled).find_map(|v| v.path)?; + let path = catalog.versions(f).into_iter().filter(|v| v.source != craft::font_catalog::Source::Bundled).find_map(|v| v.path)?; Some((f.family.clone(), f.style.clone(), path)) }) .collect(); diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index f1a024d020..671b62ddad 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -73,7 +73,7 @@ impl FontDb { } #[cfg(not(target_arch = "wasm32"))] { - let faces = self.catalog.styles(family); + let faces = self.catalog().styles(family); let off = |f: &craft::font_catalog::FaceInfo| (f.italic, (f.weight - 400.0).abs()); let nearest = faces.iter().min_by(|a, b| { let ((ai, aw), (bi, bw)) = (off(a), off(b)); @@ -89,7 +89,7 @@ impl FontDb { /// Is `family` an installed family's own name (any ASCII case)? fn is_installed(&self, family: &str) -> bool { - self.catalog.family(family).is_some_and(|f| f.eq_ignore_ascii_case(family)) + self.catalog().family(family).is_some_and(|f| f.eq_ignore_ascii_case(family)) } /// The family's own name and the style for a name given in a document: any of a family's @@ -124,7 +124,7 @@ impl FontDb { self.read_faces().iter().flat_map(|f| Alias::of(&f.family, &f.style, &f.keys)).filter(|(k, _)| *k == key).map(|(_, a)| a).collect(); // The installed face the name gives: by a family name in its family, by a legacy family // name with its legacy style, by a full or PostScript name whatever the style. - let installed = self.catalog.resolve(family, style); + let installed = self.catalog().resolve(family, style); let ns = norm(style); // A family and style split from a PostScript name by an importer that didn't have the font // (`Honoka-Mincho` → Honoka, Mincho): once it is installed, the face of that PostScript @@ -147,7 +147,7 @@ impl FontDb { if let Some(a) = found.iter().find(|a| a.style.is_none()) { return (a.family.clone(), style.to_string()); } - if let Some(installed_family) = self.catalog.family(family) { + if let Some(installed_family) = self.catalog().family(family) { return (installed_family, style.to_string()); } if let Some(a) = found.iter().find(|a| a.paired.as_ref().is_some_and(|p| *p == ns) || a.paired.is_none()) { @@ -278,7 +278,7 @@ impl FontDb { let key = norm(name); let mut families: Vec = vec![first.family.clone()]; let named = |f: &&FaceInfo| f.postscript_name.as_deref().is_some_and(|p| norm(p) == key); - for f in self.catalog.faces().iter().filter(named) { + for f in self.catalog().faces().iter().filter(named) { if families.len() < MAX_POSTSCRIPT_FACES && !families.iter().any(|known| known.eq_ignore_ascii_case(&f.family)) { families.push(f.family.clone()); } @@ -303,13 +303,14 @@ impl FontDb { /// The cataloged face of PostScript name `name`: an installed face before a bundled face of another family with the /// same name, as the installed faces alone answered before the bundled ones were cataloged. fn cataloged_postscript(&self, name: &str) -> Option { - let face = self.catalog.by_postscript_name(name)?; + let catalog = self.catalog(); + let face = catalog.by_postscript_name(name)?; if face.source != Source::Bundled { return Some(face); } let key = norm(name); let named = |f: &&FaceInfo| f.source != Source::Bundled && f.postscript_name.as_deref().is_some_and(|p| norm(p) == key); - Some(self.catalog.faces().iter().find(named).cloned().unwrap_or(face)) + Some(catalog.faces().iter().find(named).cloned().unwrap_or(face)) } /// Load the files of the installed `family`, every cataloged version of its faces included, @@ -317,8 +318,9 @@ impl FontDb { /// thread meanwhile. #[cfg(not(target_arch = "wasm32"))] fn load_cataloged(&self, family: &str) -> bool { - let faces = self.catalog.styles(family); - let mut paths: Vec = faces.iter().flat_map(|f| self.catalog.versions(f)).filter_map(|f| f.path).collect(); + let catalog = self.catalog(); + let faces = catalog.styles(family); + let mut paths: Vec = faces.iter().flat_map(|f| catalog.versions(f)).filter_map(|f| f.path).collect(); paths.sort(); paths.dedup(); let files = paths.into_iter().flat_map(|p| font_files(&p).into_iter().map(move |data| (data, Some(p.clone())))); @@ -403,7 +405,7 @@ impl FontDb { #[cfg(not(target_arch = "wasm32"))] fn is_cataloged(&self, family: &str, style: &str) -> bool { let ns = norm(style); - self.catalog.styles(family).iter().any(|f| norm(&f.style) == ns) + self.catalog().styles(family).iter().any(|f| norm(&f.style) == ns) } /// The loaded face with [`FontFace::id`] `id` (the face a laid-out glyph came from), an @@ -680,7 +682,7 @@ impl FontDb { } sys.file_searches += 1; } - let mut paths: Vec = self.catalog.faces().iter().filter_map(|f| f.path.clone()).collect(); + let mut paths: Vec = self.catalog().faces().iter().filter_map(|f| f.path.clone()).collect(); paths.sort(); paths.dedup(); for p in paths { diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index 54e4125e88..2fd95fd6b2 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -793,7 +793,77 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, #[cfg(test)] mod tests { - use super::longest_start_tried; + use super::{Affine, ArcPath, BezPath, GlyphBend, PathEl, Point, bend_outline, longest_start_tried}; + use vectorcraft_geom::{Rect, shapes}; + + /// A glyph-sized rectangle in pen space, `w` wide and `h` tall, standing on the baseline. + fn block(w: f64, h: f64) -> BezPath { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((w, 0.0)); + p.line_to((w, h)); + p.line_to((0.0, h)); + p.close_path(); + p + } + + fn end_points(path: &BezPath) -> Vec { + path.elements() + .iter() + .filter_map(|el| match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(p), + PathEl::ClosePath => None, + }) + .collect() + } + + /// Bent along a circle, a rectangle's baseline edge follows the circle and its other edge + /// follows a circle `h` farther along the path's normal; its corners stay at the ends of its + /// step along the path. Moving it off the path (`rise`) moves both edges by the same amount. + #[test] + fn an_outline_bent_along_a_circle_follows_it() { + let (center, r) = (Point::new(100.0, 100.0), 100.0); + let ap = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0))); + let (w, h, s) = (40.0, 20.0, 30.0); + let (p0, d0) = ap.at(s); + let (p1, _) = ap.at(s + w); + // Which way the path's normal points: away from the center (+1) or towards it (-1). + let side = (kurbo::Vec2::new(-d0.y, d0.x).dot(p0 - center)).signum(); + let at_radius = |p: Point, radius: f64| center + (p - center) * (radius / r); + for rise in [0.0, 5.0] { + let bend = GlyphBend { s, step: w, advance: w, rise }; + let bent = bend_outline(&block(w, h), Affine::IDENTITY, &ap, &bend).expect("a turning path bends the outline"); + let points = end_points(&bent); + let (base, top) = (r + side * rise, r + side * (rise + h)); + let corners = [at_radius(p0, base), at_radius(p1, base), at_radius(p1, top), at_radius(p0, top)]; + for c in corners { + assert!(points.iter().any(|p| p.distance(c) < 0.1), "rise {rise}: no point near the corner {c:?} in {points:?}"); + } + // The edges are cut into pieces that stay between the two circles; a straight chord + // between the corners would pass inside the inner one. + assert!(points.len() > 8, "rise {rise}: {} points", points.len()); + let (inner, outer) = (base.min(top), base.max(top)); + for p in &points { + let d = p.distance(center); + assert!(d > inner - 0.1 && d < outer + 0.1, "rise {rise}: {p:?} lies {d} from the center, outside {inner}..{outer}"); + } + let on_base = points.iter().filter(|p| (p.distance(center) - base).abs() < 0.1).count(); + assert!(on_base > 2, "rise {rise}: only {on_base} points on the baseline circle"); + } + } + + /// A path that does not turn under the glyph, and a glyph with no advance, leave the outline + /// as it is. + #[test] + fn an_outline_on_a_straight_path_is_not_bent() { + let line = ArcPath::new(&shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0))); + let bend = GlyphBend { s: 30.0, step: 40.0, advance: 40.0, rise: 0.0 }; + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &line, &bend).is_none()); + let circle = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0))); + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &bend).is_some()); + let no_advance = GlyphBend { advance: 0.0, ..bend }; + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &no_advance).is_none()); + } /// The longest start that fits is found among the ones tried; past the tries, a binary search /// finds one that fits, with as many more tries as halvings of the rest. diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 25e44392d6..4723f1ffcd 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -9,6 +9,7 @@ //! //! Frames (`TextKind::Area`) and paths (`TextKind::OnPath`) are interpreted in text space. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod bitmap; mod colr; diff --git a/crates/three-d/Cargo.toml b/crates/three-d/Cargo.toml index 48d2bfbf05..b5153163ce 100644 --- a/crates/three-d/Cargo.toml +++ b/crates/three-d/Cargo.toml @@ -11,6 +11,7 @@ workspace = true [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-pathops = { workspace = true } +craft-pbr = { workspace = true } [dev-dependencies] proptest = { workspace = true } diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 891ff4fcbc..37768ea651 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -7,6 +7,7 @@ //! //! [`fold`] finds the panels and hinges of a flat packaging blank from its fold lines. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod fold; mod solid; @@ -21,6 +22,8 @@ mod shading; pub use shading::{ClassicShading, ClassicSurface, LightGradient, RgbGradient, ShadeGradient}; mod lights; pub use lights::{Light, Lights, MAX_LIGHTS}; +mod material; +pub use material::{Highlight, Material}; mod caps; mod mesh; pub use mesh::{ @@ -106,6 +109,9 @@ pub struct Revolve { /// Ambient Light, 0 to 2. pub ambient: f64, pub shade: bool, + /// The surface's Roughness and Metallic. [`Material::DEFAULT`] shades as before they existed; + /// any other material adds its specular light ([`Highlight`]). + pub material: Material, /// Interpolate profile normals using vector gradients. Enabled by default. pub smooth_shading: bool, /// Close circular endpoint rings of open profiles (sectors on a partial sweep), and the two @@ -149,6 +155,7 @@ impl Default for Revolve { lights: None, ambient: 0.25, shade: true, + material: Material::DEFAULT, smooth_shading: true, cap_ends: true, fill_rule: FillRule::NonZero, @@ -377,6 +384,9 @@ pub struct Face { pub illumination: [f64; 3], pub light_gradient: Option, pub rgb_gradient: Option, + /// The light a material other than [`Material::DEFAULT`] reflects over the paint; `None` for + /// the default material and when the face is not shaded. + pub highlight: Option, /// Curved vector boundary; points remain a bounded visibility approximation. pub outline: Option, /// A single endpoint disk or sector, with its axis centre first in points. @@ -695,6 +705,29 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi if area.abs() < 1e-10 { return Ok(None); } + if material::shades(&o) { + let seen = |n: &V3| if n.dot(normal) < 0.0 { V3(-n.0, -n.1, -n.2) } else { *n }; + let corners: Vec = normals + .map(|normals| normals.iter().zip(vertices).map(|(n, v)| material::lit(&o, seen(n), material::to_eye(eye, *v), light)).collect()) + .unwrap_or_default(); + let shading = Shading::of(&points, &corners, material::lit(&o, normal, material::to_eye(eye, centre), light)); + return Ok(Some(Face { + points, + depth: vertices.iter().map(|v| v.2).sum::() / vertices.len() as f64, + normal: [normal.0, normal.1, normal.2], + brightness: shading.brightness, + gradient: shading.gradient, + illumination: shading.illumination, + light_gradient: shading.light_gradient, + rgb_gradient: shading.rgb_gradient, + highlight: Some(shading.highlight), + outline: None, + cap: false, + visibility_pieces: None, + surface: None, + plane, + })); + } let (brightness, gradient) = if let Some(normals) = normals { let values: Vec<_> = normals .iter() @@ -741,6 +774,7 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi illumination, light_gradient, rgb_gradient, + highlight: None, outline: None, cap: false, visibility_pieces: None, @@ -749,6 +783,63 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi })) } +/// A face's lighting under a material other than [`Material::DEFAULT`]. +pub(crate) struct Shading { + pub(crate) brightness: f64, + pub(crate) gradient: Option, + pub(crate) illumination: [f64; 3], + /// The tone ramp with the face's mean hue for mapped graphics. Proportional, unclipped RGB + /// channels share this ramp exactly; independent channel placements retain only their mean hue. + pub(crate) light_gradient: Option, + pub(crate) rgb_gradient: Option, + pub(crate) highlight: Highlight, +} + +impl Shading { + /// The lighting of a face drawn at `points` whose corners are lit as `corners` (none for a + /// flatly shaded face) and whose own normal is lit as `flat`. A face with corner values takes + /// their mean; three corners also give the smooth ramps. + pub(crate) fn of(points: &[Point], corners: &[material::Lit], flat: material::Lit) -> Self { + let mean = |pick: fn(&material::Lit) -> [f64; 3]| -> [f64; 3] { + if corners.is_empty() { + return pick(&flat); + } + let mut sum = [0.0; 3]; + for c in corners { + for (s, v) in sum.iter_mut().zip(pick(c)) { + *s += v; + } + } + sum.map(|s| s / corners.len() as f64) + }; + let illumination = mean(|l| l.paint).map(|v| v.clamp(0.0, 1.0)); + let average = |rgb: [f64; 3]| (rgb[0] + rgb[1] + rgb[2]) / 3.0; + let paints: Vec<[f64; 3]> = corners.iter().map(|c| c.paint).collect(); + let overs: Vec<[f64; 3]> = corners.iter().map(|c| c.over).collect(); + let tones: Vec = paints.iter().map(|p| average(p.map(|v| v.clamp(0.0, 1.0)))).collect(); + let brightness = average(illumination); + let gradient = ShadeGradient::triangle(points, &tones); + let rgb_gradient = RgbGradient::triangle(points, &paints); + let light_gradient = rgb_gradient.map(|rgb| LightGradient { + diffuse: gradient.unwrap_or(ShadeGradient { + start: rgb.channels[0].start, + end: rgb.channels[0].start, + brightness: [tones.iter().sum::() / tones.len() as f64; 2], + }), + ambient: 0.0, + color: if brightness == 0.0 || illumination == [illumination[0]; 3] { [1.0; 3] } else { illumination.map(|v| v / brightness) }, + }); + Self { + brightness, + gradient, + illumination, + light_gradient, + rgb_gradient, + highlight: Highlight { flat: mean(|l| l.over), ramp: RgbGradient::triangle(points, &overs) }, + } + } +} + /// Evaluate a profile in document space. All subpaths share one axis from `bounds`. /// Invalid or excessively complex inputs return an error, never a partial surface. pub fn revolve(path: &PathData, bounds: Rect, options: Revolve) -> Result, String> { diff --git a/crates/three-d/src/material.rs b/crates/three-d/src/material.rs new file mode 100644 index 0000000000..fef547d017 --- /dev/null +++ b/crates/three-d/src/material.rs @@ -0,0 +1,395 @@ +//! A surface's Roughness and Metallic, and the light they reflect. +//! +//! The specular light of each light and of the environment is craft-pbr's metallic-roughness BRDF: +//! glTF 2.0's Appendix B form with B.3.2's separable Smith visibility (B.3.5, +//! ) for a +//! directional light, and the split sum of Karis 2013 over craft-pbr's default studio environment. +//! Schlick's Fresnel (B.3.4) is linear in the reflectance at normal incidence `f0`, and +//! `f0 = 0.04 (1 − metallic) + base × metallic`, so the specular light of a paint `base` is +//! `base × A + B` for two values that do not depend on the paint. [`Lit::paint`] holds the diffuse +//! light plus `A`, which scales the paint as the lighting does today, and [`Lit::over`] holds `B`, +//! which is screened over the shaded paint. The diffuse light is the softened Lambert term of the +//! lights, scaled by `(1 − F) (1 − metallic)` with the Fresnel term `F` of the 0.04 dielectric +//! reflectance, and Ambient Light scaled by `1 − metallic`. +//! +//! The effects draw `paint` as a color layer that multiplies the paint, so each channel of `paint` is +//! clamped to 0..1 where it is drawn (`Shading::of`). Where a bright light or a low Roughness +//! makes `paint` greater than 1, the drawn face stops at that limit. The highlight `h` is also +//! drawn with Screen, so the drawn color is `p + h − p × h` for the shaded paint `p`, not `p + h`. + +use std::sync::OnceLock; + +use craft_pbr::{EnvImage, Limits, Material as Brdf, PrefilterOptions}; + +use crate::{Revolve, V3}; + +/// The reflectance at normal incidence of a dielectric, as glTF 2.0 gives it. +const DIELECTRIC: f64 = 0.04; + +/// A surface's Roughness and Metallic, each from 0 to 1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Material { + roughness: f64, + metallic: f64, +} + +impl Default for Material { + fn default() -> Self { + Self::DEFAULT + } +} + +impl Material { + /// Roughness 1 and Metallic 0: the surface the 3D effects draw without a material, shaded + /// exactly as before Roughness and Metallic existed. + pub const DEFAULT: Self = Self { roughness: 1.0, metallic: 0.0 }; + + /// A material, or `None` unless `roughness` and `metallic` are both numbers from 0 to 1. + pub fn new(roughness: f64, metallic: f64) -> Option { + let unit = |v: f64| v.is_finite() && (0.0..=1.0).contains(&v); + (unit(roughness) && unit(metallic)).then_some(Self { roughness, metallic }) + } + + pub fn roughness(self) -> f64 { + self.roughness + } + + pub fn metallic(self) -> f64 { + self.metallic + } + + /// Is this [`Material::DEFAULT`]? + pub fn is_default(self) -> bool { + self == Self::DEFAULT + } +} + +/// The light a surface with a material other than [`Material::DEFAULT`] reflects over its paint: +/// the RGB values screened over the shaded paint at the face's normal (`flat`), and on a smoothly +/// shaded triangle, those values interpolated from its corners (`ramp`), before each channel is +/// clipped to 0..1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Highlight { + pub flat: [f64; 3], + pub ramp: Option, +} + +/// The light at one point of a surface ([`lit`]): what scales the paint, per RGB channel, and +/// what is screened over it. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct Lit { + pub(crate) paint: [f64; 3], + pub(crate) over: [f64; 3], +} + +/// Does `o` shade with its material ([`lit`]) rather than as before materials existed? Only when +/// it is shaded and its material is not [`Material::DEFAULT`]. +pub(crate) fn shades(o: &Revolve) -> bool { + o.shade && !o.material.is_default() +} + +/// The unit direction from view-space point `at` to the eye at `eye` in front of the center, or +/// straight toward the viewer without perspective (`None`) or when `at` is at the eye. +pub(crate) fn to_eye(eye: Option, at: V3) -> V3 { + let v = eye.map_or(V3(0.0, 0.0, 1.0), |e| V3(0.0, 0.0, e).sub(at).unit()); + if v.dot(v) < 0.5 { V3(0.0, 0.0, 1.0) } else { v } +} + +#[cfg(test)] +thread_local! { + /// How many times this thread has evaluated craft-pbr's direct BRDF, for the tests. + pub(crate) static DIRECT_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The specular light of one light from direction `l` on a surface with normal `n` seen from `v`, +/// per unit of the light's color and intensity, for `f0` 0 and for `f0` 1 (craft-pbr's +/// [`Brdf::try_direct`] with a metal whose base color holds both). 0 for directions that are not +/// finite. +fn specular(n: V3, v: V3, l: V3, roughness: f64) -> [f64; 2] { + #[cfg(test)] + DIRECT_CALLS.with(|c| c.set(c.get() + 1)); + let f = |p: V3| [p.0 as f32, p.1 as f32, p.2 as f32]; + let Ok(metal) = Brdf::try_new([0.0, 1.0, 0.0], 1.0, roughness as f32) else { return [0.0; 2] }; + let metal = metal.with_visibility(craft_pbr::Visibility::SmithSeparable); + match metal.try_direct(f(n), f(v), f(l)) { + Ok([zero, one, _]) if zero.is_finite() && one.is_finite() => [f64::from(zero).max(0.0), f64::from(one).max(f64::from(zero))], + _ => [0.0; 2], + } +} + +/// craft-pbr's default studio environment, GGX-prefiltered once per process into its six +/// roughness levels; `None` when it could not be built. +fn environment() -> Option<&'static [EnvImage]> { + static CHAIN: OnceLock>> = OnceLock::new(); + CHAIN + .get_or_init(|| { + let env = craft_pbr::default_environment().ok()?; + craft_pbr::try_prefilter(&env, &PrefilterOptions::default(), &Limits::default()).ok() + }) + .as_deref() +} + +/// The environment's prefiltered radiance in view-space direction `d` (x right, y down, z toward +/// the viewer) for `roughness`, between the two levels nearest it. The environment's up is the +/// page's up, and its +X the page's right. 0 when it is unavailable. +fn environment_light(d: V3, roughness: f64) -> [f64; 3] { + let Some(chain) = environment().filter(|c| !c.is_empty()) else { return [0.0; 3] }; + let dir = [d.0 as f32, -d.1 as f32, d.2 as f32]; + let at = roughness.clamp(0.0, 1.0) * (chain.len() - 1) as f64; + let (lo, t) = (at.floor() as usize, at - at.floor()); + let sample = |k: usize| chain.get(k.min(chain.len() - 1)).and_then(|level| level.sample(dir).ok()).map(|c| c.map(f64::from)); + match (sample(lo), sample(lo + 1)) { + (Some(a), Some(b)) => std::array::from_fn(|c| a[c] + (b[c] - a[c]) * t), + (Some(a), None) => a, + _ => [0.0; 3], + } +} + +/// The light at a point with unit normal `n` (turned to the side the viewer sees) seen from unit +/// direction `v`, under `o`'s lights (or its single light from `legacy`) and environment, for +/// `o`'s material ([`Lit`]). +pub(crate) fn lit(o: &Revolve, n: V3, v: V3, legacy: V3) -> Lit { + let (roughness, metallic) = (o.material.roughness, o.material.metallic); + let mut out = Lit { paint: [o.ambient * (1.0 - metallic); 3], over: [0.0; 3] }; + let mut add = |l: V3, color: [f64; 3], intensity: f64, softness: f64| { + let diffuse = intensity * ((n.dot(l) + softness) / (1.0 + softness)).max(0.0); + let h = V3(v.0 + l.0, v.1 + l.1, v.2 + l.2).unit(); + let k = if h.dot(h) < 0.5 { 0.0 } else { (1.0 - v.dot(h).max(0.0)).clamp(0.0, 1.0).powi(5) }; + let fresnel = DIELECTRIC + (1.0 - DIELECTRIC) * k; + let [zero, one] = if n.dot(l) > 0.0 { specular(n, v, l, roughness) } else { [0.0; 2] }; + let lobe = one - zero; + for c in 0..3 { + out.paint[c] += color[c] * (diffuse * (1.0 - fresnel) * (1.0 - metallic) + intensity * metallic * lobe); + out.over[c] += color[c] * intensity * (DIELECTRIC * (1.0 - metallic) * lobe + zero); + } + }; + match o.lights { + Some(lights) => { + for light in lights.iter() { + let [x, y, z] = light.direction(); + add(V3(x, y, z), light.color, light.intensity, light.softness); + } + } + None => add(legacy, o.light_color, o.light_intensity, o.light_softness), + } + let n_v = n.dot(v); + let reflected = V3(2.0 * n_v * n.0 - v.0, 2.0 * n_v * n.1 - v.1, 2.0 * n_v * n.2 - v.2).unit(); + if let (Ok([scale, bias]), true) = (craft_pbr::try_environment_brdf(n_v as f32, roughness as f32), reflected.dot(reflected) > 0.5) { + let (scale, bias) = (f64::from(scale), f64::from(bias)); + let radiance = environment_light(reflected, roughness); + for c in 0..3 { + let e = radiance[c] * o.ambient; + out.paint[c] += e * metallic * scale; + out.over[c] += e * (DIELECTRIC * (1.0 - metallic) * scale + bias); + } + } + let finite = |v: [f64; 3]| v.map(|c| if c.is_finite() { c.max(0.0) } else { 0.0 }); + Lit { paint: finite(out.paint), over: finite(out.over) } +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_geom::{Rect, Shape}; + + /// One white light of intensity 1 from `l`, no softness and no ambient (so no environment), in + /// `material`. + fn one_light(material: Material) -> Revolve { + Revolve { ambient: 0.0, light_intensity: 1.0, light_softness: 0.0, light_color: [1.0; 3], lights: None, material, ..Revolve::default() } + } + + #[test] + fn a_material_takes_numbers_from_0_to_1_only() { + for (r, m) in [(0.0, 0.0), (1.0, 1.0), (0.5, 0.25)] { + assert!(Material::new(r, m).is_some(), "{r} {m}"); + } + for (r, m) in [(f64::NAN, 0.0), (0.5, f64::INFINITY), (f64::NEG_INFINITY, 0.0), (-0.01, 0.0), (1.01, 0.0), (0.0, -0.5), (0.0, 1.5)] { + assert_eq!(Material::new(r, m), None, "{r} {m}"); + } + assert!(Material::DEFAULT.is_default() && Material::default().is_default()); + assert!(!Material::new(0.99, 0.0).is_some_and(Material::is_default)); + } + + /// The paint scale and the screened light split craft-pbr's direct BRDF exactly: for any base + /// color, `base × paint + over` is craft-pbr's whole result for a dielectric and for a metal. + #[test] + fn the_paint_and_its_highlight_add_up_to_the_brdf() { + let (n, v) = (V3(0.0, 0.0, 1.0), V3(0.3, -0.2, 0.93).unit()); + let l = V3(-0.4, -0.5, 0.77).unit(); + for (roughness, metallic) in [(0.2, 0.0), (0.6, 0.0), (0.2, 1.0), (0.7, 1.0), (1.0, 1.0)] { + let Some(material) = Material::new(roughness, metallic) else { panic!("{roughness} {metallic}") }; + let lit = lit(&one_light(material), n, v, l); + for base in [[0.8f32, 0.2, 0.1], [0.1, 0.5, 0.9], [1.0, 1.0, 1.0]] { + let Ok(brdf) = Brdf::try_new(base, metallic as f32, roughness as f32) else { panic!("material") }; + let brdf = brdf.with_visibility(craft_pbr::Visibility::SmithSeparable); + let f = |p: V3| [p.0 as f32, p.1 as f32, p.2 as f32]; + let Ok(want) = brdf.try_direct(f(n), f(v), f(l)) else { panic!("brdf") }; + for c in 0..3 { + let got = f64::from(base[c]) * lit.paint[c] + lit.over[c]; + assert!((got - f64::from(want[c])).abs() < 1e-4, "{roughness} {metallic} {base:?} channel {c}: {got} vs {}", want[c]); + } + } + } + } + + /// Compares the full Appendix B result for metallic 0 and 1. At metallic 0.5 only the specular + /// term is compared: the diffuse uses dielectric Fresnel regardless of metallic, while the + /// specular term uses the base-dependent f0 of B.3.4. Softness and ambient are zero, so these + /// comparisons are exact, including the Fresnel-weighted Lambert term at metallic 0. + #[test] + fn specular_matches_the_gltf_formula() { + let directions = [ + (V3(0.0, 0.0, 1.0), V3(0.3, -0.2, 0.93), V3(-0.4, -0.5, 0.77)), + (V3(0.2, 0.1, 1.0), V3(-0.2, 0.4, 1.0), V3(0.6, -0.1, 0.8)), + (V3(-0.1, 0.3, 1.0), V3(0.4, 0.2, 1.0), V3(-0.5, 0.4, 1.0)), + ]; + let pi = std::f64::consts::PI; + for roughness in [0.1_f64, 0.5, 0.9] { + for metallic in [0.0, 0.5, 1.0] { + for (n, v, l) in directions { + let (n, v, l) = (n.unit(), v.unit(), l.unit()); + let h = V3(v.0 + l.0, v.1 + l.1, v.2 + l.2).unit(); + let (nl, nv, nh, vh) = (n.dot(l), n.dot(v), n.dot(h), v.dot(h)); + assert!(nl > 0.3 && nv > 0.3); + let a = roughness * roughness; + let a2 = a * a; + let root = |x: f64| (a2 + (1.0 - a2) * x * x).sqrt(); + let visibility = 1.0 / ((nl + root(nl)) * (nv + root(nv))); + let distribution = a2 / (pi * (nh * nh * (a2 - 1.0) + 1.0).powi(2)); + let k = (1.0 - vh).powi(5); + let material = Material::new(roughness, metallic).unwrap_or_else(|| panic!("material")); + let got = lit(&one_light(material), n, v, l); + for base in [[0.8, 0.2, 0.1], [0.1, 0.5, 0.9]] { + for c in 0..3 { + let f0 = 0.04 * (1.0 - metallic) + base[c] * metallic; + let fresnel = f0 + (1.0 - f0) * k; + let specular = fresnel * distribution * visibility * nl * pi; + let diffuse = (1.0 - fresnel) * (1.0 - metallic) * base[c] * nl; + let (actual, expected) = if metallic == 0.5 { + // Remove the softened Lambert term to isolate base * metallic * lobe + over. + let dielectric_f = 0.04 + 0.96 * k; + (base[c] * (got.paint[c] - nl * (1.0 - dielectric_f) * (1.0 - metallic)) + got.over[c], specular) + } else { + (base[c] * got.paint[c] + got.over[c], diffuse + specular) + }; + assert!((actual - expected).abs() < 1e-4, "{roughness} {metallic} {n:?} {v:?} {l:?} channel {c}: {actual} vs {expected}"); + } + } + } + } + } + } + + /// glTF 2.0's BRDF at normal incidence: with n = v = l, h = n, so the GGX D is 1 / (π α²) for + /// α = roughness², Fresnel is f0, and a metal reflects its base color while a dielectric + /// reflects 0.04 of the light over a diffuse 0.96 × (1 − metallic). + #[test] + fn at_normal_incidence_a_dielectric_reflects_four_percent_over_its_diffuse_light() { + let n = V3(0.0, 0.0, 1.0); + let Some(material) = Material::new(0.5, 0.0) else { panic!("material") }; + let dielectric = lit(&one_light(material), n, n, n); + let Some(metal) = Material::new(0.5, 1.0) else { panic!("material") }; + let metal = lit(&one_light(metal), n, n, n); + // The lobe of a white metal is the dielectric's highlight over 0.04. + let lobe = metal.paint[0]; + assert!(lobe > 0.0, "{metal:?}"); + for c in 0..3 { + assert!((dielectric.paint[c] - 0.96).abs() < 1e-6, "diffuse {:?}", dielectric.paint); + assert!((dielectric.over[c] - 0.04 * lobe).abs() < 1e-6, "{dielectric:?} {metal:?}"); + assert!(metal.over[c].abs() < 1e-6, "a metal's highlight is its paint: {metal:?}"); + } + // D V π at α = 0.25, with V from craft-pbr's visibility, falls as roughness rises. + let Some(rough) = Material::new(0.9, 1.0) else { panic!("material") }; + assert!(lit(&one_light(rough), n, n, n).paint[0] < lobe); + } + + #[test] + fn light_from_behind_the_surface_reflects_no_highlight() { + let Some(material) = Material::new(0.1, 0.5) else { panic!("material") }; + let lit = lit(&one_light(material), V3(0.0, 0.0, 1.0), V3(0.0, 0.0, 1.0), V3(0.0, 0.0, -1.0)); + assert_eq!(lit.over, [0.0; 3]); + assert_eq!(lit.paint, [0.0; 3]); + } + + /// The environment adds light only through Ambient Light: with it, a smooth metal facing the + /// viewer is lit even with its lights turned away. + #[test] + fn ambient_light_reflects_the_studio_environment() { + let Some(material) = Material::new(0.1, 1.0) else { panic!("material") }; + let o = Revolve { ambient: 1.0, light_intensity: 0.0, material, ..Revolve::default() }; + let n = V3(0.0, 0.0, 1.0); + let lit = lit(&o, n, n, V3(0.0, 0.0, -1.0)); + assert!(lit.paint.iter().all(|c| *c > 0.0 && c.is_finite()), "{lit:?}"); + } + + fn square() -> vectorcraft_geom::PathData { + vectorcraft_geom::PathData::from_bezpath(&Rect::new(0.0, 0.0, 40.0, 80.0).to_path(0.1)) + } + + /// Revolve's faces with the default material are those of the shading without materials: no + /// highlight, and craft-pbr is not called. + #[test] + fn the_default_material_shades_as_before_and_calls_no_brdf() { + DIRECT_CALLS.with(|c| c.set(0)); + let faces = crate::revolve(&square(), Rect::new(0.0, 0.0, 40.0, 80.0), Revolve::default()).unwrap_or_default(); + assert!(!faces.is_empty()); + assert!(faces.iter().all(|f| f.highlight.is_none())); + assert_eq!(DIRECT_CALLS.with(std::cell::Cell::get), 0); + let Some(material) = Material::new(0.4, 0.3) else { panic!("material") }; + let shaded = crate::revolve(&square(), Rect::new(0.0, 0.0, 40.0, 80.0), Revolve { material, ..Revolve::default() }).unwrap_or_default(); + assert_eq!(shaded.len(), faces.len()); + assert!(shaded.iter().all(|f| f.highlight.is_some())); + // One evaluation per lit point of each face: its normal and its smooth corners. + let calls = DIRECT_CALLS.with(std::cell::Cell::get); + assert!(calls > 0 && calls <= faces.len() * 5, "{calls} for {} faces", faces.len()); + let unshaded = + crate::revolve(&square(), Rect::new(0.0, 0.0, 40.0, 80.0), Revolve { material, shade: false, ..Revolve::default() }).unwrap_or_default(); + assert!(unshaded.iter().all(|f| f.highlight.is_none())); + } + + /// Mapped graphics follow each smooth material face's RGB lighting under a white light, + /// including triangles whose lighting is constant. + #[test] + fn a_materials_graphic_light_matches_its_rgb_ramp_under_white_light() { + let Some(material) = Material::new(0.4, 0.0) else { panic!("material") }; + let faces = crate::revolve(&square(), Rect::new(0.0, 0.0, 40.0, 80.0), one_light(material)).unwrap_or_default(); + let color = [0.2, 0.5, 0.8]; + let mut smooth_faces = 0; + let mut varying_faces = 0; + for face in &faces { + let Some(rgb) = face.rgb_gradient else { continue }; + smooth_faces += 1; + varying_faces += usize::from(face.gradient.is_some()); + let Some(light) = face.light_gradient else { panic!("a material RGB face must also shade its graphics smoothly") }; + for &point in &face.points { + let want = rgb.at(point); + let got = light.at(point); + let scale = (0..3).map(|c| color[c] * want[c]).fold(0.0, f64::max); + for c in 0..3 { + let error = (color[c] * got[c] - color[c] * want[c]).abs(); + assert!(error <= 1e-6 * scale, "at {point:?}, channel {c}: {got:?} vs {want:?}"); + } + } + } + assert!(smooth_faces > 0, "the revolved square must have smooth RGB faces"); + assert!(varying_faces > 0, "the graphic lighting must be checked across a varying ramp"); + } + + /// The step from the default material to the nearest others, measured on Revolve's faces: the + /// largest change of a face's brightness and of its highlight. + #[test] + fn the_nearest_materials_to_the_default_change_the_shading_by_a_measured_step() { + let b = Rect::new(0.0, 0.0, 40.0, 80.0); + let faces = |material| crate::revolve(&square(), b, Revolve { material, ..Revolve::default() }).unwrap_or_default(); + let base = faces(Material::DEFAULT); + for (r, m) in [(0.99, 0.0), (1.0, 0.01)] { + let Some(material) = Material::new(r, m) else { panic!("material") }; + let near = faces(material); + assert_eq!(near.len(), base.len()); + let brightness = base.iter().zip(&near).map(|(a, b)| (a.brightness - b.brightness).abs()).fold(0.0, f64::max); + let highlight = near.iter().filter_map(|f| f.highlight).map(|h| h.flat.iter().copied().fold(0.0, f64::max)).fold(0.0, f64::max); + println!("roughness {r} metallic {m}: brightness changes by at most {brightness:.4}, highlight at most {highlight:.4}"); + assert!(brightness < 0.1 && highlight < 0.1, "{r} {m}: {brightness} {highlight}"); + } + } +} diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index 53e1cb5786..77c6371e49 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -527,41 +527,174 @@ fn bridge(ring: Vec, hole: &[Corner], others: &[Vec], work: &mut /// is set and it lies straight between them: it then stays a corner of the triangles beside it. If /// no ear is left (a ring that crosses itself), the rest is cut as a fan. fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight: bool) -> Result<(), String> { + let grid = if ring.len() > GRID_CORNERS { Grid::new(ring) } else { None }; + cut(ring, out, work, keep_straight, grid.as_ref()).map(|_| ()) +} + +/// Rings with more corners than this are sorted into a [`Grid`] before they are cut. +const GRID_CORNERS: usize = 64; + +/// The corners of a ring sorted into square cells, so that the test of an ear looks only at the +/// corners in the cells its triangle covers, widened by `margin`. +struct Grid { + x: f64, + y: f64, + size: f64, + cols: usize, + rows: usize, + /// Where each cell's corners start in `corners`, row by row, with the end of the last cell + /// after them. + start: Vec, + corners: Vec, + /// How far outside a triangle the cells looked at reach: far more than the rounding of the + /// tests of a corner against the triangle's edges, at the size and distance from the origin of + /// the ring. + margin: f64, +} + +impl Grid { + /// The grid of `ring`, about one corner to a cell. `None` for a ring with a corner that is not + /// finite or with no extent. + fn new(ring: &[Corner]) -> Option { + if !ring.iter().all(|c| c.x.is_finite() && c.y.is_finite()) { + return None; + } + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for c in ring { + (x0, y0, x1, y1) = (x0.min(c.x), y0.min(c.y), x1.max(c.x), y1.max(c.y)); + } + let extent = (x1 - x0).max(y1 - y0); + let size = extent / (ring.len() as f64).sqrt().ceil(); + if !(size > 0.0 && size.is_finite()) { + return None; + } + let (cols, rows) = (((x1 - x0) / size) as usize + 1, ((y1 - y0) / size) as usize + 1); + let cells = cols.checked_mul(rows)?; + let reach = x0.abs().max(x1.abs()).max(y0.abs()).max(y1.abs()); + let margin = (extent + reach) * 1e-6 + 1e-8; + let mut grid = Grid { x: x0, y: y0, size, cols, rows, start: vec![], corners: vec![], margin }; + let mut start = vec![0usize; cells + 1]; + for c in ring { + start[grid.cell(c) + 1] += 1; + } + for k in 1..start.len() { + start[k] += start[k - 1]; + } + let mut fill = start.clone(); + let mut corners = vec![0; ring.len()]; + for (k, c) in ring.iter().enumerate() { + let at = &mut fill[grid.cell(c)]; + corners[*at] = k; + *at += 1; + } + (grid.start, grid.corners) = (start, corners); + Some(grid) + } + + fn col(&self, x: f64) -> usize { + (((x - self.x) / self.size).max(0.0) as usize).min(self.cols - 1) + } + + fn row(&self, y: f64) -> usize { + (((y - self.y) / self.size).max(0.0) as usize).min(self.rows - 1) + } + + fn cell(&self, c: &Corner) -> usize { + self.row(c.y) * self.cols + self.col(c.x) + } + + /// Whether `blocks` holds for a corner in a cell that triangle `t` covers, widened by the + /// margin. Every corner within the margin of the triangle is in such a cell. + fn any_near(&self, t: [&Corner; 3], mut blocks: impl FnMut(usize) -> bool) -> bool { + let m = self.margin; + let low = t.iter().map(|p| p.y).fold(f64::INFINITY, f64::min); + let high = t.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max); + for r in self.row(low - m)..=self.row(high + m) { + // The triangle's extent across the row's band, widened by the margin each way. + let top = self.y + r as f64 * self.size; + let (from, to) = ((top - m).clamp(low, high), (top + self.size + m).clamp(low, high)); + let (mut left, mut right) = (f64::INFINITY, f64::NEG_INFINITY); + for (p, q) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + let (p, q) = if p.y <= q.y { (p, q) } else { (q, p) }; + if q.y < from || p.y > to { + continue; + } + let xs = if q.y > p.y { + let at = |y: f64| p.x + (y - p.y) / (q.y - p.y) * (q.x - p.x); + [at(from.max(p.y)), at(to.min(q.y))] + } else { + [p.x, q.x] + }; + for x in xs { + (left, right) = (left.min(x), right.max(x)); + } + } + if left > right { + continue; + } + for col in self.col(left - m)..=self.col(right + m) { + let cell = r * self.cols + col; + if self.corners[self.start[cell]..self.start[cell + 1]].iter().any(|&k| blocks(k)) { + return true; + } + } + } + false + } +} + +/// [`clip`], looking up the corners an ear's test needs in `grid` when there is one, for a triangle +/// whose every angle has a sine of at least 1e-6: a corner that passes the test then lies within +/// the grid's margin of the triangle. Other ears test every corner left. Returns the number of +/// corners tested against ears. +fn cut(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight: bool, grid: Option<&Grid>) -> Result { let n = ring.len(); if n < 3 { - return Ok(()); + return Ok(0); } let mut next: Vec = (1..=n).map(|i| i % n).collect(); let mut prev: Vec = (0..n).map(|i| (i + n - 1) % n).collect(); - let (mut left, mut i, mut tried) = (n, 0usize, 0usize); + let mut gone = vec![false; n]; + let (mut left, mut i, mut tried, mut tested) = (n, 0usize, 0usize, 0usize); let cross = |a: &Corner, b: &Corner, c: &Corner| (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); let same = |a: &Corner, b: &Corner| (a.x - b.x).hypot(a.y - b.y) < 1e-12; while left > 3 { let (a, c) = (prev[i], next[i]); let (pa, pb, pc) = (&ring[a], &ring[i], &ring[c]); let turn = cross(pa, pb, pc); - let scale = (pb.x - pa.x).hypot(pb.y - pa.y) * (pc.x - pb.x).hypot(pc.y - pb.y); + let (ab, bc) = ((pb.x - pa.x).hypot(pb.y - pa.y), (pc.x - pb.x).hypot(pc.y - pb.y)); + let scale = ab * bc; let mut ear = false; let flat = turn.abs() <= 1e-12 * scale.max(1e-300); let straight = keep_straight && flat && (pb.x - pa.x) * (pc.x - pb.x) + (pb.y - pa.y) * (pc.y - pb.y) > 0.0; let drop = flat && !straight; if !flat && turn > 0.0 { spend(work, left)?; - ear = true; - let mut k = next[c]; - while k != a { + // A corner inside the ear, or a kept corner on the ear's new edge, which would be + // left off every triangle. + let mut blocks = |k: usize| { + if k == a || k == i || k == c || gone[k] { + return false; + } + tested += 1; let p = &ring[k]; - if !same(p, pa) && !same(p, pb) && !same(p, pc) && cross(pa, pb, p) > 0.0 && cross(pb, pc, p) > 0.0 && cross(pc, pa, p) > 0.0 { - ear = false; - break; + (cross(pa, pb, p) > 0.0 && cross(pb, pc, p) > 0.0 && cross(pc, pa, p) > 0.0 && !same(p, pa) && !same(p, pb) && !same(p, pc)) + || (keep_straight && touches((p.x, p.y), (pc.x, pc.y), (pa.x, pa.y))) + }; + let ca = (pa.x - pc.x).hypot(pa.y - pc.y); + let blocked = match grid { + Some(grid) if turn >= 1e-6 * (ab * bc).max(ab * ca).max(bc * ca) => grid.any_near([pa, pb, pc], &mut blocks), + _ => { + let mut k = next[c]; + let mut found = false; + while k != a && !found { + found = blocks(k); + k = next[k]; + } + found } - // A kept corner on the ear's new edge would be left off every triangle. - if keep_straight && touches((p.x, p.y), (pc.x, pc.y), (pa.x, pa.y)) { - ear = false; - break; - } - k = next[k]; - } + }; + ear = !blocked; } if !ear && !drop && tried > left { // No ear anywhere: cut what is left as a fan. @@ -571,7 +704,7 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight out.push([ring[start].v, ring[k].v, ring[next[k]].v]); k = next[k]; } - return Ok(()); + return Ok(tested); } if ear || drop { if ear { @@ -579,6 +712,7 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight } next[a] = c; prev[c] = a; + gone[i] = true; left -= 1; i = a; tried = 0; @@ -589,7 +723,7 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight } let (a, c) = (prev[i], next[i]); out.push([ring[a].v, ring[i].v, ring[c].v]); - Ok(()) + Ok(tested) } #[cfg(test)] diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 29d58a66f6..960f85dbf0 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -235,6 +235,136 @@ fn flat_triangles_stop_at_their_budget() { assert!(work >= all, "{work} of {all}"); } +fn ring_of(points: &[(f64, f64)]) -> Vec { + points.iter().map(|&(x, y)| Corner { x, y, v: V3(x, y, 0.0) }).collect() +} + +/// `n` corners on a circle of radius `r` about (`x`, `y`), every other one pulled in to `inner` +/// times the radius, counterclockwise, or clockwise when `back` is set. +fn star_ring(n: usize, x: f64, y: f64, r: f64, inner: f64, back: bool) -> Vec { + let mut points: Vec<(f64, f64)> = (0..n) + .map(|i| { + let (s, c) = (std::f64::consts::TAU * i as f64 / n as f64).sin_cos(); + let r = if i % 2 == 1 { r * inner } else { r }; + (x + r * c, y + r * s) + }) + .collect(); + if back { + points.reverse(); + } + ring_of(&points) +} + +/// `count` rings drawn from a fixed seed, each counterclockwise about its center: corners at random +/// angles and distances, with every other corner pulled in close to the center in some (spikes), +/// corners rounded to whole numbers and slanted in some (so that corners on other parts of the ring +/// lie exactly on the line between two corners), corners midway along every edge in some, some +/// stretched along one axis, some so small that a corner within the tolerance of an ear's new edge +/// lies in another cell, and some far from the origin. +fn random_rings(count: usize) -> Vec> { + let mut seed = 0x9e37_79b9_7f4a_7c15_u64; + let mut unit = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + (0..count) + .map(|k| { + let n = 70 + (unit() * 200.0) as usize; + let mut angles: Vec = (0..n).map(|_| unit() * std::f64::consts::TAU).collect(); + angles.sort_by(f64::total_cmp); + angles.dedup(); + let spiky = k % 3 == 1; + let whole = k % 3 != 0; + let mut points: Vec<(f64, f64)> = angles + .iter() + .enumerate() + .map(|(i, a)| { + let r = if spiky && i % 2 == 1 { 0.05 + 0.1 * unit() } else { 0.5 + 0.5 * unit() }; + let (x, y) = (r * a.cos(), r * a.sin()); + if whole { + let (x, y) = ((40.0 * x).round(), (40.0 * y).round()); + (x + y, y) + } else { + (x, y) + } + }) + .collect(); + points.dedup(); + if points.first() == points.last() { + points.pop(); + } + if k % 2 == 0 { + points = points.iter().zip(points.iter().cycle().skip(1)).flat_map(|(&p, &q)| [p, ((p.0 + q.0) / 2.0, (p.1 + q.1) / 2.0)]).collect(); + } + let (sx, sy) = [(1.0, 1.0), (1024.0, 1.0), (1.0, 1.0 / 1024.0), (32.0, 64.0), (1e-7, 1e-7)][k % 5]; + let (ox, oy) = if k % 7 == 0 { ((1e6 * (unit() - 0.5)).round(), (1e6 * (unit() - 0.5)).round()) } else { (0.0, 0.0) }; + ring_of(&points.iter().map(|&(x, y)| (ox + sx * x, oy + sy * y)).collect::>()) + }) + .collect() +} + +/// The triangles `ring` is cut into, with the ring's corners sorted into a grid as [`clip`] sorts +/// them, or without one, and the number of corners tested against ears. +fn cut_ring(ring: &[Corner], keep_straight: bool, grid: bool) -> (Vec<[[u64; 3]; 3]>, usize) { + let grid = if grid && ring.len() > GRID_CORNERS { Grid::new(ring) } else { None }; + let (mut out, mut work) = (vec![], 0); + let tested = cut(ring, &mut out, &mut work, keep_straight, grid.as_ref()).unwrap(); + (out.into_iter().map(|t| t.map(|v| [v.0.to_bits(), v.1.to_bits(), v.2.to_bits()])).collect(), tested) +} + +#[test] +fn a_large_cap_is_cut_testing_few_corners_per_ear() { + // Tested against every corner left, the ears of a ring of n corners test about n * n / 2. + let n = 4096; + let (triangles, tested) = cut_ring(&star_ring(n, 0.0, 0.0, 100.0, 1.0, false), false, true); + assert_eq!(triangles.len(), n - 2); + assert!(tested <= 64 * n, "a ring of {n} corners tested {tested} corners against its ears"); + let (triangles, tested) = cut_ring(&star_ring(n, 0.0, 0.0, 100.0, 0.9, false), false, true); + assert_eq!(triangles.len(), n - 2); + assert!(tested <= 64 * n, "a star of {n} corners tested {tested} corners against its ears"); +} + +#[test] +fn rings_cut_with_a_grid_give_the_triangles_cut_without_one() { + let mut rings = vec![ + star_ring(500, 0.0, 0.0, 100.0, 1.0, false), + star_ring(1000, 3.0, -7.0, 50.0, 0.4, false), + star_ring(999, 0.0, 0.0, 1.0, 0.97, false), + // Far from the origin, where the rounding of the tests is largest. + star_ring(800, 1e7, -3e7, 20.0, 0.6, false), + ]; + // Holes bridged to their outline, so that some corners appear twice. + let mut work = 0; + let mut outline = star_ring(600, 0.0, 0.0, 100.0, 0.8, false); + for (k, (x, y)) in [(30.0, 0.0), (-20.0, 25.0), (-10.0, -40.0)].into_iter().enumerate() { + let hole = star_ring(90 + 10 * k, x, y, 12.0, 0.5, true); + outline = bridge(outline, &hole, &[], &mut work).unwrap(); + } + rings.push(outline); + // Edges carrying corners midway, as a cell shares with its finer neighbors. + let mut square = vec![]; + for (from, to) in [((0.0, 0.0), (10.0, 0.0)), ((10.0, 0.0), (10.0, 10.0)), ((10.0, 10.0), (0.0, 10.0)), ((0.0, 10.0), (0.0, 0.0))] { + for i in 0..40 { + let t = i as f64 / 40.0; + square.push((from.0 + (to.0 - from.0) * t, from.1 + (to.1 - from.1) * t)); + } + } + let square = ring_of(&square); + let dent = ring_of(&[(4.0, 4.0), (4.0, 6.0), (6.0, 6.0), (6.0, 5.0), (6.0, 4.0), (5.0, 4.0)]); + rings.push(bridge(square.clone(), &dent, &[], &mut work).unwrap()); + rings.push(square); + rings.extend(random_rings(1200)); + for (k, ring) in rings.iter().enumerate() { + for keep_straight in [false, true] { + let (with, _) = cut_ring(ring, keep_straight, true); + let (without, _) = cut_ring(ring, keep_straight, false); + assert!(with == without, "ring {k} (keep_straight {keep_straight}) is cut into other triangles with a grid"); + } + } +} + #[test] fn an_inside_bevel_stays_inside_a_collapsing_convex_outline() { for points in [ diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 49e42e6732..deeaab4dde 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -4,7 +4,7 @@ //! z-axis, about the centre of its bounds, at the art's own position and size. Planar faces (caps //! and the rotated plane) are drawn whole, holes included, so no triangulation is needed; curved //! faces are cut into small facets. Colored Inflate interpolates shared membrane normals; -//! bevels and side walls retain their planar lighting. +//! bevel bands interpolate shared normals for non-default materials, and side walls retain planar lighting. //! //! Visibility is a painter's algorithm, as for Revolve: faces of a closed solid that face away //! from the viewer are left out, the rest are drawn back to front. @@ -60,6 +60,8 @@ pub struct View { pub lights: Option, pub ambient: f64, pub shade: bool, + /// The surface's Roughness and Metallic, as Revolve's. + pub material: crate::Material, } impl Default for View { @@ -79,6 +81,7 @@ impl Default for View { lights: r.lights, ambient: r.ambient, shade: r.shade, + material: r.material, } } } @@ -90,6 +93,12 @@ impl View { view.lights.map_or(view.light_color != [1.0; 3], |lights| lights.iter().any(|light| light.color != [1.0; 3])) } + /// Whether the view shades with a material other than [`crate::Material::DEFAULT`], which also + /// needs RGB shading: its highlight ([`Facet::highlight`]) and a metal's tint. + pub fn shades_material(self) -> bool { + crate::material::shades(&self.revolve()) + } + /// The same rotation, projection and lighting maths as Revolve's. fn revolve(self) -> Revolve { Revolve { @@ -106,6 +115,7 @@ impl View { lights: self.lights, ambient: self.ambient, shade: self.shade, + material: self.material, ..Revolve::default() } .sanitized() @@ -402,8 +412,12 @@ pub struct Facet { /// The face's unit normal in view space (x right, y down, z toward the viewer), turned to the /// side the viewer sees. pub normal: [f64; 3], - /// Smooth lighting on an inflated triangle, before clipping individual RGB channels. + /// Smooth lighting on an inflated triangle or a bevel-band triangle, before clipping + /// individual RGB channels. pub rgb_gradient: Option, + /// The light a material other than [`crate::Material::DEFAULT`] reflects over the paint; + /// `None` for the default material and when the facet is not shaded. + pub highlight: Option, /// The facet's outline with the profile's curves kept as cubics, for [`Facet::path`]. The /// contours stay the polygon that visibility and depth use. pub outline: Option, @@ -518,6 +532,7 @@ impl Facet { illumination: face.illumination, normal: face.normal, rgb_gradient: None, + highlight: face.highlight, outline: face.outline, side: !face.cap, // A revolved cap is not one of the planar faces graphics map onto. diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 63a6e76e68..8d74f3135f 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -201,6 +201,8 @@ pub(super) struct Builder<'a> { /// A closed solid keeps the faces turned away from the viewer too, with their outward normals, /// drawn behind the others. pub(super) hidden: bool, + /// Whether doubling every band face fits within the solid's face limit. + pub(super) split_bands: bool, pub(super) facets: Vec, /// With `Some`, every face goes here as it is, none hidden or projected, for a mesh. pub(super) mesh: Option>, @@ -244,6 +246,7 @@ impl<'a> Builder<'a> { camera, closed, hidden, + split_bands: false, facets: vec![], mesh: (keep != Keep::Facets).then(Vec::new), draw: keep != Keep::Faces, @@ -342,13 +345,21 @@ impl<'a> Builder<'a> { } else { centre.2 }; + let (brightness, illumination, highlight) = if crate::material::shades(&self.camera.view) { + let flat = crate::material::lit(&self.camera.view, n, crate::material::to_eye(self.camera.eye, centre), self.camera.light); + let shading = crate::Shading::of(&[], &[], flat); + (shading.brightness, shading.illumination, Some(shading.highlight)) + } else { + (self.camera.brightness(n), crate::illumination(&self.camera.view, n, self.camera.light), None) + }; self.facets.push(Facet { contours, depth, - brightness: self.camera.brightness(n), - illumination: crate::illumination(&self.camera.view, n, self.camera.light), + brightness, + illumination, normal: [n.0, n.1, n.2], rgb_gradient: None, + highlight, outline: None, side: false, away: behind, @@ -387,6 +398,29 @@ impl<'a> Builder<'a> { if self.facets.len() == before || !self.camera.view.shade { return Ok(()); } + if crate::material::shades(&self.camera.view) { + let view = &self.camera.view; + let corners: Vec = normals + .into_iter() + .zip(vertices) + .map(|(n, v)| { + crate::material::lit( + view, + if flip { V3(-n.0, -n.1, -n.2) } else { n }, + crate::material::to_eye(self.camera.eye, v), + self.camera.light, + ) + }) + .collect(); + if let Some(face) = self.facets.last_mut() { + let points = face.contours.first().map(Vec::as_slice).unwrap_or_default(); + let flat = crate::material::Lit { paint: face.illumination, over: face.highlight.map_or([0.0; 3], |h| h.flat) }; + let shading = crate::Shading::of(points, &corners, flat); + face.rgb_gradient = shading.rgb_gradient; + face.highlight = Some(shading.highlight); + } + return Ok(()); + } let values: Vec<_> = normals .into_iter() .map(|n| crate::unclipped_illumination(&self.camera.view, if flip { V3(-n.0, -n.1, -n.2) } else { n }, self.camera.light)) @@ -405,7 +439,10 @@ impl<'a> Builder<'a> { /// `curves`, the pieces of curve the rings' edges follow and the outlines at `a` and `b`, each /// quad keeps its edges along the profile curved. An edge cut into pieces is cut at points of /// its curve, each piece taking an equal share of the edge's piece of curve. With `side`, each - /// quad carries where its corners lie on the side unrolled flat ([`Facet::surface`]). + /// quad carries where its corners lie on the side unrolled flat ([`Facet::surface`]). Smoothed + /// bands shaded with a non-default material draw as two triangles when doubling every band + /// face fits within the solid's face limit; otherwise each band keeps one facet. Each triangle + /// has its own corner lighting and side coordinates. The mesh keeps the quad and its corner normals. pub(super) fn curved_band( &mut self, [a, b]: [&[V3]; 2], @@ -440,13 +477,15 @@ impl<'a> Builder<'a> { normal = V3(-normal.0, -normal.1, -normal.2); } let before = self.facets.len(); + let vertices = [quad[0], quad[1], quad[2], quad[3]]; + let na = mesh.normals.and_then(|(na, _)| na.get(i)?.get(k).copied().flatten()); + let nb = mesh.normals.and_then(|(_, nb)| nb.get(i)?.get(k).copied().flatten()); + let smooth = crate::material::shades(&self.camera.view) && (na.is_some() || nb.is_some()); let attrs = |_: &[Vec]| { let (u0, u1) = (mesh.u.get(i).copied().unwrap_or(0.5), mesh.u.get(i + 1).copied().unwrap_or(0.5)); let (ua, ub) = (u0 + (u1 - u0) * s0, u0 + (u1 - u0) * s1); let [va, vb] = mesh.v; // Each piece of a cut edge takes the normals smoothed for that piece. - let na = mesh.normals.and_then(|(na, _)| na.get(i)?.get(k).copied().flatten()); - let nb = mesh.normals.and_then(|(_, nb)| nb.get(i)?.get(k).copied().flatten()); Attrs::Corners(vec![vec![([ua, va], na), ([ub, va], na), ([ub, vb], nb), ([ua, vb], nb)]]) }; self.face(vec![quad], normal, order, mesh.part, attrs)?; @@ -476,14 +515,72 @@ impl<'a> Builder<'a> { }); } } - if let Some(w) = curves.as_mut() + // A band is split only when it is one facet with four corners on the page and on its surfaces. + let four = |page: &[Point], uv: &[Point]| page.len() == 4 && uv.len() == 4; + let split = self.split_bands + && smooth + && self.facets.len() == before + 1 + && self.facets.last().is_some_and(|b| { + b.contours.len() == 1 + && b.contours[0].len() == 4 + && b.cell.as_ref().is_none_or(|c| four(&c.page, &c.uv)) + && b.surface.as_ref().is_none_or(|c| four(&c.page, &c.uv)) + }); + if split && let Some(band) = self.facets.pop() { + // Both triangles keep the band's culling, normal, plane and paint order. + let normal = V3(band.normal[0], band.normal[1], band.normal[2]); + let points = vertices.map(|v| self.camera.project(v)); + let corners = [na, na, nb, nb].map(|n| n.unwrap_or(normal)); + let corners = std::array::from_fn::<_, 4, _>(|j| { + let n = corners[j]; + let n = if n.dot(normal) < 0.0 { V3(-n.0, -n.1, -n.2) } else { n }; + crate::material::lit(&self.camera.view, n, crate::material::to_eye(self.camera.eye, vertices[j]), self.camera.light) + }); + let flat = crate::material::Lit { paint: band.illumination, over: band.highlight.map_or([0.0; 3], |h| h.flat) }; + for (mut f, indices) in [band.clone(), band].into_iter().zip([[0, 1, 2], [0, 2, 3]]) { + let select = |points: &[Point]| indices.map(|j| points[j]).to_vec(); + f.contours = vec![select(&f.contours[0])]; + if let Some(cell) = f.cell.as_mut() { + cell.page = select(&cell.page); + cell.uv = select(&cell.uv); + } + if let Some(cell) = f.surface.as_mut() { + cell.page = select(&cell.page); + cell.uv = select(&cell.uv); + } + #[cfg(test)] + { + f.view = vec![indices.map(|j| vertices[j]).to_vec()]; + } + let shading = crate::Shading::of(&indices.map(|j| points[j]), &indices.map(|j| corners[j]), flat); + f.brightness = shading.brightness; + f.illumination = shading.illumination; + f.rgb_gradient = shading.rgb_gradient; + f.highlight = Some(shading.highlight); + self.facets.push(f); + } + if self.facets.len() > MAX_SOLID_FACES { + return Err(TOO_COMPLEX_SURFACE.into()); + } + } + if self.draw + && let Some(w) = curves.as_mut() && let Some(span) = span { // An edge cut on its chord, with no place on the curve for its cut corners, // stays straight. let near = w.near.filter(|_| pieces == 1 || w.places[0].is_some()); let far = w.far.filter(|_| pieces == 1 || w.places[1].is_some()); - self.outline(before, |c| c.first().and_then(|quad| outline::wall(&span, (t(s0), t(s1)), ends, quad, near, far, w.budget))); + if split { + let quad = vertices.map(|v| self.camera.project(v)); + for (half, f) in self.facets[before..].iter_mut().enumerate() { + f.outline = outline::wall(&span, (t(s0), t(s1)), ends, &quad, near, far, Some(half), w.budget); + } + } else { + self.outline(before, |c| { + c.first().and_then(|quad| outline::wall(&span, (t(s0), t(s1)), ends, quad, near, far, None, w.budget)) + }); + } } } } @@ -859,10 +956,10 @@ fn step_coordinates(steps: &[Step], depth: f64) -> Vec { } /// The largest angle, in degrees, between two neighboring bands of one bevel whose shared corners -/// are smoothed for a mesh. A sharper turn (a Step profile's) stays a hard edge. +/// are smoothed. A sharper turn (a Step profile's) stays a hard edge. pub(crate) const BEVEL_CREASE: f64 = 60.0; -/// For a mesh, the normal of each corner of each piece of each edge of `ring` at each step (one +/// The normal of each corner of each piece of each edge of `ring` at each step for meshes and material ramps (one /// list per step, one list per edge, one entry per piece: `cuts[i]` pieces along edge `i`, as /// [`Builder::curved_band`] cuts it, or one) where the bands on either side are smoothed: two /// bands of the same bevel, front or back, that turn by less than [`BEVEL_CREASE`], neither of @@ -996,6 +1093,7 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio } let camera = Camera::new(view, bounds, o.depth); let mut b = Builder::new(&camera, o.cap, o.hidden, keep); + b.split_bands = edges.saturating_mul(bands).saturating_mul(2).saturating_add(caps) <= MAX_SOLID_FACES; let z = |t: f64| o.depth / 2.0 - o.depth * t; let ring_at = |ring: &[Point], s: &Step| -> Vec { section(&inset(ring, s.inset), bounds, &o, s.t).iter().map(|p| camera.place(*p, z(s.t))).collect() }; @@ -1065,7 +1163,7 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio let unrolled = unrolled.as_ref().filter(|(k, ..)| *k == r); let placed: Vec> = steps.iter().map(|s| ring_at(ring, s)).collect(); let u = along_ring(ring); - let rows = if b.keeps_mesh() { + let rows = if b.keeps_mesh() || crate::material::shades(&camera.view) { let at: Vec<&Place> = places.iter().map(|p| p as &Place).collect(); smoothed_rows(&camera, ring, &steps, &placed, pieces, &traced.spans, &at) } else { diff --git a/crates/three-d/src/solid/outline.rs b/crates/three-d/src/solid/outline.rs index b2491896d7..1345945a46 100644 --- a/crates/three-d/src/solid/outline.rs +++ b/crates/three-d/src/solid/outline.rs @@ -212,7 +212,8 @@ pub(super) fn face(rings: &[&Ring], points: &[Vec], step: &Along, budget: /// takes). `ends` are the corners of the whole edges at `near` and at `far` (projected, where each /// starts and ends on all of `span`), so that a piece follows the curve the whole edge does, as the /// cap's edge it meets. An edge without its outline stays straight. `None` when neither edge is -/// curved. +/// curved. With `triangle`, return only half 0 (`a`, `a'`, `b'`) or half 1 (`a`, `b'`, `b`), +/// keeping that half's profile curve and a straight shared diagonal from `a` to `b'`. #[allow(clippy::too_many_arguments)] pub(super) fn wall( span: &Span, @@ -221,6 +222,7 @@ pub(super) fn wall( quad: &[Point], near: Option<&Along>, far: Option<&Along>, + triangle: Option, budget: &mut Budget, ) -> Option { let [a, a2, b2, b] = <[Point; 4]>::try_from(quad).ok()?; @@ -231,21 +233,25 @@ pub(super) fn wall( finite.then_some(Whole { t: (span.t0, span.t1), d }) }; let [near_ends, far_ends] = ends; - let front = near.and_then(|near| piece(near, span, t0, t1, (t1, t0), a, a2, whole(near, near_ends), budget)); - let back = far.and_then(|far| piece(far, span, t1, t0, (t0, t1), b2, b, whole(far, far_ends), budget)); + let front = near.filter(|_| triangle != Some(1)).and_then(|near| piece(near, span, t0, t1, (t1, t0), a, a2, whole(near, near_ends), budget)); + let back = far.filter(|_| triangle != Some(0)).and_then(|far| piece(far, span, t1, t0, (t0, t1), b2, b, whole(far, far_ends), budget)); if front.is_none() && back.is_none() { return None; } let mut path = BezPath::new(); path.move_to(a); - match front { - Some(curves) => curves.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)), - None => path.line_to(a2), + if triangle != Some(1) { + match front { + Some(curves) => curves.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)), + None => path.line_to(a2), + } } path.line_to(b2); - match back { - Some(curves) => curves.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)), - None => path.line_to(b), + if triangle != Some(0) { + match back { + Some(curves) => curves.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)), + None => path.line_to(b), + } } path.close_path(); Some(PathData::from_bezpath(&path)) diff --git a/crates/three-d/src/solid/tests_limits.rs b/crates/three-d/src/solid/tests_limits.rs index bd70096232..9ff4392389 100644 --- a/crates/three-d/src/solid/tests_limits.rs +++ b/crates/three-d/src/solid/tests_limits.rs @@ -91,6 +91,43 @@ fn faces_at_the_limit_are_taken_and_one_past_it_is_refused_before_sampling() { assert_eq!(extrude(&path, FillRule::NonZero, path.bounds().unwrap(), rounded, turned()), Err(SURFACE.to_string())); } +#[test] +fn a_material_keeps_a_rounded_bevel_within_the_face_limit() { + let rounded = Extrude { bevel: Some(Bevel { shape: BevelShape::Rounded, ..Bevel::default() }), ..Extrude::default() }; + // Eight rounded bevel bands and one wall band, with two caps. + let bevel_bands = BevelShape::Rounded.samples().len() - 1; + let bands = bevel_bands + 1; + let caps = 2; + assert_eq!(bands, 9); + let edges = (MAX_SOLID_FACES - caps) / bands; + let faces = edges * bands + caps; + assert!(faces <= MAX_SOLID_FACES && MAX_SOLID_FACES - faces < bands); + assert!(edges * bands * 2 + caps > MAX_SOLID_FACES); + let path = polygon(edges, 20_000.0); + let bounds = path.bounds().unwrap(); + let view = View { shade: true, ..turned() }; + let material_view = View { material: crate::Material::new(0.4, 0.0).unwrap(), ..view }; + let plain = extrude(&path, FillRule::NonZero, bounds, rounded, view); + let material = extrude(&path, FillRule::NonZero, bounds, rounded, material_view); + assert!(plain.is_ok(), "{plain:?}"); + assert!(material.is_ok(), "{material:?}"); + assert!(built(&plain.unwrap())); + assert!(built(&material.unwrap())); +} + +#[test] +fn a_material_splits_rounded_bevel_bands_with_room_below_the_face_limit() { + let path = polygon(256, 20_000.0); + let bounds = path.bounds().unwrap(); + let rounded = Extrude { bevel: Some(Bevel { shape: BevelShape::Rounded, ..Bevel::default() }), ..Extrude::default() }; + let view = View { shade: true, ..turned() }; + let material_view = View { material: crate::Material::new(0.4, 0.0).unwrap(), ..view }; + let plain = extrude(&path, FillRule::NonZero, bounds, rounded, view).unwrap(); + let material = extrude(&path, FillRule::NonZero, bounds, rounded, material_view).unwrap(); + assert!(built(&plain) && built(&material)); + assert!(material.len() > plain.len(), "the material splits smoothed bands into triangles"); +} + #[test] fn curves_over_the_budget_take_fewer_pieces_down_to_four() { let path = petals(2000, 500.0, 20.0); diff --git a/crates/three-d/src/visibility.rs b/crates/three-d/src/visibility.rs index 71c5af62c3..f98d19d668 100644 --- a/crates/three-d/src/visibility.rs +++ b/crates/three-d/src/visibility.rs @@ -26,6 +26,7 @@ pub struct VisibleFace { pub illumination: [f64; 3], pub light_gradient: Option, pub rgb_gradient: Option, + pub highlight: Option, } struct Polygon { @@ -273,6 +274,7 @@ pub fn visible_faces(faces: &[Face]) -> Result, String> { illumination: face.illumination, light_gradient: face.light_gradient, rgb_gradient: face.rgb_gradient, + highlight: face.highlight, }); // A completely covered face need not occupy the grid. Its coverage already belongs // to nearer faces; this keeps repeated overlapping surfaces bounded in practice. @@ -302,6 +304,7 @@ mod tests { illumination: [brightness; 3], light_gradient: None, rgb_gradient: None, + highlight: None, outline: None, cap: false, visibility_pieces: None, diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c1c4bcbfb2..cf3551fc19 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -110,6 +110,8 @@ struct HandlePress { moved: bool, /// The picked handles when the press began. picked: PickedHandles, + /// A mirroring Cmd/Ctrl press on one of several picked handles: they stay picked after its drag. + keeps_picks: bool, } #[derive(Clone, Debug)] @@ -1046,6 +1048,33 @@ impl Tool for DirectSelectionTool { self.lent_cmd = value.as_bool().unwrap_or(false); } } + /// A Cmd/Ctrl press without Alt on the end of a shown direction handle (a path's, type on a + /// path's or a selected blend spine anchor's) stays with Direct Selection, so the drag mirrors + /// the opposite handle ([`DirectSelectionTool::mirrors`]). A press on a handle of the bounding + /// box the lent Selection tool shows still goes to that tool, and so does a press anywhere else, + /// including one that a press of the tool gives to something it checks before the handles (a + /// corner widget, a bracket of type on a path, a gradient mesh point). + fn keeps_cmd_press(&self, cx: &ToolContext, p: Point, mods: Mods) -> bool { + if self.group || mods.alt || crate::select::bbox_handle_at(cx, p) { + return false; + } + let point = cx.point_tol(); + // The order of the checks is the order `pointer` tries them in on a press. + let ev = PointerEvent::new(PointerKind::Down, p.x, p.y).with_mods(mods); + if CornerDrag::hit(cx, &ev, true).is_some_and(|c| !(c.on_unpicked() && c.widget_center().is_some_and(|w| yields_to_point(cx, p, w)))) { + return false; + } + if !over_path_type_anchor(cx, p) && BracketDrag::hit_any(cx, &ev).is_some() { + return false; + } + if self.spine.filter(|(id, _)| cx.selection.contains(*id)).and_then(|sel| hit_spine_handle(cx, sel, p, point)).is_some() { + return true; + } + if self.mesh.hit(cx, &cx.selection.objects, p).is_some() { + return false; + } + hit_handle(cx, p, point).is_some() + } /// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh /// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved /// goes back and the tool waits for the next press (#1743). @@ -1087,13 +1116,16 @@ impl Tool for DirectSelectionTool { self.mesh.cancel(); // The frame anchors or handles a cancelled drag held stay selected. let frame = matches!(self.state, State::TypeArea { .. }) && !self.frame.is_empty(); - let handles = matches!(self.state, State::Handles { .. }); + let kept = self.handle_press.take().filter(|press| press.keeps_picks && matches!(self.state, State::Handle { .. })); + let handles = matches!(self.state, State::Handles { .. }) || kept.is_some(); + if let Some(press) = kept { + self.handles = press.picked; + } self.state = State::Idle; self.guides.clear(); (self.anchor_snap, self.copy_snap, self.move_snap) = (None, None, None); self.last_location = None; (self.click, self.click_segment, self.click_group, self.frame_click) = (None, None, None, None); - self.handle_press = None; match (frame, handles) { (true, _) => vec![Action::Cancel, Action::Notify(FRAME_PICKED.into())], (_, true) => vec![Action::Cancel, Action::Notify(HANDLES_PICKED.into())], @@ -1896,9 +1928,11 @@ impl DirectSelectionTool { self.state = State::Handle { id, si, ai, out, drag: Some(drag) }; vec![Action::Preview("path.setHandle".into(), params)] } - /// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift on one of two or - /// more picked handles (`picks`, as they were before the press), a drag moves them all; any - /// other press drags that handle alone, as before handles could be picked. + /// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift or a mirroring + /// Cmd/Ctrl ([`Self::mirrors`]) on one of two or more picked handles (`picks`, as they were + /// before the press), a drag moves them all; any other press drags that handle alone, as before + /// handles could be picked, so a Cmd/Ctrl drag mirrors its opposite handle. The picked handles + /// stay picked after such a Cmd/Ctrl or Cmd/Ctrl+Shift drag of one of them. fn press_handle( &mut self, cx: &ToolContext, @@ -1931,8 +1965,11 @@ impl DirectSelectionTool { }; let handle = (id, (si, ai, out)); let on = picks.get(&id).is_some_and(|set| set.contains(&handle.1)); - let several = on && !ev.mods.shift && picks.values().map(BTreeSet::len).sum::() > 1; - let begin = if several { + let one_of_several = on && picks.values().map(BTreeSet::len).sum::() > 1; + let among_several = one_of_several && !ev.mods.shift; + // A mirroring drag keeps the picks with Shift held too. + let keeps_picks = one_of_several && self.mirrors(ev); + let begin = if among_several && !keeps_picks { let items = picks.iter().flat_map(|(id, set)| set.iter().map(|h| (*id, *h))).collect(); self.state = State::Handles { handle, from, start: p, items, began: false }; self.handles = picks.clone(); @@ -1942,7 +1979,7 @@ impl DirectSelectionTool { self.state = State::Handle { id, si, ai, out, drag }; vec![Action::Begin("Reshape".into())] }; - self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks }); + self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks, keeps_picks }); begin } /// The release of a press on one of several picked handles: a drag commits, and the picked @@ -1957,10 +1994,18 @@ impl DirectSelectionTool { self.handles = BTreeMap::from([(handle.0, BTreeSet::from([handle.1]))]); vec![Action::Notify(HANDLES_PICKED.into())] } - /// After the release of a press on a handle that did not drag: a click picks the handle alone, - /// and a Shift-click adds it to the picked handles or takes it away. + /// After the release of a press on a handle: a click picks the handle alone, and a Shift-click + /// adds it to the picked handles or takes it away. A mirroring drag of one of several picked + /// handles leaves them all picked. fn pick_clicked_handle(&mut self) -> Option { - let press = self.handle_press.take().filter(|press| !press.moved)?; + let press = self.handle_press.take()?; + if press.moved { + if !press.keeps_picks { + return None; + } + self.handles = press.picked; + return Some(Action::Notify(HANDLES_PICKED.into())); + } let (id, h) = press.handle; let mut picked = if press.shift { press.picked } else { BTreeMap::new() }; let set = picked.entry(id).or_default(); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 5a32145ec0..bee869a8e8 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -6,6 +6,7 @@ //! and journal entry. One-shot `Exec` actions run immediately. This makes every gesture replayable //! by the control channel and MCP, and keeps tools testable without a UI. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; pub mod bbox; @@ -278,6 +279,12 @@ pub trait Tool: Send { fn hover_object(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Option { None } + /// Does a press at `p` with Cmd/Ctrl and `mods` held stay with the tool, instead of going to + /// the selection tool the session lends for Cmd/Ctrl? Direct Selection keeps a press on a shown + /// direction handle, where Cmd/Ctrl mirrors the opposite handle. + fn keeps_cmd_press(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> bool { + false + } /// What the Info panel shows for the tool as it is now: the drag in progress (a move of the /// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear /// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show. diff --git a/crates/trace/src/lib.rs b/crates/trace/src/lib.rs index 7bb59c79b1..02acf76de0 100644 --- a/crates/trace/src/lib.rs +++ b/crates/trace/src/lib.rs @@ -46,6 +46,7 @@ //! it, so each enclosed outline is fitted once. An area that holds a transparent pixel or a color //! left out stays a hole. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod centerline; mod contour; diff --git a/crates/ui-egui/src/addons/cleanup.rs b/crates/ui-egui/src/addons/cleanup.rs index 8ce1aa6812..1b012b66f7 100644 --- a/crates/ui-egui/src/addons/cleanup.rs +++ b/crates/ui-egui/src/addons/cleanup.rs @@ -8,10 +8,11 @@ use craft::behavior::{DisplayOrder, ItemSource, Selection}; use craft::keymap::Mods; use craft::menu::Node; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::display::{Divider, Text}; use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; +use craft::ui::menu::{Menu, MenuItem}; use craft::ui::sections::Section; use egui::Ui; use serde_json::{Value, json}; @@ -136,6 +137,8 @@ pub(crate) struct Results { rows: Vec<(String, String, u64)>, /// The rows picked in the list, by position in `rows`. picked: Selection, + /// The clicked finding and the kinds to fix, captured when its menu opens. + menu: Option<(String, Vec)>, /// What the last fix did. status: String, } @@ -320,14 +323,41 @@ fn text_tools(ui: &mut Ui, selected: bool, editing: bool, action: &mut Option) { let source = Positional { rows: &r.rows, label: |row| row.1.as_str() }; - List::::new(tl!("Issues").to_string()).empty(tl!("No issues found.").to_string()).selection(Bind::bound(&mut r.picked)).show_items( - ui, - &source, - &mut |key, _| match r.rows.get(*key) { - Some((_, label, count)) => ListRow::new(tl!(label).to_string()).trailing(count.to_string()), + let mut selection = r.picked.clone(); + let out = List::::new(tl!("Issues")) + .id(ui.scope_id().with(("cleanup-issues", r.doc))) + .select(SelectMode::Multi) + .row_menu() + .empty(tl!("No issues found.").to_string()) + .selection(Bind::bound(&mut selection)) + .show_items(ui, &source, &mut |key, item| match r.rows.get(*key) { + Some((_, label, count)) => ListRow::new(tl!(label).to_string()).trailing(count.to_string()).state(item.row.clone()), None => ListRow::spacer(), - }, - ); + }); + if let Some(key) = out.events.iter().find_map(|event| match event { + CollectionEvent::ContextMenu(request) => Some(request.key), + _ => None, + }) { + if !r.picked.items.contains(&key) { + r.picked = Selection::single(key); + } + r.menu = r.rows.get(key).map(|row| (row.0.clone(), r.picked_kinds())); + } else { + r.picked = selection; + } + if let Some((kind, kinds)) = &r.menu { + let menu = Menu::context(tl!("Issues"), &out.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Show Affected Artwork")).show(ui).ran { + *action = Some(Action::Show(kind.clone())); + } + if MenuItem::new(tl!("Fix Selected")).show(ui).ran { + *action = Some(Action::Fix(kinds.clone())); + } + }); + if menu.output.closed.is_some() || action.is_some() { + r.menu = None; + } + } if !r.status.is_empty() { Text::new(r.status.clone()).show(ui); } diff --git a/crates/ui-egui/src/addons/cleanup/tests.rs b/crates/ui-egui/src/addons/cleanup/tests.rs index 1b414177fb..072eb5e8fc 100644 --- a/crates/ui-egui/src/addons/cleanup/tests.rs +++ b/crates/ui-egui/src/addons/cleanup/tests.rs @@ -3,6 +3,7 @@ use vectorcraft_engine::Session; use super::{check, current, fix}; use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; /// An app with a rectangle and a stray point (a path of one anchor), nothing selected. fn app() -> VectorcraftApp { @@ -46,3 +47,52 @@ fn a_fix_with_no_results_does_nothing() { assert!(app.addon_panels.cleanup.is_none()); assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "nothing was fixed without a check"); } + +#[test] +fn a_selected_rows_menu_shows_its_own_artwork_and_fixes_the_whole_selection() { + let mut app = app(); + let outside = app.run("shape.rectangle", json!({"x": 500, "y": 500, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + check(&mut app, None); + let mut panel = Panel::new(app, super::show); + panel.click("Off-Artboard Art"); + panel.click_with("Stray Points", egui::Modifiers::SHIFT); + panel.secondary_click("Off-Artboard Art"); + panel.click_menu_item("Show Affected Artwork"); + assert_eq!(panel.app().session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(outside)]); + panel.secondary_click("Off-Artboard Art"); + panel.click_menu_item("Fix Selected"); + assert!(current(&panel.app()).unwrap().rows.is_empty(), "both findings were fixed"); +} + +#[test] +fn opening_the_menu_on_an_unselected_row_fixes_only_that_finding() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 500, "y": 500, "width": 20, "height": 20})).unwrap(); + check(&mut app, Some("document")); + let mut panel = Panel::new(app, super::show); + panel.click("Stray Points"); + panel.secondary_click("Off-Artboard Art"); + panel.click_menu_item("Fix Selected"); + let app = panel.app(); + let remaining = ¤t(&app).unwrap().rows; + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].0, "strayPoints"); +} + +#[test] +fn dismissing_the_keyboard_menu_returns_focus_to_the_finding() { + let mut app = app(); + check(&mut app, None); + let mut panel = Panel::new(app, super::show); + panel.focus("Stray Points"); + panel.key(egui::Key::F10, egui::Modifiers::SHIFT); + panel.frame(); + panel.frame(); + assert!(panel.focused("Show Affected Artwork")); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + panel.frame(); + assert!(panel.focused("Stray Points")); + assert!(!panel.shows("Show Affected Artwork")); +} diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 18816efa11..ecbcf6856d 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -64,7 +64,7 @@ fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> { } /// Closes the open add-on dialog without an answer and rolls its preview back. -fn close_open(app: &mut VectorcraftApp) { +pub(crate) fn close_open(app: &mut VectorcraftApp) { let Some(open) = app.addon_dialogs.open.take() else { return }; app.addon_dialogs.preview_error = None; let id = open.id; @@ -100,8 +100,9 @@ pub(crate) fn open( /// The dialog the menu item of command `id` opens, with no params; `None` for another command. pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option> { - use super::{color, pathtools, select, typetools}; + use super::{color, document, pathtools, select, typetools}; let open: fn(&mut VectorcraftApp) -> Result = match id { + document::FLOOD_FILL => document::open_flood_fill, pathtools::set_corners::COMMAND => pathtools::set_corners::open, pathtools::dashes::COMMAND => pathtools::dashes::open, pathtools::COMMON_TANGENTS => pathtools::tangents::open, diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index 9fcf01e5c2..1e38dcc3d8 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -3,15 +3,20 @@ //! each layer's art replaced by an instance). Save a Timestamped Copy of a document never saved //! asks for the folder to put it in ([`save_copy`]). Export All Open Documents as PDF or SVG asks //! for the folder the copies go in ([`export_all`], #4920). Batch Trace Folder asks for the folder of -//! images and then the folder the results go in ([`batch_trace`], #4921). +//! images and then the folder the results go in ([`batch_trace`], #4921). Flood Fill Artboards… +//! opens a dialog ([`open_flood_fill`]) that previews on the canvas and runs +//! `addon.document.floodFillArtboards` on OK. use craft::host::{PickRequest, Picked}; use craft::menu::Node; +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; +use super::dialogs::Spec; use crate::VectorcraftApp; use crate::file_asks::{Owner, ask}; -use crate::menus::{Sep, cp}; +use crate::menus::{Sep, c, cp}; /// Save a Timestamped Copy. pub const SAVE_COPY: &str = "addon.document.saveTimestampedCopy"; @@ -21,6 +26,14 @@ pub const EXPORT_ALL: &str = "addon.document.exportAllOpen"; pub const BATCH_TRACE: &str = "addon.document.batchTraceFolder"; /// New Symbols from Layers (Convert Layers to Symbols: with their art replaced by instances). const SYMBOLS: &str = "addon.document.symbolsFromLayers"; +/// Flood Fill Artboards. +pub const FLOOD_FILL: &str = "addon.document.floodFillArtboards"; +/// The layer Flood Fill Artboards puts its rectangles on unless another is named. +const FLOOD_LAYER: &str = "Flood Fill"; +/// The color the Flood Fill Artboards dialog opens with when the current fill is not a solid color. +const GRAY: [f32; 3] = [0.5, 0.5, 0.5]; + +static FLOOD_SPEC: Spec = Spec { command: FLOOD_FILL, params: flood_params, found: None }; /// Object › Plug-ins › Document Tools. pub fn menu() -> Vec { @@ -32,9 +45,123 @@ pub fn menu() -> Vec { Sep, cp("New Symbols from Layers", SYMBOLS, json!({})), cp("Convert Layers to Symbols", SYMBOLS, json!({ "replace": true })), + Sep, + c("Flood Fill Artboards…", FLOOD_FILL), ] } +/// The rows of the Flood Fill Artboards dialog. +fn flood_rows() -> Vec { + vec![ + Param::new( + "artboards", + tl!("Artboards:"), + ParamKind::choice( + vec![("active".into(), tl!("Active Artboard").into()), ("all".into(), tl!("All Artboards").into())], + Some("active".into()), + ), + ), + Param::new( + "fill", + tl!("Fill:"), + ParamKind::choice(vec![("current".into(), tl!("Current Fill").into()), ("color".into(), tl!("Color").into())], Some("current".into())), + ), + Param::new("color", tl!("Color:"), ParamKind::color(Some(GRAY))).enabled_when("fill", "color"), + Param::new("layer", tl!("Layer:"), ParamKind::text(FLOOD_LAYER)), + ] +} + +/// The working-RGB components `[r, g, b]` of the dialog's display sRGB color, as the engine reads a +/// color array. +fn working_rgb(srgb: [f32; 3]) -> Value { + let [r, g, b] = vectorcraft_color::cms::active().srgb_to_rgb(srgb.map(|v| v.clamp(0.0, 1.0))); + json!([r, g, b]) +} + +/// Flood Fill Artboards' params from the dialog: every artboard or the one the dialog opened on (`board`, kept +/// out of sight), the color only when Color is picked (in the document's working RGB), and the layer named. +fn flood_params(fields: &DialogFields) -> Value { + let mut p = match fields.text("artboards") { + Some("all") => json!({ "all": true }), + _ => json!({ "activeArtboard": fields.int("board").unwrap_or(0) }), + }; + if fields.text("fill") == Some("color") { + let picked = fields.color("color").unwrap_or(GRAY); + // The opening fill, while its shown color is unchanged, keeps its own working components, also + // those outside the displayable sRGB range, and stays RGB in a CMYK document. + let start = (fields.color("startShown") == Some(picked)) + .then(|| fields.text("startColor").and_then(|t| serde_json::from_str::(t).ok())) + .flatten(); + match start { + Some(start) => { + p["color"] = start; + p["keepModel"] = json!(true); + } + None => p["color"] = working_rgb(picked), + } + } + p["layer"] = json!(fields.text("layer").unwrap_or(FLOOD_LAYER)); + p +} + +/// Opens Flood Fill Artboards' dialog on the active artboard and the current fill, or, when there is no fill, on +/// Color with gray. +pub(crate) fn open_flood_fill(app: &mut VectorcraftApp) -> Result { + let command = vectorcraft_engine::find_command(FLOOD_FILL).ok_or_else(|| format!("unknown command {FLOOD_FILL}"))?; + (command.enabled)(&app.session)?; + // A reopened dialog reads the fill after the open dialog's preview is rolled back, not the previewed fill. + super::dialogs::close_open(app); + let board = app.view().map_or(0, |v| v.artboard); + let fill = &app.session.paint.fill; + let no_current_fill = fill.is_none(); + let color = fill.color().map_or(GRAY, |c| c.to_rgb().map(|v| v.clamp(0.0, 1.0))); + // An RGB opening fill's working components, unclamped, sent when Color keeps the shown color. + let start_color = fill + .color() + .and_then(|c| match c { + vectorcraft_color::Color::Rgb { r, g, b } => Some([r, g, b]), + _ => None, + }) + .filter(|rgb| rgb.iter().all(|v| v.is_finite())) + .map_or_else(String::new, |rgb| json!(rgb).to_string()); + let fields = DialogFields::from_pairs([ + ("artboards", FieldValue::Text("active".into())), + ("fill", FieldValue::Text(if fill.is_none() { "color" } else { "current" }.into())), + ("color", FieldValue::Color(color)), + ("layer", FieldValue::Text(FLOOD_LAYER.into())), + ("board", FieldValue::Int(board as i64)), + ("startShown", FieldValue::Color(color)), + ("startColor", FieldValue::Text(start_color)), + ]); + let mut layer_clips = std::collections::HashMap::new(); + if let Ok(st) = app.session.doc() { + for layer in st.doc.layers.iter().filter(|layer| layer.is_layer()) { + if let Some(name) = &layer.name { + layer_clips.entry(name.clone()).or_insert_with(|| layer.clips()); + } + } + } + super::dialogs::open(app, &FLOOD_SPEC, fields, move |fields| { + let name = fields.text("layer").unwrap_or_default().trim(); + let reason = if name.is_empty() { + Some(tl!("Name the layer.")) + } else if name.chars().count() > 255 { + Some(tl!("Use at most 255 characters for the layer name.")) + } else if layer_clips.get(name) == Some(&true) { + Some(tl!("The layer holds a clipping mask.")) + } else if no_current_fill && fields.text("fill") == Some("current") { + Some(tl!("There is no current fill.")) + } else { + None + }; + ParamDialog::new(FLOOD_FILL, tl!("Flood Fill Artboards"), flood_rows()) + .ok_enabled(reason.is_none()) + .ok_reason(reason.unwrap_or_default().into()) + .values(Bind::bound(fields)) + .previews(true) + }) +} + /// The params as an object, with the picked folder under `key`. fn with_folder(p: &Value, key: &str, picked: &Picked) -> Result { let folder = picked.first_path().ok_or("no folder picked")?; diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 1cc56d18cb..fc77f7a4ab 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -4,6 +4,8 @@ use serde_json::json; use vectorcraft_engine::Session; use super::{BATCH_TRACE, EXPORT_ALL, SAVE_COPY}; +use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel as Harness; use crate::tests::picks::{poll, scripted}; use crate::{VectorcraftApp, menus}; use craft::host::PickKind; @@ -237,3 +239,293 @@ fn batch_trace_folder_asks_for_both_folders() { assert_eq!(picker.requests().len(), asked + 1, "declining the source asks nothing more"); let _ = std::fs::remove_dir_all(&dir); } + +/// A window, a document of three 100 × 80 artboards with the second active, and a red fill. +fn boards() -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 80, "artboards": 3})).unwrap(); + app.sync_views(); + if let Some(v) = app.view_mut() { + v.artboard = 1; + } + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app +} + +/// The names of the document's top-level layers, bottom first. +fn layer_names(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect() +} + +/// The bounds and fill of each object on the bottom layer. +fn bottom_art(app: &VectorcraftApp) -> Vec<(vectorcraft_geom::Rect, vectorcraft_color::Paint)> { + let doc = &app.session.doc().unwrap().doc; + let art = doc.layers[0].children().map(|c| c.to_vec()).unwrap_or_default(); + art.iter().map(|n| (n.geometric_bounds().unwrap(), n.appearance.fill_paint())).collect() +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +#[test] +fn flood_fill_typed_layer_name_previews_and_ok_applies_one_step() { + let app = boards(); + let undo = undo_len(&app); + let artboard = app.session.doc().unwrap().doc.artboards[1].rect; + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Flood Fill Artboards…"); + panel.frame(); + panel.click("Layer"); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("Paper"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#ff0000").unwrap()); + { + let app = panel.app(); + assert_eq!(layer_names(&app)[0], "Paper", "the preview makes the typed layer at the bottom"); + assert_eq!(bottom_art(&app), [(artboard, red.clone())], "the active artboard, in the current fill"); + assert_eq!(undo_len(&app), undo, "the preview is still temporary"); + } + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app), ["Paper", "Layer 1"]); + assert_eq!(bottom_art(&app), [(artboard, red)]); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + assert_eq!(app.session.doc().unwrap().history.undo.last().unwrap().label, "Flood Fill Artboards"); +} + +#[test] +fn flood_fill_active_artboard_records_a_relative_action_target() { + let mut app = boards(); + let start = app.session.journal.len(); + let opening_board = app.session.doc().unwrap().doc.artboards[1].rect; + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + let params = host::read(&app, id, super::flood_params); + assert_eq!(params["activeArtboard"], json!(1)); + assert!(params.get("artboards").is_none()); + app.view_mut().unwrap().artboard = 2; + host::set(&app, id, "layer", json!("Paper")); + host::frame(&mut app); + assert_eq!(bottom_art(&app)[0].0, opening_board); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(bottom_art(&app)[0].0, opening_board); + let journal = app.session.journal.since(start); + let (_, params) = journal.iter().find(|(cmd, _)| cmd == super::FLOOD_FILL).unwrap(); + assert_eq!(params["activeArtboard"], json!(1)); + let steps = app.session.journal_for_action(start); + let (command, params) = steps.iter().find(|(cmd, _)| cmd == super::FLOOD_FILL).unwrap(); + assert!(params.get("activeArtboard").is_none()); + assert!(params.get("artboards").is_none()); + app.run("file.new", json!({"width": 60, "height": 40})).unwrap(); + app.sync_views(); + let playback_board = app.session.doc().unwrap().doc.artboards[0].rect; + app.run(command, params.clone()).unwrap(); + assert_eq!(bottom_art(&app)[0].0, playback_board); +} + +#[test] +fn flood_fill_cancel_rolls_the_preview_back() { + let app = boards(); + let (undo, doc) = (undo_len(&app), app.session.doc().unwrap().doc.clone()); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Flood Fill Artboards…"); + panel.frame(); + assert_eq!(layer_names(&panel.app())[0], "Flood Fill", "previewed"); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!((*app.session.doc().unwrap().doc == *doc, undo_len(&app)), (true, undo), "nothing kept"); +} + +#[test] +fn flood_fill_all_artboards_in_a_chosen_color() { + let srgb = std::sync::Arc::new(vectorcraft_color::cms::Cms::new(&Default::default()).unwrap()); + vectorcraft_color::cms::with_active(srgb, || { + let mut app = boards(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "artboards", json!("all")); + assert_eq!(host::read(&app, id, |f| f.color("color")), Some([1.0, 0.0, 0.0]), "Color opens on the current fill's color"); + host::set(&app, id, "fill", json!("color")); + host::set(&app, id, "color", json!([0.0, 0.0, 1.0])); + let params = host::read(&app, id, super::flood_params); + assert_eq!(params, json!({"all": true, "color": [0.0, 0.0, 1.0], "layer": "Flood Fill"})); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let blue = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#0000ff").unwrap()); + let artboards: Vec<_> = app.session.doc().unwrap().doc.artboards.iter().map(|a| (a.rect, blue.clone())).collect(); + assert_eq!(bottom_art(&app), artboards, "one rectangle per artboard, in the dialog's color"); + }); +} + +/// In a working RGB space other than sRGB, switching from Current Fill to Color without editing the +/// color fills the artboards in the current fill's color. +#[test] +fn flood_fill_color_keeps_the_current_fill_in_a_non_srgb_working_space() { + use vectorcraft_color::{Color, cms}; + let settings = cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }; + let wide = std::sync::Arc::new(cms::Cms::new(&settings).unwrap()); + cms::with_active(wide, || { + assert!(!cms::active().rgb_is_srgb()); + let mut app = boards(); + app.run("paint.setFill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "fill", json!("color")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let art = bottom_art(&app); + assert_eq!(art.len(), 1); + let Some(Color::Rgb { r, g, b }) = art[0].1.color() else { panic!("an RGB fill: {:?}", art[0].1) }; + for (got, want) in [(r, 0.6), (g, 0.5), (b, 0.4)] { + assert!((got - want).abs() < 1e-3, "{:?} is the current fill [0.6, 0.5, 0.4]", [r, g, b]); + } + }); +} + +/// A current fill outside the sRGB gamut, whose shown color does not convert back to it, keeps its +/// working components when Color is picked without editing the color. +#[test] +fn flood_fill_color_keeps_an_out_of_srgb_current_fill() { + use vectorcraft_color::cms; + let settings = cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }; + let wide = std::sync::Arc::new(cms::Cms::new(&settings).unwrap()); + cms::with_active(wide, || { + let shown = vectorcraft_color::Color::rgb(0.0, 1.0, 0.0).to_rgb(); + assert_ne!(super::working_rgb(shown), json!([0.0, 1.0, 0.0]), "{shown:?} does not convert back to the fill"); + let mut app = boards(); + app.run("paint.setFill", json!({"color": [0.0, 1.0, 0.0]})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "fill", json!("color")); + let params = host::read(&app, id, super::flood_params); + assert_eq!(params["color"], json!([0.0, 1.0, 0.0])); + }); +} + +/// In a CMYK document, an RGB current fill kept by picking Color without editing it stays RGB. +#[test] +fn flood_fill_color_keeps_an_rgb_current_fill_in_a_cmyk_document() { + use vectorcraft_color::Color; + let mut app = boards(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + app.run("paint.setFill", json!({"color": [0.6, 0.5, 0.4], "keepModel": true})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "fill", json!("color")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let art = bottom_art(&app); + assert_eq!(art.len(), 1); + let Some(Color::Rgb { r, g, b }) = art[0].1.color() else { panic!("an RGB fill: {:?}", art[0].1) }; + for (got, want) in [(r, 0.6), (g, 0.5), (b, 0.4)] { + assert!((got - want).abs() < 1e-3, "{:?} is the current fill [0.6, 0.5, 0.4]", [r, g, b]); + } +} + +#[test] +fn flood_fill_layer_name_limit_counts_characters_after_trimming() { + let mut app = boards(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "layer", json!("é".repeat(256))); + assert!(!host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.any_dialog_open()); + let name = "é".repeat(255); + host::set(&app, id, "layer", json!(format!(" {name} "))); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app)[0], name); +} + +#[test] +fn flood_fill_rejects_a_layer_with_a_clipping_mask_and_keeps_the_dialog_open() { + let mut app = boards(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let layer = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.clippingMask.toggle", json!({"id": layer.0})).unwrap(); + assert!(app.session.doc().unwrap().doc.node(layer).unwrap().clips()); + let name = app.session.doc().unwrap().doc.node(layer).unwrap().name.clone().unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "layer", json!(format!(" {name} "))); + assert!(!host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.any_dialog_open()); + assert_eq!(host::read(&app, id, |f| f.text("layer").map(str::to_owned)), Some(format!(" {name} "))); + host::set(&app, id, "layer", json!("Paper")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app)[0], "Paper"); +} + +#[test] +fn flood_fill_current_fill_without_a_fill_keeps_the_dialog_open() { + let mut app = boards(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + let before = app.session.doc().unwrap().history.undo.len(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "layer", json!("Paper")); + host::set(&app, id, "fill", json!("current")); + assert!(!host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.any_dialog_open()); + assert_eq!(host::read(&app, id, |f| f.text("layer").map(str::to_owned)), Some("Paper".to_owned())); + assert_eq!(app.session.doc().unwrap().history.undo.len(), before); + host::set(&app, id, "fill", json!("color")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app)[0], "Paper"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), before + 1); +} + +#[test] +fn flood_fill_menu_dialog_is_refused_without_a_document() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + assert!(app.run("ui.menuDialog", json!({"command": super::FLOOD_FILL})).is_err(), "the command is off without a document"); + assert!(!app.any_dialog_open()); +} + +/// With New Art Has Basic Appearance off and no fill, reopening the dialog while a Color preview is +/// showing opens it on the fill from before the preview, not on the previewed rectangles' fill. +#[test] +fn flood_fill_reopened_during_a_color_preview_reads_the_fill_before_it() { + let mut app = boards(); + app.run("appearance.setNewArtBasic", json!({"on": false})).unwrap(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + app.run("ui.menuDialog", json!({"command": super::FLOOD_FILL})).unwrap(); + let id = host::dialog_id(&app); + host::set(&app, id, "color", json!([0.0, 0.0, 1.0])); + host::frame(&mut app); + assert_eq!(layer_names(&app)[0], "Flood Fill", "previewed"); + app.run("ui.menuDialog", json!({"command": super::FLOOD_FILL})).unwrap(); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| f.text("fill").map(str::to_owned)), Some("color".to_owned())); +} + +#[test] +fn flood_fill_opens_on_color_without_a_fill_and_needs_a_layer_name() { + let mut app = boards(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| f.text("fill").map(str::to_owned)), Some("color".to_owned())); + host::set(&app, id, "layer", json!(" ")); + assert!(!host::confirm(&app, id), "OK is off without a layer name"); + host::set(&app, id, "layer", json!("Back")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(layer_names(&app)[0], "Back"); +} diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index a6aa04dfc7..7a0de94cb4 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -23,7 +23,7 @@ use craft::ui::display::{Divider, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Row as Line; use craft::ui::list::{Finding, Findings, FindingsList, FindingsWords, List, ListRow, Severity, ThumbSize}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::runtime::env::UnitKind; use craft::ui::text::NumberField; @@ -149,6 +149,8 @@ fn doc_key(app: &VectorcraftApp) -> Option { pub(crate) struct FoldLines { /// The last check of each document. checks: Checks, + /// The immutable check and row on which the context menu opened. + menu: Option<(Weak, usize)>, /// The role rows for the document state they were read for. rows: Rows, } @@ -210,22 +212,45 @@ fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } - let Some(checked) = last_check(app) else { return }; + let Some(checked) = last_check(app) else { + app.addon_panels.fold.menu = None; + return; + }; Text::new(crate::i18n::msg(&checked.summary())).show(ui); let findings: Vec = (0u64..) .zip(&checked.issues) .map(|(id, issue)| Finding::new(id, if issue.error { Severity::Error } else { Severity::Warning }, crate::i18n::msg(&issue.message))) .collect(); - let out = - FindingsList::new(tl!("Issues").to_string()).show_items(ui, &Findings::new(&findings), &mut |key, icx| match findings.get(*key as usize) { - Some(finding) => finding.row(&icx.words::()), - None => ListRow::spacer(), - }); - for event in &out.events { - if let CollectionEvent::Activate(n) = event { - select_issue(app, &checked, *n as usize); + let list = FindingsList::new(tl!("Issues").to_string()).id(ui.scope_id().with(("fold-issues", Arc::as_ptr(&checked)))); + let out = list.show_items(ui, &Findings::new(&findings), &mut |key, icx| match findings.get(*key as usize) { + Some(finding) => finding.row(&icx.words::()).row_menu(), + None => ListRow::spacer(), + }); + for event in out.events { + match event { + CollectionEvent::Activate(n) => select_issue(app, &checked, n as usize), + CollectionEvent::ContextMenu(request) => app.addon_panels.fold.menu = Some((Arc::downgrade(&checked), request.key as usize)), + _ => {} } } + let Some((owner, n)) = &app.addon_panels.fold.menu else { return }; + let n = *n; + let Some(issue) = checked.issues.get(n).filter(|_| owner.as_ptr() == Arc::as_ptr(&checked)) else { + app.addon_panels.fold.menu = None; + return; + }; + let shown = Menu::context(tl!("Issues"), &out.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Select Affected Objects")).enabled(!issue.ids.is_empty()).show(ui).ran { + select_issue(app, &checked, n); + } + if MenuItem::new(tl!("Copy Finding")).show(ui).ran { + app.clipboard_out = Some(crate::i18n::msg(&issue.message)); + app.status(tl!("Copied finding")); + } + }); + if shown.output.closed.is_some() { + app.addon_panels.fold.menu = None; + } } /// One role row: (role id, swatch name, the swatch's paint if the document has it, count). @@ -346,6 +371,7 @@ fn role_label(role: &str) -> &str { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(selected) = app.session.active().map(|st| !st.selection.is_empty()) else { + app.addon_panels.fold.menu = None; empty_state(ui, "scissors", tl!("No document"), tl!("Open a document to mark its fold lines.")); return; }; diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 26d9ac729b..ea89dcd928 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -116,6 +116,58 @@ fn each_document_keeps_its_own_check() { assert!(last_check(&app).is_some_and(|kept| Arc::ptr_eq(&kept, &second))); } +#[test] +fn a_finding_menu_selects_its_objects_and_restores_keyboard_focus_on_escape() { + let (mut app, slit) = blank(); + let checked = run_check(&mut app, json!({})).unwrap(); + let row = format!("{}, Error", checked.issues[0].message); + let mut panel = Panel::new(app, super::show_check); + panel.focus(&row); + panel.key(Key::F10, Modifiers::SHIFT); + panel.frame(); + panel.frame(); + assert!(panel.focused("Select Affected Objects")); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + panel.frame(); + assert!(panel.focused(&row)); + panel.secondary_click(&row); + panel.frame(); + panel.click_menu_item("Select Affected Objects"); + assert_eq!(panel.app().session.active().unwrap().selection.objects, [vectorcraft_doc::NodeId(slit)]); +} + +#[test] +fn a_recheck_and_a_document_switch_dismiss_the_menu_and_an_objectless_finding_can_be_copied() { + let (mut app, a, _) = app(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let checked = run_check(&mut app, json!({})).unwrap(); + let row = format!("{}, Error", checked.issues[0].message); + let mut panel = Panel::new(app, super::show_check); + panel.secondary_click(&row); + panel.frame(); + assert!(!panel.menu_item_enabled("Select Affected Objects")); + panel.click_menu_item("Copy Finding"); + assert_eq!(panel.app().clipboard_out.as_deref(), Some(checked.issues[0].message.as_str())); + assert_eq!(panel.app().session.active().unwrap().selection.objects, [vectorcraft_doc::NodeId(a)]); + + panel.secondary_click(&row); + panel.frame(); + assert!(panel.shows("Copy Finding")); + let replacement = run_check(&mut panel.app(), json!({"ids": [a]})).unwrap(); + panel.frame(); + assert!(!panel.shows("Copy Finding")); + assert!(!panel.shows("Select Affected Objects")); + panel.secondary_click(&format!("{}, Error", replacement.issues[0].message)); + panel.frame(); + assert!(panel.shows("Copy Finding")); + panel.app().run("file.new", json!({"width": 100, "height": 100})).unwrap(); + run_check(&mut panel.app(), json!({})).unwrap(); + panel.frame(); + assert!(!panel.shows("Copy Finding")); + assert!(!panel.shows("Select Affected Objects")); +} + /// The messages `addon.packaging.check` gives its issues, one for each code (three for `noCut`). const ISSUE_MESSAGES: [&str; 17] = [ "No cut lines are in the selection.", diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs index 65fed545ca..5e25b913c9 100644 --- a/crates/ui-egui/src/addons/shapes.rs +++ b/crates/ui-egui/src/addons/shapes.rs @@ -25,6 +25,7 @@ use crate::VectorcraftApp; use crate::canvas::rulers::general_lengths; use crate::chrome::rank; use crate::edits::{self, EditPath}; +use crate::icons::ToolIcons; use crate::menus::cp; use crate::panels::{Live, live_run}; @@ -51,9 +52,10 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { divider(ui); if tool == "box3d" { + let tools = ToolIcons::of(&app.session.prefs); let shapes: [Choice; 6] = [("box3d", "3D Box"), ("rectangle", "Rectangle"), ("ellipse", "Ellipse"), ("polygon", "Polygon"), ("star", "Star"), ("spiral", "Spiral")] - .map(|(id, label)| (id, label, icon_for_shape(id))); + .map(|(id, label)| (id, label, icon_for_shape(id, tools))); if let Some(shape) = choice(ui, "Shape", &active_shape, &shapes) { app.run("tool.setOption", json!({ "key": "shape", "value": shape })).ok(); } @@ -408,7 +410,8 @@ fn draw_polygon_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, ac end_deg = a1; mode = mode_str(arc_mode); } - let kinds: [Choice; 2] = [("polygon", "Polygon", icon_for_shape("polygon")), ("star", "Star", icon_for_shape("star"))]; + let tools = ToolIcons::of(&app.session.prefs); + let kinds: [Choice; 2] = [("polygon", "Polygon", icon_for_shape("polygon", tools)), ("star", "Star", icon_for_shape("star", tools))]; match choice(ui, "Shape", if is_star { "star" } else { "polygon" }, &kinds) { Some("star") => apply_shape(app, &[("polyIsStar", json!(true))], json!({ "isStar": true, "spokeRatio": spoke })), Some(_) => apply_shape(app, &[("polyIsStar", json!(false))], json!({ "isStar": false })), @@ -508,9 +511,10 @@ fn draw_box3d_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, sele } } -/// The toolbar icon of the shape tool `id`, so the Control bar's shape buttons show the same icon. -fn icon_for_shape(id: &str) -> &'static str { - vectorcraft_tools::tool_info(id).map_or("square-dashed", |t| crate::icons::tool_icon(t.icon)) +/// The toolbar icon of the shape tool `id` in the set `tools` (Tool Icons), so the Control bar's shape buttons show the +/// same icon. +fn icon_for_shape(id: &str, tools: ToolIcons) -> &'static str { + vectorcraft_tools::tool_info(id).map_or("square-dashed", |t| tools.tool_icon(t.icon)) } fn mode_str(m: EllipseMode) -> &'static str { @@ -711,18 +715,24 @@ mod tests { use craft::behavior::IconId; use craft::ui::primitives::has_icon; - use super::icon_for_shape; + use super::{ToolIcons, icon_for_shape}; /// The Control bar's shape buttons look their icons up by tool id; an id that names no tool - /// would show the placeholder instead of the toolbar's icon. + /// would show the placeholder instead of the toolbar's icon. In each Tool Icons set they show + /// the toolbar's icon of that set. #[test] fn every_shape_button_shows_its_tools_icon() { crate::icons::register(); - for id in ["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"] { - let tool = vectorcraft_tools::tool_info(id).unwrap_or_else(|| panic!("{id} is a tool")); - assert_eq!(icon_for_shape(id), crate::icons::tool_icon(tool.icon), "{id}"); - assert!(has_icon(&IconId::new(icon_for_shape(id))), "{id}'s icon {} isn't an icon", icon_for_shape(id)); + craft::ui::primitives::register_app_icons(&crate::icons::CLASSIC_ICONS); + for set in [ToolIcons::Current, ToolIcons::Classic] { + for id in ["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"] { + let tool = vectorcraft_tools::tool_info(id).unwrap_or_else(|| panic!("{id} is a tool")); + let icon = icon_for_shape(id, set); + assert_eq!(icon, set.tool_icon(tool.icon), "{id} in {set:?}"); + assert!(has_icon(&IconId::new(icon)), "{id}'s icon {icon} in {set:?} isn't an icon"); + } + assert_eq!(icon_for_shape("no-such-tool", set), "square-dashed"); } - assert_eq!(icon_for_shape("no-such-tool"), "square-dashed"); + assert_ne!(icon_for_shape("spiral", ToolIcons::Classic), icon_for_shape("spiral", ToolIcons::Current)); } } diff --git a/crates/ui-egui/src/addons/typetools/numbers.rs b/crates/ui-egui/src/addons/typetools/numbers.rs index 68351ad068..250e6788a6 100644 --- a/crates/ui-egui/src/addons/typetools/numbers.rs +++ b/crates/ui-egui/src/addons/typetools/numbers.rs @@ -84,7 +84,9 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { Param::section(tl!("Zeros")), Param::new("leadingZeros", tl!("Leading Zeros"), ParamKind::bool(true)), Param::new("fixedDigits", tl!("Fixed Number of Digits"), ParamKind::bool(false)).enabled_when("leadingZeros", FieldValue::Bool(true)), - Param::new("digits", tl!("Digits:"), ParamKind::int(Some(1), Some(30), 3)).enabled_when("fixedDigits", FieldValue::Bool(true)), + Param::new("digits", tl!("Digits:"), ParamKind::int(Some(1), Some(30), 3)) + .enabled_when("fixedDigits", FieldValue::Bool(true)) + .and_enabled_when_in("leadingZeros", [FieldValue::Bool(true)]), Param::new("trailingZeros", tl!("Trailing Zeros"), ParamKind::bool(false)), Param::new("order", tl!("Order:"), radio(&ORDERS)).enabled_when("shuffle", FieldValue::Bool(false)), Param::new("replace", tl!("Replace:"), radio(&REPLACES)), diff --git a/crates/ui-egui/src/addons/typetools/numbers/tests.rs b/crates/ui-egui/src/addons/typetools/numbers/tests.rs index 79acbf8ef1..bb9f3bcfca 100644 --- a/crates/ui-egui/src/addons/typetools/numbers/tests.rs +++ b/crates/ui-egui/src/addons/typetools/numbers/tests.rs @@ -25,6 +25,24 @@ fn texts(app: &VectorcraftApp, ids: &[u64]) -> Vec { .collect() } +/// Digits takes input only while Leading Zeros and Fixed Number of Digits are both on, since the +/// command gets `digits` only then. +#[test] +fn digits_takes_input_only_with_leading_zeros() { + let (app, _) = app(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + open_item(&mut panel.app(), "Type Tools", "Make Numbers Sequence…"); + panel.frame(); + let dialog = dialog_id(&panel.app()); + set(&panel.app(), dialog, "fixedDigits", json!(true)); + panel.frame(); + assert!(panel.enabled("Digits")); + set(&panel.app(), dialog, "leadingZeros", json!(false)); + panel.frame(); + assert!(read(&panel.app(), dialog, super::params).get("digits").is_none()); + assert!(!panel.enabled("Digits"), "with Leading Zeros off the command gets no digits"); +} + /// The dialog's fields reach the command: an end and fixed digits only when turned on, and OK /// numbers the objects as one undo step. #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b87001e4b5..0448534fda 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -11,7 +11,7 @@ use craft::ui::docking::IconGroupSeparator; use craft::ui::list::{CommandHighlight, ThumbRows}; use craft::ui::menu::{MenuTitleLook, MenuTitlePad}; use craft::ui::patterns::form_dialogs::PresetCardLook; -use craft::ui::runtime::env::{RootEnv, Scale, ScrubDrags, WindowKey}; +use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey}; use craft::ui::runtime::frame::{FrameInput, FrameOutput}; use craft::ui::runtime::toast::{self, Toast}; use craft::ui::runtime::windows::WindowHost; @@ -61,6 +61,12 @@ fn now_secs() -> f64 { monotonic_ms() / 1000.0 } +#[cfg(test)] +std::thread_local! { + /// The notices [`VectorcraftApp::deliver_plugin_events`] took on this thread. + static TAKEN_EVENT_NOTICES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + impl VectorcraftApp { /// The app around `session`, reaching the platform through `services` (the clipboard, files /// and the like). It registers the app's icon sets, starts cataloguing the installed fonts at @@ -68,6 +74,7 @@ impl VectorcraftApp { pub fn new(mut session: Session, mut services: Services) -> Self { // Every entry point (desktop, web, tests) makes the app before its first pass. super::icons::register(); + craft::ui::primitives::register_app_icons(&super::icons::CLASSIC_ICONS); craft::ui::primitives::register_app_icons(&super::cursors::CURSOR_ICONS); // The font menus and the first file opened need the installed fonts: catalog them now. vectorcraft_text::FontDb::global().scan_in_background(); @@ -79,6 +86,9 @@ impl VectorcraftApp { session.place_cursor_requests = true; // A script runs a slice per frame, so the window keeps drawing and Stop can be pressed. session.script_frames = true; + // Plug-in events are delivered by the frame: after the work that finished in the + // background, and at the end of the UI pass ([`VectorcraftApp::deliver_plugin_events`]). + session.plugin_event_frames = true; let views = session.documents().iter().map(View::of).collect(); let view_uids = session.documents().iter().map(|d| d.uid).collect(); let known = session.documents().iter().map(|d| d.uid).collect(); @@ -139,6 +149,7 @@ impl VectorcraftApp { spelling: Default::default(), text_nodes: Default::default(), momentary: None, + momentary_keys: vec![], hand: None, zoom_tool: None, selection_box: None, @@ -158,6 +169,8 @@ impl VectorcraftApp { carry_target: None, last_drag: None, escaped_press: false, + pressed_at: None, + keys_at: None, host_caps_lock: None, committed_preview: false, panes: Default::default(), @@ -194,6 +207,7 @@ impl VectorcraftApp { titlebar_inset: 0.0, last_effect: None, last_pathfinder: None, + queued_script_printers: None, last_filters: Default::default(), character_focus: None, run_count: 0, @@ -361,10 +375,11 @@ impl VectorcraftApp { /// Applies the work that finished off the UI thread. It stays pending while a script runs, since /// every change to the documents ends in a busy error until the script ends. Plug-in worker runs /// are still read then, so Cancel and their time budgets still end them ([`plugin_runs::poll`]). - pub(crate) fn poll_finished_work(&mut self) { + /// Returns whether plug-in event delivery needs a repaint. + pub(crate) fn poll_finished_work(&mut self) -> bool { if self.session.script_running() { plugin_runs::poll(self); - return; + return false; } background::poll(self); opening::poll(self); @@ -372,6 +387,46 @@ impl VectorcraftApp { trace_runs::poll(self); placing::poll(self); retype_runs::poll(self); + // The handlers' time counts toward the frame-time sample, as the delivery after the UI + // pass does. + let t0 = monotonic_ms(); + let pending = self.deliver_plugin_events(); + self.perf.early_events_ms += monotonic_ms() - t0; + pending + } + + /// The plug-in event notices this thread's apps took, for tests that check a handler ran in a + /// pass ([`Self::deliver_plugin_events`] takes them from the session). + #[cfg(test)] + pub(crate) fn take_event_notices_taken() -> Vec { + TAKEN_EVENT_NOTICES.with(|taken| std::mem::take(&mut *taken.borrow_mut())) + } + + /// Hands the plug-ins that react to events the changes of this frame + /// ([`vectorcraft_engine::Session::deliver_plugin_events`]). The last warning or error a handler + /// wrote, or the last handler failure, shows in the status bar after the plug-in's name. + /// Returns whether the status bar changed or runnable handlers remain queued. + fn deliver_plugin_events(&mut self) -> bool { + let pending = self.session.deliver_plugin_events(); + let notices = self.session.take_plugin_event_notices(); + #[cfg(test)] + TAKEN_EVENT_NOTICES.with(|taken| taken.borrow_mut().extend(notices.iter().cloned())); + let shown = notices.into_iter().rev().find(|n| matches!(n.level, vectorcraft_plugins::LogLevel::Error | vectorcraft_plugins::LogLevel::Warn)); + let Some(mut n) = shown else { return pending }; + let name = vectorcraft_plugins::permissions::display_text(&n.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + // The status is kept in English and translated when the status bar shows it, with the + // plug-in's name kept as it is; a line the handler wrote is kept whole. + let status = format!("{name}: {}", n.text); + self.status(status.clone()); + if n.failure.is_some() { + n.name = name; + self.ui.status_plugin_event = Some((status, n)); + self.ui.status_kept = None; + } else { + self.ui.status_plugin_event = None; + self.ui.status_kept = Some((String::new(), status, String::new())); + } + true } /// The language the UI is drawn in: the Preferences window's choice while it is open (so a @@ -466,6 +521,10 @@ impl VectorcraftApp { /// [`Self::tick`]'s work. fn tick_frame(&mut self, ctx: &egui::Context) { self.ticked_pass = Some(ctx.cumulative_pass_nr()); + if ctx.current_pass_index() == 0 { + self.perf.early_events_ms = 0.0; + self.session.begin_plugin_event_frame(); + } let lang = self.ui_language(); i18n::set_current(lang); // The engine gives new type the Japanese defaults while the UI is in Japanese. @@ -514,23 +573,37 @@ impl VectorcraftApp { // them, even if the worker below finishes them during this same tick. ctx.data_mut(|d| d.insert_temp(egui::Id::unique("clipboard.pending-at-tick"), self.clipboard_publishing.is_pending())); screen_color::tick(self, ctx); + let script_was_running = self.session.script_running(); // Once a frame: work that finishes during a frame's first pass is applied in the next frame, not in a second // pass of this one. - if ctx.current_pass_index() == 0 { - self.poll_finished_work(); + if ctx.current_pass_index() == 0 && self.poll_finished_work() { + ctx.request_repaint(); } crate::script_runs::poll(self); + // Apply the work that waited for the script in the frame it ended in. + if script_was_running && !self.session.script_running() && self.poll_finished_work() { + ctx.request_repaint(); + } // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); + // A palette event whose run starts on the next frame. While a run goes on, the block below + // asks for its frames, and a run that waits for the person goes on at their next input. An + // event that waits for an open undo group asks for no frame; the pass that ends the group + // asks for the next one (`ui_frame`). + if crate::script_palettes::can_start(self) { + ctx.request_repaint(); + } if self.session.script_running() + && !crate::script_runs::waiting_for_print(self) && !self.session.script_waiting() && self.session.script_dialog().is_none() + && self.session.script_window().is_none() && self.session.script_picker().is_none() { // A script in `$.sleep` goes on when its time is up; until then the app can idle. A // script at a file dialog goes on when the dialog answers, and `file_asks::poll` looks - // for that. + // for that. A script at its ScriptUI dialog goes on when the dialog gives it an event. match self.session.script_sleep_left() { Some(left) => ctx.request_repaint_after(left), None => ctx.request_repaint(), @@ -650,6 +723,9 @@ impl VectorcraftApp { /// input to the automation roots and turns a panic into an error message. pub fn ui(&mut self, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); + if ctx.current_pass_index() == 0 && self.ticked_pass != Some(ctx.cumulative_pass_nr()) { + self.perf.early_events_ms = 0.0; + } self.adopt_context(&ctx); let confined = self.automation_scope(&ctx); if let Err(msg) = file_access::confine(confined.as_ref(), || { @@ -657,6 +733,19 @@ impl VectorcraftApp { self.handle_input(&ctx); self.ui_frame(ui); self.window_keys(&ctx); + // What the canvas, a panel, a dialog or a window key changed in this pass reaches + // the plug-ins that react to it now, since an idle app draws no further frame; a + // line a handler wrote shows in the next one. The handlers' time counts toward the + // frame-time sample of a pass egui presents. + let t0 = monotonic_ms(); + if !self.session.script_running() && self.deliver_plugin_events() { + ctx.request_repaint(); + } + if !ctx.will_discard() { + self.perf.frame_ms += monotonic_ms() - t0; + } else { + self.perf.early_events_ms += monotonic_ms() - t0; + } }) }) { self.session.set_replaying(false); @@ -721,6 +810,7 @@ impl VectorcraftApp { panels::learn::locate::tidy(self, &ctx); crate::doc_windows::show(self, ui); export_progress::show(self, ui); + crate::script_palettes::show(self, &ctx); // After every window this pass may open, and before the palette's field takes the keyboard. panel_docking::close_overlays_for_modal(self, &ctx); let drawn_document = self.session.active().map(|st| (st.uid, st.revision)); @@ -741,6 +831,10 @@ impl VectorcraftApp { toast::post(&ctx, &WindowKey::main(), Toast::new(t.message).tone(tone(t.level)).timeout(Some(t.seconds as f32))); } menus::native::sync(self, &ctx); + // A palette event that waited for an undo group this pass ended starts its run next frame. + if crate::script_palettes::can_start(self) { + ctx.request_repaint(); + } // Only a field's commit in the pass of the press is the one it made. self.canvas.committed_preview = false; self.drop_formats_after_egui_copy(&ctx); @@ -751,7 +845,7 @@ impl VectorcraftApp { // A pass egui will discard and rerun is not a presented frame: it must not become the // frame-time sample, and it must not issue a capture of what it drew. if !ctx.will_discard() { - self.perf.frame_ms = monotonic_ms() - t0; + self.perf.frame_ms = monotonic_ms() - t0 + std::mem::take(&mut self.perf.early_events_ms); self.issue_captures(&ctx); // A hidden window's pass shows nothing, so the step waits for a pass the user sees. if step_held && !self.viewport_hidden(&ctx) { @@ -839,6 +933,11 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print root.escape_leaves_fields = true; // A held key repeats its command (Cmd+= keeps zooming in). root.shortcuts_repeat = true; + // On Windows and Linux only the keypad digits type an Alt code, and Alt with a top-row digit stays a key press for + // the shortcuts (macOS has no Alt codes). A keypad digit types its code also when the Type tool claims Alt with that + // digit. On Windows the system composes keypad codes, and the app takes their digits out of the frame (the app's + // `windows_alt_codes`). + root.alt_code_keys = AltCodeKeys::Keypad; // The wheel steps a focused number field only while the pointer is over it; elsewhere it scrolls what is under the // pointer. root.pointer_scoped_field_wheel = true; diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 1298051ad8..818863408d 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -97,6 +97,9 @@ impl VectorcraftApp { crate::plugin_runs::show_notice(self, id, r); } placing::settle_swatch_paste(self); + for (uid, from, to) in self.session.take_swatch_renames() { + dialogs::gradient_stop::follow_swatch_rename(self, uid, &from, &to); + } result } @@ -262,7 +265,7 @@ impl VectorcraftApp { } // A filter plug-in run becomes Object › Plug-ins › Apply Last Filter. dialogs::plugin::after_command(self, id, ¶ms, &r, plugins_before); - let copied = r.is_ok() && self.publish_copy(id); + let copied = r.as_ref().is_ok_and(|v| self.publish_copy(id, v)); self.sync_views(); self.refresh_replace_font_warning(false); // File › Revert replaces the document in its tab, keeps the tab's view and starts the tool afresh. @@ -328,10 +331,11 @@ impl VectorcraftApp { r } - /// After a Copy or Cut `id` that ran: offer what it copied to other apps - /// ([`Self::publish_clipboard`]) → whether `id` is one. - fn publish_copy(&mut self, id: &str) -> bool { - let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut"); + /// After a Copy or Cut `id` that ran, or a script run to its end (`reply` without `running`) + /// that reports `copied`: offer what it copied to other apps ([`Self::publish_clipboard`]) → + /// whether it did. + fn publish_copy(&mut self, id: &str, reply: &Value) -> bool { + let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut") || (id == "script.run" && reply["copied"] == true); if copy { self.publish_clipboard(matches!(id, "edit.cut" | "artboard.cut")); } diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 2389373b4c..fc1694736a 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -44,6 +44,7 @@ impl VectorcraftApp { }); self.finish_captures(finished); let settle = settle_ms(ctx.global_style().animation_time); + let mut handled = 0usize; while let Some(req) = self.deferred_control.take().or_else(|| self.channel.as_mut().and_then(ControlChannel::next_request)) { // A request held past its deadline is answered as one still queued then. if req.deadline.is_some_and(|deadline| self.instant() >= deadline) { @@ -71,6 +72,7 @@ impl VectorcraftApp { // Guarded per request: a panic must not stop the requests behind it. let answer = file_access::confine(roots.as_ref(), || vectorcraft_engine::guard::catch_panic(|| control::handle(self, ctx, &req))); self.ui.answering_control = false; + handled += 1; let reply = match answer { Ok(reply) => reply, Err(msg) => { @@ -92,6 +94,10 @@ impl VectorcraftApp { host.paint_while_hidden(); } ctx.request_repaint(); + } else if handled > 0 && self.session.script_running() { + // A request may have answered the dialog a run waits at, which the app idles for: the + // next frame takes the answer and the run's next slice. + ctx.request_repaint(); } self.answer_pointer_waits(ctx); } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 06c564f4c8..d2809d5846 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -81,6 +81,9 @@ pub struct CanvasCache { /// The Hand, Zoom and Rotate View tools the Space key and its chords lend the canvas, between /// passes; the tool adapter takes it out for its call and puts it back. pub momentary: Option, + /// The keys down when the held momentary command started; empty while none is held or when none started it. + /// Temporary, with `tool_adapter::end_missed_momentary` (craft-libs#5056). + pub momentary_keys: Vec, pub hand: Option, /// The selected Zoom tool keeps its press and drag rectangle between canvas passes. pub zoom_tool: Option, @@ -129,6 +132,12 @@ pub struct CanvasCache { /// Escape cancelled the tool's press while the button is still down: its release still sends the tool its Up, /// which gives back a selection tool Cmd lent. pub escaped_press: bool, + /// The input time of the last pass whose pointer button events all landed on a canvas, with no other layer over it: + /// the menus' state key leaves such a press out (`menus::model::last_press`). + pub pressed_at: Option, + /// The input time of the last pass in which the canvas or nothing had the focus, so that the canvas or the app's + /// shortcuts took its keys: the menus' state key leaves those keys out (`menus::model::last_press`). + pub keys_at: Option, /// The host's Caps Lock state at the last canvas pass, which `VectorcraftApp::follow_caps_lock` compares with the /// next reading; `None` before the first pass. pub host_caps_lock: Option, @@ -409,4 +418,6 @@ pub struct Perf { pub frame_ms: f64, pub render_ms: f64, pub fps: f64, + /// Time plug-in event handlers took before the frame's UI pass, added to its `frame_ms`. + pub early_events_ms: f64, } diff --git a/crates/ui-egui/src/canvas/context_menu.rs b/crates/ui-egui/src/canvas/context_menu.rs index bfef665bb8..a52c6d64c1 100644 --- a/crates/ui-egui/src/canvas/context_menu.rs +++ b/crates/ui-egui/src/canvas/context_menu.rs @@ -1,3 +1,5 @@ +use craft::behavior::IconId; +use craft::menu::Item; use craft::ui::canvas::CanvasSpace; use craft::ui::contract::overlay::Anchor; use craft::ui::contract::{Bind, ShowContainer as _, Trigger}; @@ -47,7 +49,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp .opened_by(opener, Trigger::Manual) .anchor(Anchor::Point(at)) .open(Bind::bound(&mut open)) - .show(ui, |ui, _| craft::menu::context::rows(ui, &nodes)); + .show(ui, |ui, _| craft::menu::context::rows_with_icons(ui, &nodes, canvas_icon)); if shown.output.closed.is_some() || !open { app.ui.context_menu_at = None; app.ui.context_locked = None; @@ -57,6 +59,54 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp } } +/// The icon each canvas menu command shows in this menu, so a row can be found by its shape (#4602). A command +/// left out has no glyph that says what it does here, and shows its catalog icon, if any, or none. +const ICONS: &[(&str, &str)] = &[ + ("edit.undo", "undo-2"), + ("edit.redo", "redo-2"), + ("edit.cut", "scissors"), + ("edit.copy", "copy"), + ("edit.paste", "clipboard-paste"), + ("edit.clear", "trash-2"), + ("object.group", "group"), + ("object.ungroup", "ungroup"), + ("object.path.smooth", "dc-smooth"), + ("object.objectsOnPath.attach", "dc-objects-on-path"), + ("path.join", "dc-join"), + ("type.applyBullets", "dc-para-bullets"), + ("type.applyNumbers", "dc-para-numbers"), + ("view.grid", "grid-3x3"), + ("view.rulers", "ruler"), + ("view.guides.lock", "lock"), + ("view.fitArtboard", "maximize-2"), + ("artboard.new", "file-plus"), + ("artboard.duplicate", "copy"), + ("artboard.copy", "copy"), + ("artboard.cut", "scissors"), + ("artboard.delete", "trash-2"), + ("artboard.rearrange", "dc-rearrange"), + ("file.exportSelection", "share-2"), + ("file.exportForScreens", "share-2"), +]; + +/// The icons of rows whose command alone doesn't say what they do: Artboard Options (`tool.options` for the +/// Artboard tool) and the Lock Artboards and Unlock Artboards rows (`artboard.setProps` with `locked`). +const ARTBOARD_OPTIONS_ICON: &str = "dc-artboard-options"; +const LOCK_ICON: &str = "lock"; +const UNLOCK_ICON: &str = "lock-open"; + +/// The canvas menu's icon for `item`: Artboard Options' and the artboard lock rows' by their parameters, otherwise +/// its command's entry in [`ICONS`]. +fn canvas_icon(item: &Item) -> Option { + let params = &item.command.params; + let icon = match item.command.id.as_str() { + "tool.options" => (params["tool"] == "artboard").then_some(ARTBOARD_OPTIONS_ICON), + "artboard.setProps" => params["artboards"][0]["locked"].as_bool().map(|locked| if locked { LOCK_ICON } else { UNLOCK_ICON }), + id => ICONS.iter().find(|(command, _)| *command == id).map(|(_, icon)| *icon), + }; + icon.map(IconId::new) +} + /// The one-shot work of a request at screen point `at`: the facts the menu's rows read, and the selection. fn prepare(app: &mut VectorcraftApp, space: &CanvasSpace, at: Pos2) { let p = space.view.to_doc(at); @@ -114,3 +164,47 @@ fn prepare_key(app: &mut VectorcraftApp, space: &CanvasSpace) -> Pos2 { } at } + +#[cfg(test)] +mod tests { + use craft::behavior::IconId; + use craft::ui::primitives::has_icon; + + use craft::menu::Node; + use serde_json::json; + + use super::{ARTBOARD_OPTIONS_ICON, ICONS, LOCK_ICON, UNLOCK_ICON, canvas_icon}; + use crate::menus::cp; + + /// Each canvas menu icon names a drawn icon and a command: a misspelt icon would leave its row's icon slot + /// empty, and a renamed command would quietly lose its icon. + #[test] + fn every_canvas_menu_icon_is_an_icon_of_a_command() { + crate::icons::register(); + for (id, icon) in ICONS { + assert!(has_icon(&IconId::new(icon)), "{id}'s icon {icon} isn't an icon"); + let ui_command = crate::menus::UI_COMMANDS.iter().any(|c| c.0 == *id); + assert!(vectorcraft_engine::find_command(id).is_some() || ui_command, "{id} isn't a command"); + } + for icon in [ARTBOARD_OPTIONS_ICON, LOCK_ICON, UNLOCK_ICON] { + assert!(has_icon(&IconId::new(icon)), "{icon} isn't an icon"); + } + } + + /// Rows that share a command take their icon from their parameters: the Artboard Options glyph goes on + /// Artboard Options (`tool.options` for the Artboard tool), not on another tool's options, and the Lock + /// Artboards and Unlock Artboards rows (`artboard.setProps`) show a closed and an open lock. + #[test] + fn rows_that_share_a_command_take_their_icon_from_its_parameters() { + let icon = |node: Node| match node { + Node::Item(item) => canvas_icon(&item), + _ => None, + }; + let lock = |locked| cp("Lock All", "artboard.setProps", json!({ "artboards": [{ "index": 0, "locked": locked }] })); + assert_eq!(icon(cp("Artboard Options", "tool.options", json!({ "tool": "artboard" }))), Some(IconId::new(ARTBOARD_OPTIONS_ICON))); + assert_eq!(icon(cp("Options", "tool.options", json!({ "tool": "pen" }))), None); + assert_eq!(icon(lock(true)), Some(IconId::new(LOCK_ICON))); + assert_eq!(icon(lock(false)), Some(IconId::new(UNLOCK_ICON))); + assert_ne!(icon(lock(true)), icon(lock(false))); + } +} diff --git a/crates/ui-egui/src/canvas/marks.rs b/crates/ui-egui/src/canvas/marks.rs index abe7c5a6db..9993669339 100644 --- a/crates/ui-egui/src/canvas/marks.rs +++ b/crates/ui-egui/src/canvas/marks.rs @@ -835,3 +835,65 @@ pub(in crate::canvas) fn live_paint_gap_overlays(app: &mut VectorcraftApp) -> Ve }; gaps.to_vec() } + +/// Teeth View → Show Curvature Comb draws on each segment. +const COMB_SAMPLES: usize = 16; +/// The comb's length at zoom 1, in screen points squared: a curve that bends with a radius of +/// 100 screen points has teeth 20 screen points long at any zoom. VectorCraft's own value. +const COMB_SCALE: f64 = 2000.0; + +/// View → Show Curvature Comb: on each selected path, and each path of a selected compound path, a +/// tooth along the normal at evenly spaced points of every segment, as long as the curvature there, +/// and a line through the teeth's tips, in the path's layer color. At most +/// [`vectorcraft_geom::curvature::MAX_COMB_TEETH`] teeth in all, shared among the subpaths by their +/// number of segments, so a large selection gets fewer teeth everywhere. +pub(in crate::canvas) fn curvature_comb_overlays(app: &VectorcraftApp, zoom: f64) -> Vec { + use vectorcraft_geom::curvature::{MAX_COMB_TEETH, comb_closes, curvature_comb}; + let Some(st) = app.session.active() else { return vec![] }; + if !(zoom.is_finite() && zoom > 0.0) { + return vec![]; + } + let scale = COMB_SCALE / (zoom * zoom); + let mut paths = vec![]; + for &id in &st.selection.objects { + let Some(n) = st.doc.node(id).filter(|n| !n.is_guide()) else { continue }; + let color = st.doc.layer_color(id); + match &n.kind { + NodeKind::Compound { children, .. } => paths.extend(children.iter().filter_map(|c| c.path_data()).map(|pd| (pd, color))), + _ => paths.extend(n.path_data().map(|pd| (pd, color))), + } + } + let all: Vec<_> = + paths.iter().flat_map(|(pd, color)| pd.subpaths.iter().map(move |sp| (sp, *color))).filter(|(sp, _)| sp.segment_count() > 0).collect(); + // With more subpaths than the teeth allow 2 each, every k-th subpath gets a comb. + let stride = (all.len() * 2).div_ceil(MAX_COMB_TEETH).max(1); + let chosen: Vec<_> = all.into_iter().step_by(stride).collect(); + // Each chosen subpath has 2 teeth set aside; the rest are shared by number of segments. + let total: usize = chosen.iter().map(|(sp, _)| sp.segment_count()).sum(); + let spare = MAX_COMB_TEETH.saturating_sub(2 * chosen.len()); + let mut o = vec![]; + for (sp, color) in chosen { + let extra = (spare as u128) * (sp.segment_count() as u128) / (total.max(1) as u128); + let share = 2usize.saturating_add(usize::try_from(extra).unwrap_or(usize::MAX)); + let teeth = curvature_comb(sp, COMB_SAMPLES, scale, share); + let mut envelope = BezPath::new(); + for t in &teeth { + o.push(Overlay::Line { a: t.at, b: t.tip, color, dashed: false }); + if t.start { + envelope.move_to(t.tip); + } else { + envelope.line_to(t.tip); + } + } + // A closed subpath combed all the way round ends where it starts: the line closes there. + if let Some(first) = teeth.first() + && comb_closes(sp, &teeth) + { + envelope.line_to(first.tip); + } + if teeth.len() > 1 { + o.push(Overlay::Path { path: envelope, color, width: 1.0, dashed: false }); + } + } + o +} diff --git a/crates/ui-egui/src/canvas/marks/tests.rs b/crates/ui-egui/src/canvas/marks/tests.rs index 29336a8ad8..621a7b67e2 100644 --- a/crates/ui-egui/src/canvas/marks/tests.rs +++ b/crates/ui-egui/src/canvas/marks/tests.rs @@ -359,6 +359,46 @@ fn live_paint_gaps_follow_the_selected_groups() { assert!(live_paint_gap_overlays(&mut app).is_empty()); } +/// View → Show Curvature Comb: a selected circle of radius 100 gets teeth 20 screen points long at +/// zoom 1 and 10 at zoom 2, where it shows twice as large (within 3%: the circle is made of cubics), +/// and a line through their tips; a compound path gets a comb on each of its paths; nothing +/// selected draws nothing. +#[test] +fn the_curvature_comb_follows_the_selection_and_the_zoom() { + let mut app = app(); + let id = app.session.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let teeth = |o: &[Overlay], zoom: f64| -> Vec { + o.iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { Some(a.distance(*b) * zoom) } else { None }).collect() + }; + let at_one = teeth(&curvature_comb_overlays(&app, 1.0), 1.0); + for zoom in [1.0, 2.0] { + let o = curvature_comb_overlays(&app, zoom); + let got = teeth(&o, zoom); + assert_eq!(got.len(), 64, "16 teeth on each of the circle's four segments"); + let want = 2000.0 / (100.0 * zoom); + assert!(got.iter().all(|t| (t - want).abs() < 0.03 * want), "{zoom}: {got:?}"); + assert!(got.iter().zip(&at_one).all(|(t, one)| (t * zoom - one).abs() < 1e-9), "zoom divides each tooth's screen length"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Path { .. })).count(), 1, "one line through the tips"); + let Some(Overlay::Path { path, .. }) = o.iter().find(|o| matches!(o, Overlay::Path { .. })) else { panic!("no line through the tips") }; + let ends: Vec<_> = path.elements().iter().filter_map(|e| e.end_point()).collect(); + assert_eq!(ends.first(), ends.last(), "the closed circle's line through the tips closes"); + } + let other = app.session.execute("shape.ellipse", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id, other]})).unwrap(); + app.session.execute("object.compoundPath.make", &json!({})).unwrap(); + let o = curvature_comb_overlays(&app, 1.0); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Path { .. })).count(), 2, "the compound path's two paths"); + assert_eq!(teeth(&o, 1.0).len(), 128); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(curvature_comb_overlays(&app, 1.0).is_empty()); + assert!(app.run("view.curvatureComb", json!({"on": true})).is_err(), "it takes no parameters"); + assert!(!app.ui.view.curvature_comb, "a refused call leaves it off"); + assert!(app.run("view.curvatureComb", json!({})).unwrap() == json!(true)); + assert!(app.ui.view.curvature_comb); + assert!(app.run("view.curvatureComb", json!({})).unwrap() == json!(false)); +} + /// Draw Inside's arms: an open rectangle round the object, each arm a third of its side or 16 /// points at most, kept with the object deselected and gone with the mode. #[test] diff --git a/crates/ui-egui/src/canvas/quick_pen_bar.rs b/crates/ui-egui/src/canvas/quick_pen_bar.rs index 9b2846847e..ec268beb61 100644 --- a/crates/ui-egui/src/canvas/quick_pen_bar.rs +++ b/crates/ui-egui/src/canvas/quick_pen_bar.rs @@ -19,7 +19,7 @@ use craft::ui::canvas_controls::TaskBar; use craft::ui::choice::Segmented; use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; use craft::ui::primitives::IconSpec; -use craft::ui::runtime::env::{Direction, Env}; +use craft::ui::runtime::env::{Direction, Env, WordsOverride, with_env}; use vectorcraft_tools::quickpen::{self, Stroke as Action}; use super::{Ui, VectorcraftApp, json}; @@ -31,6 +31,13 @@ pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &Canva if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID { return None; } + let lang = app.ui_language(); + let words = super::task_bar::bar_words(lang, "Move Toolbar", "Hide Toolbar", "window.quickPenToolbar.pin", "window.quickPenToolbar.reset"); + with_env(ui, |env| env.words = Some(WordsOverride::Overlay(words)), |ui| shown_quick_pen_bar(app, ui, space)) +} + +/// The Quick Pen toolbar of [`quick_pen_bar`], in a scope with the toolbar's words. +fn shown_quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { // PLAN: assumed `super::tool_adapter::in_gesture(app: &VectorcraftApp, ctx: &egui::Context) -> bool` (cv.S3) if super::tool_adapter::in_gesture(app, ui.ctx()) { return None; diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 4f50576df8..c2d53fcf97 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -8,15 +8,15 @@ use std::hash::{Hash, Hasher}; use std::sync::{Arc, Weak}; use craft::behavior::Input; -use craft::behavior::Metrics; +use craft::behavior::{CanvasView, Metrics}; use craft::draw::ui::{ - AnchorsShown, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleStyle, HandlesShown, Knot, KnotRef, PathOptionsSettings, PathSelection, + AnchorsShown, EditPath, EditSubpath, HandleSide, HandleStyle, HandlesShown, Knot, KnotRef, MAX_ANCHORS, PathOptionsSettings, PathSelection, SegmentMark, }; use craft::theme::Srgba; use craft::ui::canvas::{CanvasSpace, canvas_space}; -use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline}; -use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _}; +use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline, path_runs}; +use craft::ui::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _, Styled as _}; use craft::ui::style::{ComponentStyle, DataColor, StyleCx}; use egui::{Color32, Rect, Response, Shape, Stroke, StrokeKind, vec2}; use vectorcraft_doc::{Document, NodeId, NodeKind}; @@ -622,6 +622,457 @@ impl Component for SelectionDots<'_> { } } +// TEMPORARY: craft-libs#4900 and craft-libs#4928. `BezierOverlay` at the pinned craft-libs lays out its scene and +// flattens and strokes every outline on every paint, and the canvas cloned the paths for it each frame, so a large +// selection stalled every frame. `AnchorMarks` draws what the overlay draws under `BezierTool::Anchors`, from the +// kept marks, and keeps it as one mesh while the marks, the view and the look stay the same. When the craft-libs pin +// includes both pull requests, remove `AnchorMarks` and this section and go back to +// `BezierOverlay::display(...).revision(marks.key)`. + +/// The marks' look, resolved from the theme: the colors and widths `BezierOverlay` paints anchors, handles and +/// outlines with. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +struct AnchorMarksStyle { + #[style(metrics)] + metrics: Metrics, + /// The outline of a path without a color of its own, and the fill of a selected anchor. + line: craft::ui::style::StyleColor, + /// The fill of a hollow anchor and of a handle's end, per state. + fill: craft::ui::style::Stateful, + /// The edge of an anchor or a handle's end, for a path without a color of its own. + edge: craft::ui::style::StyleColor, + /// An anchor's side. + anchor: f32, + /// A handle end's side with Large handles. + large: f32, + thin: f32, + medium: f32, + thick: f32, + /// How far outside the canvas an anchor or a handle's end is still drawn. + reach: f32, +} + +/// [`AnchorMarksStyle`] for one paint, with the fill resolved: what the kept mesh is built from besides the marks. +#[derive(Clone, Copy, Debug, PartialEq)] +struct MarkLook { + line: Color32, + fill: Color32, + edge: Color32, + anchor: f32, + large: f32, + thin: f32, + medium: f32, + thick: f32, + reach: f32, +} + +/// Everything the kept mesh of the anchor marks depends on. +#[derive(Clone, Copy, Debug, PartialEq)] +struct MeshKey { + /// [`marks_key`] of the marks. + marks: u64, + view: CanvasView, + rect: Rect, + clip: Rect, + pixels_per_point: f32, + options: egui::epaint::TessellationOptions, + look: MarkLook, +} + +/// The anchor marks tessellated as one mesh, and what they were tessellated from. +pub(crate) struct KeptMesh { + key: MeshKey, + mesh: Arc, +} + +/// One set of anchors as `BezierOverlay` took it: the paths, which anchors are selected and how they show. +struct MarkSet<'a> { + paths: &'a [EditPath], + selection: &'a PathSelection, + handles: HandlesShown, + shown: AnchorsShown, + segment_mark: SegmentMark, + options: &'a PathOptionsSettings, +} + +/// The two sets the canvas shows: the paths whose handles the tools drag, then the paths whose anchors show selected +/// without handles. +fn mark_sets(anchors: &Anchors) -> [MarkSet<'_>; 2] { + [ + MarkSet { + paths: &anchors.paths, + selection: &anchors.selection, + handles: anchors.handles, + shown: anchors.shown, + segment_mark: anchors.segment_mark, + options: &anchors.options, + }, + MarkSet { + paths: &anchors.plain, + selection: &anchors.plain_selection, + handles: HandlesShown::OneAnchor, + shown: anchors.shown, + segment_mark: SegmentMark::default(), + options: &anchors.options, + }, + ] +} + +/// The anchors, handles and outlines of the selection, painted over the canvas as one kept mesh: no pointer, key or +/// accessibility node, as `BezierOverlay` under `BezierTool::Anchors` has none. +#[derive(craft::ui::contract::Component, craft::ui::contract::Props)] +#[component(canvas_control, content_painter)] +struct AnchorMarks<'a> { + #[common] + common: Common, + anchors: &'a Anchors, + /// [`marks_key`] of `anchors`. + key: u64, + kept: &'a std::cell::RefCell>, +} + +impl Component for AnchorMarks<'_> { + const ROLE: Role = Role::GRAPHICS_OBJECT; + const ALT_ROLES: &'static [Role] = &[Role::None]; + const INPUT: Input = Input::Display; + const PARTS: bool = false; + const STOPS: bool = false; + const OVERLAYS: bool = false; + type Style = AnchorMarksStyle; + type Output = Response; + + fn style(cx: &StyleCx<'_>, _: AnchorMarksStyleKey) -> AnchorMarksStyle { + let tokens = cx.tokens; + let handle = cx.handle(); + AnchorMarksStyle { + metrics: Metrics::new(), + line: cx.color(tokens.color.overlay.line), + fill: handle.fill, + edge: handle.stroke, + anchor: tokens.size.handle.sm, + large: handle.side, + thin: tokens.stroke.thin, + medium: tokens.stroke.medium, + thick: tokens.stroke.thick, + reach: tokens.size.hit.target, + } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> egui::Vec2 { + egui::Vec2::ZERO + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let Some(space) = canvas_space(&cx.env) else { return }; + let style = &cx.style; + let look = MarkLook { + line: style.line.egui(), + fill: cx.resolve(&style.fill).egui(), + edge: style.edge.egui(), + anchor: style.anchor, + large: style.large, + thin: style.thin, + medium: style.medium, + thick: style.thick, + reach: style.reach, + }; + let painter = ui.content_painter(cx); + let key = MeshKey { + marks: self.key, + view: space.view, + rect: cx.rect, + clip: painter.painter.clip_rect(), + pixels_per_point: painter.pixels_per_point(), + options: painter.painter.ctx().tessellation_options(|options| *options), + look, + }; + let shapes = || { + let mut shapes = Vec::new(); + for set in mark_sets(self.anchors) { + mark_shapes(&mut shapes, &set, &space.view, cx.rect, &look); + } + shapes + }; + #[cfg(test)] + if tests::RAW_MARKS.with(std::cell::Cell::get) { + painter.painter.extend(shapes()); + return; + } + let mut kept = self.kept.borrow_mut(); + let mesh = match kept.as_ref().filter(|kept| kept.key == key) { + Some(kept) => Arc::clone(&kept.mesh), + None => { + let shapes = shapes(); + let mesh = Arc::new(tessellate(shapes, &key)); + *kept = Some(KeptMesh { key, mesh: Arc::clone(&mesh) }); + mesh + } + }; + if !mesh.is_empty() { + painter.painter.add(Shape::Mesh(mesh)); + } + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.role(Role::None); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +/// `shapes` as one mesh, tessellated as the frame would tessellate them, except that a small filled circle is a +/// polygon rather than a disc from the font atlas, so a later change to the atlas cannot leave the mesh wrong. +fn tessellate(shapes: Vec, key: &MeshKey) -> egui::Mesh { + #[cfg(test)] + tests::MESHES_BUILT.with(|built| built.set(built.get() + 1)); + let mut tessellator = egui::epaint::Tessellator::new(key.pixels_per_point, key.options, [1, 1], Vec::new()); + tessellator.set_clip_rect(key.clip); + let mut mesh = egui::Mesh::default(); + for shape in shapes { + tessellator.tessellate_shape(shape, &mut mesh); + } + mesh +} + +/// Shows the selection's anchors, handles and outlines from `marks`. +fn paint_anchor_marks(ui: &mut egui::Ui, rect: Rect, marks: &SelectionMarks) { + let anchors = &marks.anchors; + if anchors.paths.is_empty() && anchors.plain.is_empty() { + return; + } + #[cfg(test)] + if tests::OVERLAY_MARKS.with(std::cell::Cell::get) { + tests::paint_with_overlay(ui, rect, anchors); + return; + } + AnchorMarks { common: Common::new(), anchors, key: marks.key, kept: &marks.mesh }.label("Anchors").show_at(ui, rect); +} + +/// The fill of an anchor or a handle's end. +#[derive(Clone, Copy)] +enum MarkFill { + /// The look's fill. + Look, + /// The path's color, or the look's line without one: a selected anchor. + Path, +} + +/// The egui shapes `BezierOverlay` paints for `set` under `BezierTool::Anchors`, in its order: every outline, the +/// selected segment, then the anchors and handles near `rect`, then the handles of the other paths' selected anchors. +fn mark_shapes(out: &mut Vec, set: &MarkSet<'_>, view: &CanvasView, rect: Rect, look: &MarkLook) { + let options = set.options; + let option_color = options.color.map(|[r, g, b]| Color32::from(Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0))); + let path_color = |path: &EditPath| path.color.map(Color32::from); + let anchor_side = options.anchor_size.unwrap_or(look.anchor); + let handle_side = if options.handles == HandleStyle::Large { look.large } else { look.anchor }; + let circles = set.shown == AnchorsShown::Curvature; + let line = |out: &mut Vec, points: Vec, closed: bool, segment: bool, color: Option| { + let named = if segment { look.thick } else { look.medium }; + let ink = color.unwrap_or(look.line); + match options.thickness { + Some(thickness) => { + if segment { + stroke_line(out, points.clone(), closed, Stroke::new(thickness, ink)); + stroke_line(out, points, closed, Stroke::new(named, ink)); + } else { + stroke_line(out, points, closed, Stroke::new(thickness, ink)); + } + } + None => stroke_line(out, points, closed, Stroke::new(named, ink)), + } + }; + for path in set.paths { + let color = path.color.map(Color32::from).or(option_color); + for sub in &path.subpaths { + for (points, closed) in path_runs(view, &sub.bez_path()) { + line(out, points, closed, false, color); + } + } + if set.segment_mark == SegmentMark::Line + && let Some(s) = set.selection.segment.filter(|_| set.selection.path == Some(path.key)) + && let Some(curve) = path.subpaths.get(s.subpath).and_then(|sub| sub.segment(s.knot)) + { + let mut segment = BezPath::new(); + segment.move_to(curve.p0); + segment.curve_to(curve.p1, curve.p2, curve.p3); + for (points, closed) in path_runs(view, &segment) { + line(out, points, closed, true, color); + } + } + } + let total: usize = set.paths.iter().map(EditPath::anchor_count).sum(); + if set.shown == AnchorsShown::Hidden || total > MAX_ANCHORS { + return; + } + let mark = |out: &mut Vec, at: egui::Pos2, side: f32, circle: bool, fill: MarkFill, color: Option| { + let fill = match fill { + MarkFill::Look => look.fill, + MarkFill::Path => color.unwrap_or(look.line), + }; + let edge = Stroke::new(look.thin, color.unwrap_or(look.edge)); + if circle { + let radius = side / 2.0; + out.push(Shape::Circle(egui::epaint::CircleShape { center: at, radius, fill, stroke: Stroke::NONE })); + out.push(Shape::Circle(egui::epaint::CircleShape { center: at, radius, fill: Color32::TRANSPARENT, stroke: edge })); + } else { + let square = Rect::from_center_size(at, egui::Vec2::splat(side)); + out.push(Shape::Rect(egui::epaint::RectShape::new(square, 0.0, fill, Stroke::NONE, StrokeKind::Inside))); + out.push(Shape::Rect(egui::epaint::RectShape::new(square, 0.0, Color32::TRANSPARENT, edge, StrokeKind::Inside))); + } + }; + // A direction handle: its line from the anchor, then its end. + let handle = |out: &mut Vec, path: &EditPath, knot: KnotRef, end: egui::Pos2| { + let color = path_color(path); + if let Some(knot) = path.knot(knot) { + out.push(Shape::line(vec![view.to_screen(knot.anchor), end], Stroke::new(look.thin, color.unwrap_or(look.line)))); + } + mark(out, end, handle_side, true, MarkFill::Look, color); + }; + let selected = Selected::of(set.selection); + let near = rect.expand(look.reach); + let shown = if circles { Vec::new() } else { shown_handles(set.paths, set.selection, &selected, set.handles, view) }; + let mut handles = shown.iter().peekable(); + for (at, path) in set.paths.iter().enumerate() { + for knot_ref in path.knot_refs() { + let Some(knot) = path.knot(knot_ref) else { continue }; + let anchor = view.to_screen(knot.anchor); + if near.contains(anchor) && set.selection.shows(path.key, knot_ref.subpath) { + let fill = if selected.draws_selected(path.key, knot_ref) { MarkFill::Path } else { MarkFill::Look }; + mark(out, anchor, anchor_side, circles, fill, path_color(path)); + } + while let Some(&(_, _, end)) = handles.next_if(|(p, k, _)| *p == at && *k == knot_ref) { + if near.contains(end) { + handle(out, path, knot_ref, end); + } + } + } + } + if circles || set.handles == HandlesShown::All { + return; + } + // The handles of anchors selected in paths other than the edited one. + let edited = set.selection.path.map_or(0, |_| set.selection.anchors.len()); + for path in set.paths { + if set.selection.path == Some(path.key) || !selected.listed.contains(&path.key) { + continue; + } + let own = PathSelection::new(Some(path.key), Vec::new(), None); + let listed = |key: u64, knot: KnotRef| selected.others.contains(&(key, knot)); + for (_, knot, end) in handles_of(std::slice::from_ref(path), &own, listed, selected.others_len + edited, set.handles, view) { + handle(out, path, knot, end); + } + } +} + +/// Strokes the run `points`, closed or open, on its centre line. +fn stroke_line(out: &mut Vec, points: Vec, closed: bool, stroke: Stroke) { + if closed { + if stroke.is_empty() { + return; + } + let mut line = egui::epaint::PathStroke::from(stroke); + line.kind = StrokeKind::Middle; + out.push(Shape::closed_line(points, line)); + } else { + out.push(Shape::line(points, stroke)); + } +} + +/// The anchors a [`PathSelection`] selects, gathered into sets once. +struct Selected { + path: Option, + anchors: std::collections::HashSet, + others: std::collections::HashSet<(u64, KnotRef)>, + listed: std::collections::HashSet, + others_len: usize, +} + +impl Selected { + fn of(sel: &PathSelection) -> Self { + Self { + path: sel.path, + anchors: sel.anchors.iter().copied().collect(), + others: sel.others.iter().flat_map(|(key, knots)| knots.iter().map(|knot| (*key, *knot))).collect(), + listed: sel.others.iter().map(|(key, _)| *key).collect(), + others_len: sel.others.iter().map(|(_, knots)| knots.len()).sum(), + } + } + + /// Whether `knot` of `path` is a selected anchor of the edited path. + fn has_anchor(&self, path: u64, knot: KnotRef) -> bool { + self.path == Some(path) && self.anchors.contains(&knot) + } + + /// Whether `knot` of `path` draws selected. + fn draws_selected(&self, path: u64, knot: KnotRef) -> bool { + self.has_anchor(path, knot) || self.others.contains(&(path, knot)) + } +} + +/// The handles that show for `sel`, in path order, in then out: each path's index, the knot and the end on screen. +fn shown_handles( + paths: &[EditPath], + sel: &PathSelection, + selected: &Selected, + shown: HandlesShown, + view: &CanvasView, +) -> Vec<(usize, KnotRef, egui::Pos2)> { + handles_of(paths, sel, |path, knot| selected.has_anchor(path, knot), sel.selected_len(), shown, view) +} + +/// The handles that show, with `has_anchor` answering whether a knot is a selected anchor and `count` the number of +/// selected anchors `HandlesShown::OneAnchor` counts. A retracted handle and the handles of a subpath the selection +/// does not show are left out. +fn handles_of( + paths: &[EditPath], + sel: &PathSelection, + has_anchor: impl Fn(u64, KnotRef) -> bool, + count: usize, + shown: HandlesShown, + view: &CanvasView, +) -> Vec<(usize, KnotRef, egui::Pos2)> { + let mut out = Vec::new(); + for (index, path) in paths.iter().enumerate() { + let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| { + let (a, b) = path.subpaths.get(s.subpath)?.segment_ends(s.knot)?; + Some((KnotRef::new(s.subpath, a), KnotRef::new(s.subpath, b))) + }); + for knot_ref in path.knot_refs().filter(|k| sel.shows(path.key, k.subpath)) { + let Some(knot) = path.knot(knot_ref) else { continue }; + for side in [HandleSide::In, HandleSide::Out] { + let of_selection = || { + has_anchor(path.key, knot_ref) + || next_to_selected(path, &has_anchor, knot_ref, side) + || segment_ends.is_some_and(|(a, b)| (side == HandleSide::Out && a == knot_ref) || (side == HandleSide::In && b == knot_ref)) + }; + let wanted = match shown { + HandlesShown::All => true, + HandlesShown::OneAnchor => count == 1 && of_selection(), + _ => of_selection(), + }; + if wanted && !knot.retracted(side) { + out.push((index, knot_ref, view.to_screen(knot.handle(side)))); + } + } + } + } + out +} + +/// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out handle +/// or the next anchor's in handle, across a closed subpath's seam too. +fn next_to_selected(path: &EditPath, has_anchor: &impl Fn(u64, KnotRef) -> bool, knot: KnotRef, side: HandleSide) -> bool { + let Some(sub) = path.subpaths.get(knot.subpath) else { return false }; + let count = sub.knots.len(); + if side == HandleSide::Out { + return sub.segment_ends(knot.knot).is_some_and(|(_, next)| has_anchor(path.key, KnotRef::new(knot.subpath, next))); + } + let previous = (knot.knot + count.saturating_sub(1)) % count.max(1); + sub.segment_ends(previous).is_some_and(|(previous, _)| has_anchor(path.key, KnotRef::new(knot.subpath, previous))) +} + /// Whether the active tool draws its own points over the paths: the Curvature tool while it has a draft. fn tool_draws_points(app: &mut VectorcraftApp) -> bool { if app.session.tool_id() != "curvature" { @@ -675,27 +1126,7 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp } outline.show_at(ui, rect); } - let anchors = &marks.anchors; - if !anchors.paths.is_empty() { - let mut paths = anchors.paths.clone(); - // The marks only show the selection: the tools make the edits. - let _ = BezierOverlay::new("Anchors", Bind::bound(&mut paths), &anchors.selection) - .tool(BezierTool::Anchors) - .handles(anchors.handles) - .anchors(anchors.shown) - .segment_mark(anchors.segment_mark) - .path_options(&anchors.options) - .show_at(ui, rect); - } - if !anchors.plain.is_empty() { - let mut paths = anchors.plain.clone(); - let _ = BezierOverlay::new("Selected anchors", Bind::bound(&mut paths), &anchors.plain_selection) - .tool(BezierTool::Anchors) - .handles(HandlesShown::OneAnchor) - .anchors(anchors.shown) - .path_options(&anchors.options) - .show_at(ui, rect); - } + paint_anchor_marks(ui, rect, &marks); let dots = &marks.dots; if !(dots.centers.is_empty() && dots.origins.is_empty() && dots.key_anchor.is_none()) { SelectionDots { common: Common::new(), dots }.label("Selection dots").show_at(ui, rect); @@ -722,6 +1153,8 @@ pub(crate) struct SelectionMarks { outlines: Vec, anchors: Anchors, dots: Dots, + /// The anchor marks as one mesh, from the last paint ([`AnchorMarks`]). + mesh: std::cell::RefCell>, } impl SelectionMarks { @@ -738,6 +1171,7 @@ impl SelectionMarks { outlines: outlines(app, st), anchors: anchors(app, st, tool, tool_points), dots: dots(app, st), + mesh: std::cell::RefCell::new(None), } } @@ -803,4 +1237,4 @@ fn view_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) } #[cfg(test)] -mod tests; +pub(super) mod tests; diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 42e0bc620b..42adf76890 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -942,6 +942,217 @@ fn grouping_selected_anchors_by_path_compares_each_path_a_bounded_number_of_time assert!(compared.get() < 2 * 2001, "{} comparisons for 2,001 entries", compared.get()); } +thread_local! { + /// Whether `show` draws the anchor marks with `BezierOverlay`, as it did before [`AnchorMarks`]. + pub(super) static OVERLAY_MARKS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Whether [`AnchorMarks`] paints its shapes one by one instead of as a mesh. + pub(in crate::canvas) static RAW_MARKS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many meshes [`AnchorMarks`] tessellated. + pub(super) static MESHES_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The anchor marks as `show` drew them before [`AnchorMarks`]: two `BezierOverlay`s under `BezierTool::Anchors`. +pub(super) fn paint_with_overlay(ui: &mut egui::Ui, rect: Rect, anchors: &Anchors) { + use craft::draw::ui::{BezierOverlay, BezierTool}; + use craft::ui::contract::Bind; + if !anchors.paths.is_empty() { + let mut paths = anchors.paths.clone(); + let _ = BezierOverlay::new("Anchors", Bind::bound(&mut paths), &anchors.selection) + .tool(BezierTool::Anchors) + .handles(anchors.handles) + .anchors(anchors.shown) + .segment_mark(anchors.segment_mark) + .path_options(&anchors.options) + .show_at(ui, rect); + } + if !anchors.plain.is_empty() { + let mut paths = anchors.plain.clone(); + let _ = BezierOverlay::new("Selected anchors", Bind::bound(&mut paths), &anchors.plain_selection) + .tool(BezierTool::Anchors) + .handles(HandlesShown::OneAnchor) + .anchors(anchors.shown) + .path_options(&anchors.options) + .show_at(ui, rect); + } +} + +/// One frame of the canvas alone with `events`. +fn canvas_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::super::show(app, ui)); + out.textures_delta.clear(); + out +} + +/// The shapes a canvas frame paints, with the anchor marks drawn by `BezierOverlay` (`overlay`) or by +/// [`AnchorMarks`] one shape at a time. +fn canvas_shapes(app: &mut VectorcraftApp, ctx: &egui::Context, overlay: bool) -> Vec { + OVERLAY_MARKS.with(|on| on.set(overlay)); + RAW_MARKS.with(|on| on.set(!overlay)); + canvas_frame(app, ctx, vec![]); + let out = canvas_frame(app, ctx, vec![]); + OVERLAY_MARKS.with(|on| on.set(false)); + RAW_MARKS.with(|on| on.set(false)); + crate::tests::labels::flat_painted_shapes(&out.shapes) +} + +/// A canvas app with one curve, the task bar off and every frame drawn on this thread. +fn canvas_app() -> (VectorcraftApp, NodeId) { + let mut app = blank(); + app.ui.task_bar = false; + app.canvas.worker_started = true; + let curve = id_of(&app.run("path.create", json!({"d": "M40 40 C60 10 90 10 110 40 S160 70 180 40 L180 90"})).unwrap()); + (app, curve) +} + +// The anchor marks paint the shapes `BezierOverlay` paints for the same marks: under the Selection tool, Direct +// Selection with a partial selection, a selected segment and the Curvature tool, with handles shown for one anchor or +// for every selected anchor, each handle style, and the Path Options color and thickness on paths without a color. +#[test] +fn the_anchor_marks_paint_what_the_bezier_overlay_paints() { + let (mut app, curve) = scene(); + let ctx = crate::testing::ui_context(); + let compare = |app: &mut VectorcraftApp, case: &str, change: &dyn Fn(&mut Anchors)| { + canvas_frame(app, &ctx, vec![]); + if let Some(marks) = app.canvas.selection_marks.as_mut() { + change(&mut marks.anchors); + } + let overlay = canvas_shapes(app, &ctx, true); + let marks = canvas_shapes(app, &ctx, false); + assert!(overlay.len() > 20, "{case}: the overlay painted the marks ({} shapes)", overlay.len()); + let differs = overlay.iter().zip(&marks).position(|(a, b)| a != b); + assert!( + overlay == marks, + "{case}: {} shapes from the overlay, {} from the marks, first difference at {differs:?}", + overlay.len(), + marks.len() + ); + }; + let same = |_: &mut Anchors| {}; + app.select_tool("selection"); + compare(&mut app, "the Selection tool", &same); + for (multiple, style) in [(true, "solid"), (false, "hollow"), (true, "large")] { + app.session.prefs.show_handles_multiple_anchors = multiple; + app.session.prefs.handle_style = style.into(); + app.session.prefs.anchor_size = 5; + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 1], [0, 2]], "mode": "set"})).unwrap(); + compare(&mut app, &format!("Direct Selection, multiple {multiple}, {style}"), &same); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 2]], "mode": "set"})).unwrap(); + compare(&mut app, &format!("one anchor, multiple {multiple}, {style}"), &same); + } + // A segment selected in place keeps the revision, so the kept marks are dropped to build them again. + let pick_segment = |app: &mut VectorcraftApp| { + app.session.active_mut().unwrap().selection.segments.insert(curve, [(0, 1)].into_iter().collect()); + app.canvas.selection_marks = None; + }; + pick_segment(&mut app); + compare(&mut app, "a selected segment", &|anchors| assert!(anchors.selection.segment.is_some(), "a segment is selected")); + app.session.active_mut().unwrap().selection.segments.clear(); + app.run("select.all", json!({})).unwrap(); + compare(&mut app, "every handle", &|anchors| anchors.handles = HandlesShown::All); + let options = |anchors: &mut Anchors| { + anchors.options.color = Some([10, 200, 30]); + anchors.options.thickness = Some(3.0); + for path in anchors.paths.iter_mut().chain(&mut anchors.plain) { + path.color = None; + } + }; + compare(&mut app, "the Path Options color and thickness", &options); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + app.select_tool("directSelection"); + pick_segment(&mut app); + compare(&mut app, "a selected segment with a thickness", &options); + compare(&mut app, "paths without a color", &|anchors| { + for path in anchors.paths.iter_mut().chain(&mut anchors.plain) { + path.color = None; + } + }); + app.session.active_mut().unwrap().selection.segments.clear(); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + app.select_tool("curvature"); + compare(&mut app, "the Curvature tool", &same); +} + +// The canvas tessellates the anchor marks once and paints the kept mesh while nothing they show changes: frames that +// change nothing tessellate none, and a new selection, a scroll of the view and a new zoom each tessellate them once. +#[test] +fn an_idle_frame_tessellates_no_anchor_marks() { + let (mut app, curve) = canvas_app(); + app.select_tool("directSelection"); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + let ctx = crate::testing::ui_context(); + let frames = |app: &mut VectorcraftApp, n: usize| { + let before = MESHES_BUILT.with(std::cell::Cell::get); + for _ in 0..n { + canvas_frame(app, &ctx, vec![]); + } + MESHES_BUILT.with(std::cell::Cell::get) - before + }; + assert_eq!(frames(&mut app, 3), 1, "the first frame tessellates the marks"); + assert_eq!(frames(&mut app, 10), 0, "frames that change nothing"); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + assert_eq!(frames(&mut app, 5), 1, "a new selection"); + app.view_mut().unwrap().center.x += 40.0; + assert_eq!(frames(&mut app, 5), 1, "a scroll"); + app.view_mut().unwrap().zoom *= 2.0; + assert_eq!(frames(&mut app, 5), 1, "a new zoom"); + app.run("select.none", json!({})).unwrap(); + assert_eq!(frames(&mut app, 5), 0, "nothing selected, nothing to tessellate"); +} + +/// What a press-drag and Tab presses did: the curve's bounds, its selected anchors, and the focused accessibility node +/// after each Tab. +type Reached = (vectorcraft_geom::Rect, Vec<(usize, usize)>, Vec>); + +/// What the canvas does with a press-drag from the curve's third anchor under `tool`, then Tab presses. +fn press_and_tab(tool: &str, overlay: bool) -> Reached { + OVERLAY_MARKS.with(|on| on.set(overlay)); + let (mut app, curve) = canvas_app(); + app.select_tool(tool); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + canvas_frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + // The curve's third anchor, and a drag away from it. + let (from, to) = (xf.to_screen(Point::new(110.0, 40.0)), xf.to_screen(Point::new(130.0, 60.0))); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + canvas_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + canvas_frame(&mut app, &ctx, vec![button(from, true)]); + for i in 1..=5 { + canvas_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * (i as f32 / 5.0))]); + } + canvas_frame(&mut app, &ctx, vec![button(to, false)]); + let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let focused = (0..4) + .map(|_| { + let out = canvas_frame(&mut app, &ctx, vec![tab.clone()]); + let update = out.platform_output.accesskit_update.as_ref().expect("an accessibility tree"); + update.nodes.iter().find(|(id, _)| *id == update.focus).and_then(|(_, node)| node.label().map(str::to_owned)) + }) + .collect(); + OVERLAY_MARKS.with(|on| on.set(false)); + let st = app.session.active().unwrap(); + let bounds = st.doc.bounds_of(&[curve], false).unwrap(); + let mut chosen: Vec<(usize, usize)> = st.selection.partial(curve).map(|set| set.iter().copied().collect()).unwrap_or_default(); + chosen.sort_unstable(); + (bounds, chosen, focused) +} + +// A press on a shown anchor reaches the tool and Tab from the canvas goes where it went with `BezierOverlay`: the +// Selection tool drags the whole path, Direct Selection drags the anchor, and Tab keeps the focus on the canvas. +#[test] +fn a_press_on_an_anchor_and_tab_reach_what_they_reached_with_the_overlay() { + for tool in ["selection", "directSelection"] { + let overlay = press_and_tab(tool, true); + let marks = press_and_tab(tool, false); + assert_eq!(marks, overlay, "{tool}"); + let (bounds, ..) = &marks; + assert!((bounds.x0 - 40.0).abs() > 1.0 || (bounds.x1 - 180.0).abs() > 1.0, "{tool}: the drag edited the curve: {bounds:?}"); + } +} + thread_local! { /// How many times the canvas built the selection's marks ([`SelectionMarks::build`]). pub(super) static MARKS_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 56657ef670..dcd87f71ee 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -1,17 +1,19 @@ use craft::behavior::CanvasView; use craft::behavior::{IconId, Mixed}; use craft::color_ui::ui::{PaintChip, PaintChipSize}; +use craft::i18n::WordSet as _; use craft::theme::{Srgba, Variant}; use craft::ui::buttons::{Button, IconButton}; use craft::ui::canvas::CanvasSpace; -use craft::ui::canvas_controls::{TaskBar, TaskBarGrip, TaskBarHang}; +use craft::ui::canvas_controls::{CanvasControlWords, TaskBar, TaskBarGrip, TaskBarHang}; use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::display::Text; use craft::ui::menu::PanelRow; use craft::ui::popover::Popover; use craft::ui::primitives::IconSpec; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; -use craft::ui::runtime::env::Label; +use craft::ui::runtime::env::{Env, Label, WordRows, WordsOverride, with_env}; +use craft::ui::style::{UiTokens, rgba_color}; use vectorcraft_doc::NodeKind; use vectorcraft_doc::text::TextKind; use vectorcraft_geom::{Point, Rect}; @@ -442,12 +444,43 @@ fn more_rows(offer: &Offer) -> Vec { ] } +/// VectorCraft's words for a canvas bar's More Options button, its grip (`grip`) and the rows the framework puts in +/// More Options (`hide`, and the commands `pin` and `reset`, named by their titles), over the framework's words. Outside +/// English, a word the language's catalog does not translate keeps the framework's translation. +pub(crate) fn bar_words(lang: crate::i18n::Lang, grip: &'static str, hide: &'static str, pin: &str, reset: &str) -> WordRows { + fn plain(lang: crate::i18n::Lang, english: &'static str) -> (&'static str, &'static str) { + (english, crate::i18n::tr(lang, english)) + } + fn command(lang: crate::i18n::Lang, id: &str) -> (&'static str, &'static str) { + let english = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map_or("", |c| c.1); + (english, crate::i18n::tr_id(lang, id, english)) + } + let words = [ + ("taskBar.more", plain(lang, "More Options")), + ("taskBar.move", plain(lang, grip)), + ("taskBar.hide", plain(lang, hide)), + ("taskBar.pin", command(lang, pin)), + ("taskBar.reset", command(lang, reset)), + ]; + words + .into_iter() + .filter(|(_, (english, shown))| !english.is_empty() && (lang == crate::i18n::Lang::EN || shown != english)) + .filter_map(|(id, (_, shown))| Some((CanvasControlWords::word(id)?, shown))) + .fold(WordRows::new(), |rows, (word, shown)| rows.row(word, shown)) +} + /// The Contextual Task Bar: a floating pill under the selection with the most likely next actions /// ([`offered`]). Its grip drags it anywhere on the canvas; unpinned it keeps that offset as it follows the /// selection, pinned it stays put ([`super::bar_place::KeyedPlace`]). More Options › Bar Actions turns each action /// and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]); with every one of them off, the /// bar still shows its grip and More Options, where they turn back on. Returns the bar's rect on screen. pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { + let words = bar_words(app.ui_language(), "Move Bar", "Hide Bar", "window.taskBar.pin", "window.taskBar.reset"); + with_env(ui, |env| env.words = Some(WordsOverride::Overlay(words)), |ui| shown_task_bar(app, ui, space)) +} + +/// The Contextual Task Bar of [`task_bar`], in a scope with the bar's words. +fn shown_task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { let offer = offered(app)?; let key = (app.session.active()?.uid, false); let mut local = app.ui.task_bar_place.for_key(key); @@ -456,12 +489,14 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpac let has_shape = offer.shape.is_some(); let mut run: Option<(&'static str, serde_json::Value)> = None; let mut show_swatches = false; + let mut layer = None; let shown = TaskBar::new(tl!("Contextual Task Bar"), &offer.anchor, Bind::bound(&mut local)) .grip(TaskBarGrip::Bar) .member_gap(Gap::Item) .hang_gap(TaskBarHang::ClearOfHandles) .more_rows(more_rows(&offer)) .show(ui, space.view.rect, |ui, _| { + layer = Some((ui.layer_id(), ui.opacity())); for (label, icon, cmd, params) in &offer.actions { if *cmd == TASK_BAR_FIDELITY { // The Smooth tool's Fidelity, labeled, sets the tool's option once a typed or stepped value is @@ -535,6 +570,9 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpac } }); let (rect, hide) = (shown.output.rect, shown.output.hide); + if let Some((layer, opacity)) = layer { + accent_outline(ui, layer, opacity, rect); + } if local != before { app.ui.task_bar_place.set(key, local); } @@ -567,6 +605,23 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpac Some(rect) } +/// Outlines the Contextual Task Bar at `rect` on its `layer` in the accent border color, on the corners of the floating +/// surface the bar paints and at its rect rounded to pixels, at the `opacity` the bar's members paint at while the bar +/// fades in or out. +/// +/// Temporary: craft-libs#4892 adds `TaskBar::edge(BarEdge::Accent)`, which draws this outline in place of the +/// surface's own border. Delete this function and set that edge on the bar once the craft-libs pin includes it. +fn accent_outline(ui: &Ui, layer: egui::LayerId, opacity: f32, rect: egui::Rect) { + let env = Env::of(ui); + let tokens = env.tokens.tokens(); + let stroke = egui::Stroke::new(tokens.stroke.thin, rgba_color(tokens.color.accent.border)); + let corners = UiTokens::corner(tokens.shape.radius.window); + let mut painter = ui.ctx().layer_painter(layer); + painter.set_opacity(opacity); + let rect = egui::emath::GuiRounding::round_to_pixels(rect, painter.pixels_per_point()); + painter.rect_stroke(rect, corners, stroke, egui::StrokeKind::Inside); +} + /// The controls the Contextual Task Bar shows after its actions: the Fill and Stroke chips, /// Recolor Artwork, and Lock or a basic shape's Shape Properties. #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 41d0e93837..e7fec25534 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -267,10 +267,12 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { } /// One headless canvas frame with `events` → the points it paints: the centres of circles and rectangles and the -/// points of lines and paths. +/// points of lines and paths. The selection's anchor marks paint as the shapes their mesh is made of. fn painted_points(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + super::selection::tests::RAW_MARKS.with(|on| on.set(true)); let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + super::selection::tests::RAW_MARKS.with(|on| on.set(false)); out.textures_delta.clear(); let mut points = vec![]; for shape in flat_shapes(out.shapes) { @@ -897,13 +899,12 @@ fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() { assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it"); } -/// A Selection tool move builds the menus' states again twice, in the frame of its press and in the frame of its -/// release, which commits the move. The frame the move begins in and the frames of its previews, which change the -/// document's revision, keep them. The menus are also built again when a process-wide catalog changes, so the fonts -/// and plug-ins are held steady against tests running alongside for the whole run, and the move runs again on a new -/// app, at most 20 times, until the other catalogs held still through it. -#[test] -fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() { +/// How many times each frame of `steps` builds the menus' states again, with the Selection tool and a 60 × 30 +/// rectangle at (100, 100) selected and the pointer resting over its middle (`steps` gets that point). The menus are +/// also built again when a process-wide catalog changes, so the fonts and plug-ins are held steady against tests +/// running alongside for the whole run, and the steps run again on a new app, at most 20 times, until the other +/// catalogs held still through them. +fn selection_tool_rebuilds(steps: impl Fn(Pos2, &craft::behavior::CanvasView) -> Vec>) -> (VectorcraftApp, Vec) { let fonts = vectorcraft_text::FontDb::global(); let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins()); let catalogs = || { @@ -920,33 +921,59 @@ fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() { let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap()["id"].as_u64().unwrap(); app.select_tool("selection"); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); - let (from, to) = (xf.to_screen(Point::new(130.0, 115.0)), xf.to_screen(Point::new(170.0, 135.0))); + let from = xf.to_screen(Point::new(130.0, 115.0)); app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); for _ in 0..2 { app_step(&mut app, &ctx, vec![]); } - let none = egui::Modifiers::NONE; - let mut steps = vec![vec![primary(from, true, none)]]; - steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))])); - steps.push(vec![primary(to, false, none)]); - steps.extend([vec![], vec![], vec![]]); let mut rebuilt = vec![]; - for events in steps { + for events in steps(from, &xf) { let before = app.menus.rebuilds; app_step(&mut app, &ctx, events); rebuilt.push(app.menus.rebuilds - before); } (app, rebuilt) }; - let (app, rebuilt) = (0..20) + (0..20) .find_map(|_| { let before = catalogs(); let out = run(); (catalogs() == before).then_some(out) }) - .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")); + .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")) +} + +/// A Selection tool move builds the menus' states again once, for the release that commits it. Its press lands on the +/// canvas, and the frame the move begins in and the frames of its previews, which change the document's revision, keep +/// them. +#[test] +fn a_selection_move_rebuilds_the_menus_for_its_release_only() { + let none = egui::Modifiers::NONE; + let (app, rebuilt) = selection_tool_rebuilds(|from, xf| { + let to = xf.to_screen(Point::new(170.0, 135.0)); + let mut steps = vec![vec![primary(from, true, none)]]; + steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))])); + steps.push(vec![primary(to, false, none)]); + steps.extend([vec![], vec![], vec![]]); + steps + }); assert_eq!(drawn_paths(&app), vec![Rect::new(140.0, 120.0, 200.0, 150.0)], "the drag moves the rectangle"); - assert_eq!(rebuilt, [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], "rebuilds in each frame: press, 8 moves, release, 3 idle"); + assert_eq!(rebuilt[..9].iter().sum::(), 0, "the press and the 8 moves keep the menus: {rebuilt:?}"); + assert_eq!(rebuilt.iter().sum::(), 1, "the release that commits the move rebuilds them once: {rebuilt:?}"); +} + +/// A click on the selected rectangle that leaves it where it was, and F20 pressed and released with no field or dialog +/// taking it and no command on it, change nothing the menus show: no frame builds the menus' states again. +#[test] +fn a_canvas_click_that_changes_nothing_keeps_the_menus() { + let none = egui::Modifiers::NONE; + let f20 = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: none }; + let (app, rebuilt) = selection_tool_rebuilds(|from, _| { + vec![vec![primary(from, true, none)], vec![primary(from, false, none)], vec![f20(true)], vec![f20(false)], vec![], vec![]] + }); + assert_eq!(drawn_paths(&app), vec![Rect::new(100.0, 100.0, 160.0, 130.0)], "the click leaves the rectangle where it was"); + assert_eq!(app.session.active().map(|d| d.selection.objects.len()), Some(1), "the rectangle stays selected"); + assert_eq!(rebuilt, [0; 6], "rebuilds in each frame: press, release, a key press and release, 2 idle"); } /// #6369: only the selection box remains over the temporary halftone, and the original @@ -4489,6 +4516,38 @@ fn plain(app: &VectorcraftApp, id: u64) -> String { } } +/// While the Type tool edits text, a click in the text and an arrow key, which move the caret without an edit, build +/// the menus' states again: the type rows read the caret's range. +#[test] +fn a_click_or_a_key_in_edited_text_rebuilds_the_menus() { + use egui::Event; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = crate::testing::ui_context(); + let id = start_typing(&mut app, &ctx); + typing_frame(&mut app, &ctx, vec![Event::Text("abc".into())]); + typing_frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(101.0, 100.0)); + let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let left = |pressed| Event::Key { key: egui::Key::ArrowLeft, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + let rebuilds = |app: &mut VectorcraftApp, steps: Vec>| { + let before = app.menus.rebuilds; + for events in steps { + typing_frame(app, &ctx, events); + } + app.menus.rebuilds - before + }; + let click = || vec![vec![Event::PointerMoved(at), button(true)], vec![button(false)]]; + // The first click puts the caret there; the second leaves the document's revision as it is. + rebuilds(&mut app, click()); + let revision = app.session.active().map(|d| d.revision); + assert!(rebuilds(&mut app, click()) > 0, "a click in the text"); + assert_eq!(app.session.active().map(|d| d.revision), revision, "the click changes no revision"); + assert!(rebuilds(&mut app, vec![vec![left(true)], vec![left(false)]]) > 0, "an arrow key in the text"); + assert_eq!(plain(&app, id), "abc", "neither edits the text"); + assert!(app.session.tool_wants_text(), "editing goes on"); +} + /// Starts editing new point type with the Type tool; returns its id. fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 8b2b35db16..34ef127f95 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -7,8 +7,8 @@ use craft::behavior::{CancelReason, CanvasView, Cursor, DropOperation, PointerKi use craft::keymap::{Chord, Key}; use craft::ui::canvas::ToolPath; use craft::ui::canvas::{ - Autoscroll, CanvasTool, Momentary, MomentaryShift, ToolAction, ToolClaims, ToolContext, ToolHost, ToolHostResponse, ToolKey, ToolPass, - ToolPointer, + Autoscroll, CanvasTool, Momentary, MomentaryCommands, MomentaryShift, ToolAction, ToolClaims, ToolContext, ToolHost, ToolHostResponse, ToolKey, + ToolPass, ToolPointer, }; use serde_json::json; use vectorcraft_engine::ViewInfo; @@ -615,6 +615,37 @@ impl CanvasTool for SessionTool<'_> { } } +/// Ends the held momentary command (Space's Hand, Cmd+Space's Zoom...) once none of the keys that were down when it +/// started is down, and returns the command still held. The shortcut board drops a queued release when the canvas +/// does not run on the frame the key goes up (a dialog or another tab in front). A hold that started with no key down +/// (automation) lasts until its release. +/// +/// Temporary: craft-libs#5056 ends the hold inside the tool host. Remove this function, [`note_momentary_keys`], +/// their calls and `CanvasCache::momentary_keys` once the craft-libs pin includes that change. +fn end_missed_momentary(ctx: &egui::Context, momentary: &mut Momentary, keys: &mut Vec) -> Option { + let held = momentary.held()?; + if keys.is_empty() { + return Some(held); + } + let down = craft::ui::runtime::keys::held(ctx); + if keys.iter().any(|key| down.contains(key)) { + return Some(held); + } + momentary.fired(held, craft::ui::runtime::commands::FirePhase::Release); + keys.clear(); + None +} + +/// Notes the keys down when a momentary command starts (or changes), for [`end_missed_momentary`]; `before` is the +/// command held before the tool host's pass. +fn note_momentary_keys(ctx: &egui::Context, before: Option, momentary: &Momentary, keys: &mut Vec) { + match momentary.held() { + None => keys.clear(), + Some(held) if before != Some(held) => *keys = craft::ui::runtime::keys::held(ctx), + Some(_) => {} + } +} + /// Runs the tool host on `tool` with the app's momentary set, which the app keeps across passes. A finger, once a pen /// has been seen, only navigates (palm rejection). fn host_run(app: &mut VectorcraftApp, ui: &Ui, pass: &ToolPass, tool: &mut dyn CanvasTool) -> ToolHostResponse { @@ -622,7 +653,9 @@ fn host_run(app: &mut VectorcraftApp, ui: &Ui, pass: &ToolPass, tool: &mut dyn C let mut momentary = app.canvas.momentary.take().unwrap_or_else(|| Momentary::new(options).shift(MomentaryShift::RotateView)); momentary.set_options(options); momentary.hand_selected(app.session.tool_id() == "hand"); + let before = end_missed_momentary(ui.ctx(), &mut momentary, &mut app.canvas.momentary_keys); let response = ToolHost::new().momentary(&mut momentary).navigates(crate::touch::finger_navigates_only()).run(ui, pass, tool); + note_momentary_keys(ui.ctx(), before, &momentary, &mut app.canvas.momentary_keys); app.canvas.momentary = Some(momentary); response } @@ -656,6 +689,17 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too if ui.ctx().current_pass_index() == 0 && view_press { app.session.tool_press_elsewhere(); } + // A press on the canvas, and a key while the canvas or nothing has the focus, change what the menus show only through + // the document, the tool or a command, which the menus' state key reads, so the key leaves them out + // (`menus::model::last_press`). + let presses: Vec = + ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerButton { pos, .. } = e { Some(*pos) } else { None }).collect()); + if !presses.is_empty() && presses.iter().all(|&at| over(Some(at)) && ui.ctx().layer_id_at(at) == Some(ui.layer_id())) { + app.canvas.pressed_at = Some(ui.input(|i| i.time)); + } + if ui.ctx().memory(|m| m.focused()).is_none_or(|id| id == pass.id) { + app.canvas.keys_at = Some(ui.input(|i| i.time)); + } let view_info = app.view_info(); let mut picked = ToolHostResponse::default(); let mut response = if crate::dialogs::recolor::edit_tab::with_theme_pick(app, |app, tool| picked = host_run(app, ui, pass, tool)) { @@ -744,9 +788,14 @@ fn host_run_session(tool: &mut SessionTool<'_>, ui: &Ui, pass: &ToolPass) -> Too let mut momentary = app.canvas.momentary.take().unwrap_or_else(|| Momentary::new(options).shift(MomentaryShift::RotateView)); momentary.set_options(options); momentary.hand_selected(app.session.tool_id() == "hand"); + let mut keys = std::mem::take(&mut app.canvas.momentary_keys); drop(app); + let before = end_missed_momentary(ui.ctx(), &mut momentary, &mut keys); let response = ToolHost::new().momentary(&mut momentary).navigates(crate::touch::finger_navigates_only()).run(ui, pass, tool); - tool.app().canvas.momentary = Some(momentary); + note_momentary_keys(ui.ctx(), before, &momentary, &mut keys); + let mut app = tool.app(); + app.canvas.momentary = Some(momentary); + app.canvas.momentary_keys = keys; response } @@ -771,6 +820,9 @@ fn show_overlays(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass, view_in if app.ui.view.live_paint_gaps { extra.extend(super::marks::live_paint_gap_overlays(app)); } + if app.ui.view.curvature_comb { + extra.extend(super::marks::curvature_comb_overlays(app, space.view.zoom)); + } } super::overlays::show(app, ui, &space, &list, &extra); } diff --git a/crates/ui-egui/src/canvas/tool_adapter/tests.rs b/crates/ui-egui/src/canvas/tool_adapter/tests.rs index 1ff48b983a..a9c60d1089 100644 --- a/crates/ui-egui/src/canvas/tool_adapter/tests.rs +++ b/crates/ui-egui/src/canvas/tool_adapter/tests.rs @@ -48,6 +48,69 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec out.textures_delta.clear(); } +/// A frame where the canvas does not run, as with a dialog or another tab in front. +fn frame_without_canvas(ctx: &egui::Context, events: Vec) { + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |_| {}); + out.textures_delta.clear(); +} + +fn space_key(pressed: bool) -> egui::Event { + egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE } +} + +/// Space let go while the canvas is away for long enough that the shortcut board drops its queued release (two +/// frames) ends the momentary Hand at the canvas's next pass, and Space still held across such frames keeps it. The +/// Rectangle tool runs through the session's tool, and the Zoom tool through the framework's. +#[test] +fn space_let_go_while_the_canvas_is_away_ends_the_momentary_hand() { + for tool in ["rectangle", "zoom"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool(tool); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![space_key(true)]); + frame(&mut app, &ctx, vec![]); + assert!(view_tool_held(&app), "{tool}: Space down holds the Hand"); + frame_without_canvas(&ctx, vec![]); + frame_without_canvas(&ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert!(view_tool_held(&app), "{tool}: Space still down keeps the Hand across frames without the canvas"); + frame_without_canvas(&ctx, vec![space_key(false)]); + frame_without_canvas(&ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert!(!view_tool_held(&app), "{tool}: Space let go while the canvas was away ends the Hand"); + } +} + +/// A momentary Hand whose key is down at another physical position than the one its shortcut names (another keyboard +/// layout) stays held across passes while that key is down, and ends once it goes up while the canvas is away. +#[test] +fn a_momentary_hand_from_another_layout_position_lasts_while_its_key_is_down() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("rectangle"); + let ctx = crate::testing::ui_context(); + let key = |pressed| egui::Event::Key { + key: egui::Key::Space, + physical_key: Some(egui::Key::Backtick), + pressed, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![key(true)]); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert!(view_tool_held(&app), "the key still down keeps the Hand"); + frame_without_canvas(&ctx, vec![key(false)]); + frame_without_canvas(&ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert!(!view_tool_held(&app), "the key let go while the canvas was away ends the Hand"); +} + /// With the Live Paint Bucket and the pointer still, an Alt-only pass changes the cursor and back. #[test] fn bucket_modifier_only_hover_updates_the_visible_cursor() { diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 82dba96e51..985646a065 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -285,10 +285,15 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui) { fn opacity_field(app: &mut VectorcraftApp, ui: &mut Ui, opacity: f32, selected: bool) { let label = tl!("Opacity:"); let (mut link, mut typed) = (false, None); + let target = crate::panels::transparency_target(app); group(ui, rank::OPACITY, |ui| { Field::new(label).side(SideLabel::new().link().scrub(true)).show(ui, |ui, _| { - let number = - NumberField::new(label, Bind::given(Some(f64::from(opacity) * 100.0))).range(0.0..=100.0).unit("%").scrub_by_label().show(ui); + let number = NumberField::new(label, Bind::given(Some(f64::from(opacity) * 100.0))) + .range(0.0..=100.0) + .unit("%") + .scrub_by_label() + .edit_target(&target) + .show(ui); link |= number.link; typed = number.edit.events.committed().copied().flatten().or(typed); }); diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index b7446defb4..e4a9e91d82 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -771,6 +771,20 @@ fn date_time_now() -> (String, u64) { /// it are translated. pub(crate) fn status_message(app: &VectorcraftApp) -> String { let status = app.ui.status.as_str(); + if let Some((original, notice)) = &app.ui.status_plugin_event + && original == status + { + use vectorcraft_engine::plugin_events::Failure; + let text = match ¬ice.failure { + Some(Failure::Handler { error }) => crate::i18n::fmt(&crate::i18n::msg(Failure::HANDLER), &[("event", notice.event), ("error", error)]), + Some(Failure::EventsOff { count }) => { + let template = if *count == 1 { Failure::EVENTS_OFF_ONE } else { Failure::EVENTS_OFF_OTHER }; + crate::i18n::fmt(&crate::i18n::msg(template), &[("n", &count.to_string())]) + } + None => notice.text.clone(), + }; + return format!("{}: {text}", notice.name); + } let is = |before: &str, kept: &str, after: &str| status.strip_prefix(before).and_then(|rest| rest.strip_suffix(after)) == Some(kept); if let Some((before, kept, after)) = app.session.script_authored_failure() && is(&before, kept, &after) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 79d4371f47..fb3032d235 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -631,7 +631,7 @@ fn the_status_bar_stands_still_while_its_readouts_change() { ] { let (x_value, y_value) = { let mut app = bar.app(); - app.perf = crate::Perf { render_ms: render, frame_ms: frame, fps }; + app.perf = crate::Perf { render_ms: render, frame_ms: frame, fps, ..Default::default() }; app.hover_doc = Some(vectorcraft_geom::Point::new(x, y)); (app.session.general_unit().readout(x), app.session.general_unit().readout(y)) }; @@ -3163,6 +3163,37 @@ fn the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners() { assert_eq!((0..4).map(|k| lc.kind(k)).collect::>(), [CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Round]); } +/// An unfinished Opacity expression in the Control bar belongs to the object it was typed for: after another object +/// with the same opacity is selected, the field shows that object's value, and further typing starts a new value +/// instead of finishing the old expression. +#[test] +fn the_control_bar_opacity_drops_an_unfinished_value_when_the_selection_changes() { + use egui::{Key, Modifiers}; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 50, "width": 40, "height": 40})).unwrap()["id"].clone() + }; + let (a, b) = (rect(&mut app, 20.0), rect(&mut app, 200.0)); + app.run("transparency.set", json!({"ids": [a, b], "opacity": 50})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let opacity = |bar: &crate::tests::panel_harness::Panel, id: &serde_json::Value| { + bar.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().opacity + }; + let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar); + bar.room(egui::vec2(2400.0, 300.0)).frame(); + bar.click_role("Opacity:", Role::SPIN_BUTTON); + bar.key(Key::A, Modifiers::COMMAND); + bar.type_text("20+"); + bar.app().run("select.set", json!({"ids": [b]})).unwrap(); + bar.frame(); + assert_eq!(bar.value_role("Opacity:", Role::SPIN_BUTTON).as_deref(), Some("50%"), "the field shows the other object's value"); + bar.type_text("1"); + bar.key(Key::Enter, Modifiers::NONE); + assert_eq!((opacity(&bar, &a), opacity(&bar, &b)), (0.5, 0.01), "the typing gives the other object 1%, not 20+1"); +} + /// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard /// controls while it has room, and the Distribute buttons for two or more selected artboards with /// Align to Artboard and three or more with Align to Selection. A diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 7495e0ed02..158cf852f8 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -153,6 +153,7 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { } let mut dialogs = app.dialogs().map_or_else(|| json!([]), |dialogs| dialogs.with(|host| craft::automation::dialogs::inspect(host))); crate::dialogs::javascript_files::show_selected(app, &mut dialogs); + crate::dialogs::find_replace::show_action(app, &mut dialogs); // The Simplify or Smooth slider over the canvas, listed first: `"top"` names a hosted dialog open with it. if let (Some(open), Some(strip)) = (dialogs.as_array_mut(), crate::dialogs::simplify_slider::inspected(app)) { open.insert(0, strip); @@ -1463,6 +1464,10 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val if let Some(r) = crate::dialogs::script_window::dialog_method(app, method, ¶ms) { return wrap(r); } + // Find and Replace presses the button its `action` field names and stays open. + if let Some(r) = crate::dialogs::find_replace::dialog_method(app, ctx, method, ¶ms) { + return wrap(r); + } // `ui.dialog.set {action}` answers the dialog after setting its fields: the app's own key, which the // framework's method does not take. let action = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { None }; @@ -1474,6 +1479,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val }; let pdf = app.save_pdf.as_ref().map(|open| open.id).filter(|_| method == "ui.dialog.set"); let reply = dialogs.with(|host| { + // A Color Picker whose Recolor Artwork row changed while it was open refuses OK. + if method == "ui.dialog.confirm" + && let Err(reason) = crate::dialogs::color_picker::check_confirm(app, host, ¶ms) + { + return Some(Err(reason)); + } // The answer goes to the dialog the fields went to, even when setting them opens another over it. if answer.is_some() && params["dialog"] == "top" @@ -1486,6 +1497,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val { crate::dialogs::effect::normalize_set_mode(app, id, &mut params); } + // A set with `action: confirm` on such a picker changes none of its fields. + if answer == Some("ui.dialog.confirm") + && let Err(reason) = crate::dialogs::color_picker::check_confirm(app, host, ¶ms) + { + return Some(Err(reason)); + } let sets = params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog")); let set = if answer.is_none() || sets { // A Save PDF settings object keeps the options it leaves out. @@ -1498,6 +1515,11 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val }; match (set, answer) { (Some(Ok(_)), Some(answer)) => { + if answer == "ui.dialog.confirm" + && let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms) + { + crate::dialogs::print::prepare_confirm(app, host, id); + } craft::automation::dialogs::dialog_method(host, ctx, answer, &json!({ "dialog": params["dialog"] })) } // A set answers with the dialog it set, `{id, parent, key, fields}`, as production did. diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index f4c1d52986..a0554f26bb 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -45,3 +45,40 @@ fn every_cursor_icon_the_app_names_is_in_its_set() { } } } + +/// Painted cursors use the SVG's alpha as ink. Drawing the vent in white makes it solid ink. +#[test] +fn the_painted_pen_nibs_keep_their_breather_holes() { + use craft::ui::primitives::{painted_image, register_app_icons}; + use craft::ui::runtime::env::Env; + use craft::ui::style::rgba_color; + + register_app_icons(&crate::icons::APP_ICONS); + register_app_icons(&CURSOR_ICONS); + crate::testing::ui_context() + .run_ui(Default::default(), |ui| { + let env = Env::of(ui); + let tokens = env.tokens.tokens(); + let ink = rgba_color(tokens.color.overlay.cursor); + let is_ink = |px: &[u8]| px[3] >= 240 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8); + let scale = 4.0; + let from_art_units = tokens.size.icon.md * scale / 24.0; + for c in [Cursor::Pen, Cursor::PenConvert, Cursor::PenJoin, Cursor::Curvature] { + let cb::Cursor::Painted(painted @ PaintedCursor::Tool { hotspot, .. }) = tool_cursor(c) else { + panic!("{c:?} must have painted tool art"); + }; + let image = painted_image(&env, &painted, scale).expect("the cursor fits in its bitmap"); + let [hx, hy] = image.hotspot.map(f32::from); + let pixel = |x: f32, y: f32| { + let x = (hx + (x - hotspot.x) * from_art_units).round() as usize; + let y = (hy + (y - hotspot.y) * from_art_units).round() as usize; + let i = (y * usize::from(image.size[0]) + x) * 4; + &image.rgba[i..i + 4] + }; + assert!(is_ink(pixel(9.5, 13.2)), "{c:?}: the nib body is ink"); + assert!(!is_ink(pixel(6.62, 12.86)), "{c:?}: the vent must break up the ink"); + } + }) + .textures_delta + .clear(); +} diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 6e29fc182f..d8ca17ce8f 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -5,7 +5,9 @@ //! `datasets`), `datasetFileNaming`, `folder`, `includeSubdirs`, `destination` (`none`, //! `saveAndClose` or `folder`), `destinationFolder`, `overrideOpen`, `overrideSave`, //! `overrideExport` and `stopOnError`. OK plays the action; a source or destination folder left -//! empty, or Data Sets without a document, is an error and the dialog stays open. +//! empty, or Data Sets without a document, is an error and the dialog stays open. After the batch +//! the status bar gives the counts, and when a file or data set failed, a message lists each one +//! with its error. use std::hash::Hash; use std::sync::Arc; @@ -293,17 +295,66 @@ impl ActionDialog for BatchDialog { return Err("open a document with data sets".into()); } let result = app.replay("action.batch", params(&fields, &a.name, commands))?; - let count = result["count"].as_u64().unwrap_or(0); - let failed = result["failed"].as_u64().unwrap_or(0); - if failed > 0 { - app.status(format!("Batch: {count} processed, {failed} failed")); - } else { - app.status(format!("Batch: {count} processed")); - } + report(app, &result); Ok(()) } } +/// How many failed files or data sets the message after a batch lists; the rest are counted. +const LISTED_FAILURES: usize = 10; + +/// How many characters of a failed file's or data set's error the message shows; a longer error +/// ends in "…". +const ERROR_CHARS: usize = 300; + +/// Says in the status bar how many files or data sets the batch `result` processed and how many +/// failed. When any failed, a message lists each failed one with its error ([`failure_lines`]). +fn report(app: &mut VectorcraftApp, result: &Value) { + let count = result["count"].as_u64().unwrap_or(0); + let failed = result["failed"].as_u64().unwrap_or(0); + if failed == 0 { + app.status(format!("Batch: {count} processed")); + return; + } + let summary = format!("Batch: {count} processed, {failed} failed"); + app.status(summary.clone()); + super::confirm::tell(app, &crate::i18n::msg(&summary), &failure_lines(result).join("\n")); +} + +/// One line for each failed file or data set of the batch `result`, in the order the batch ran +/// them: its path or data set name, as it is, and its error in the interface language. The first +/// [`LISTED_FAILURES`] are listed and a line counts the rest; a line says when Stop on Errors +/// ended the batch. +fn failure_lines(result: &Value) -> Vec { + let failures: Vec<(&str, &str)> = result["processed"] + .as_array() + .into_iter() + .flatten() + .filter_map(|row| { + let error = row["error"].as_str()?; + Some((row["path"].as_str().or_else(|| row["dataset"].as_str()).unwrap_or_default(), error)) + }) + .collect(); + let mut lines: Vec = + failures.iter().take(LISTED_FAILURES).map(|(source, error)| format!("{source}: {}", shortened(&crate::i18n::msg(error)))).collect(); + let more = failures.len().saturating_sub(LISTED_FAILURES); + if more > 0 { + lines.push(crate::i18n::tn(more as u64, "and {n} more", "and {n} more")); + } + if result["stopped"] == true { + lines.push(crate::i18n::t("Stop on Errors ended the batch at this error.").to_owned()); + } + lines +} + +/// `text` cut to [`ERROR_CHARS`] characters, with "…" at the end when it was cut. +fn shortened(text: &str) -> String { + match text.char_indices().nth(ERROR_CHARS) { + Some((at, _)) => format!("{}…", &text[..at]), + None => text.to_owned(), + } +} + /// A row that picks one of `entries` for `value`. fn select_row(ui: &mut Ui, name: &str, value: &mut T, entries: &[Entry]) { Field::new(label(name)).show(ui, |ui, _| { @@ -535,6 +586,116 @@ mod tests { assert!(!app.session.replaying()); } + /// Runs the action "Draw" as a batch from the dialog with `fields`, pressing OK in a panel, and + /// gives the panel after the frames that close the dialog and show what follows it. + fn batch_in_panel(app: VectorcraftApp, fields: &[(&str, Value)]) -> Panel { + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + open(&mut panel.app(), 0, 0).unwrap(); + set_fields(&panel.app(), fields); + panel.frame(); + panel.click("OK"); + for _ in 0..4 { + panel.frame(); + } + assert!(!panel.app().dialogs().unwrap().with(|host| host.is_open::())); + panel + } + + /// The message the batch left: its text and its lines, one for each failed source. + fn told(panel: &Panel) -> Option<(String, Vec)> { + panel.app().told.0.last().map(|(message, detail)| (message.clone(), detail.lines().map(str::to_owned).collect())) + } + + /// An app holding the action "Draw" with `steps` and a document with the data sets `names`. + fn with_data_sets(steps: Vec, names: &[String]) -> VectorcraftApp { + let mut app = app_with(steps); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + for name in names { + app.run("dataset.new", json!({"name": name})).unwrap(); + } + app + } + + /// A step that fails on every document: Align with nothing selected. + fn failing_align() -> ActionStep { + ActionStep::new("object.align", json!({})) + } + + #[test] + fn a_file_that_fails_is_listed_with_its_error() { + let folder = std::env::temp_dir().join(format!("vc-ui-batch-failed-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + let svg = r#""#; + std::fs::write(folder.join("a.svg"), svg).unwrap(); + std::fs::write(folder.join("b.svg"), "not an svg").unwrap(); + let app = app_with(vec![ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))]); + let fields = [("folder", json!(folder.to_string_lossy())), ("destination", json!("none")), ("stopOnError", json!(false))]; + let panel = batch_in_panel(app, &fields); + let _ = std::fs::remove_dir_all(&folder); + assert_eq!(panel.app().ui.status, "Batch: 2 processed, 1 failed"); + let (message, lines) = told(&panel).expect("a message lists the failed file"); + assert_eq!(message, "Batch: 2 processed, 1 failed"); + let bad = folder.join("b.svg").to_string_lossy().into_owned(); + assert_eq!(lines.len(), 1, "{lines:?}"); + let error = lines[0].strip_prefix(&format!("{bad}: ")).unwrap_or_else(|| panic!("{lines:?}")); + assert!(!error.is_empty() && !error.contains("action step"), "the open's own error: {lines:?}"); + assert!(panel.texts().iter().any(|(text, _)| text.contains(&lines[0])), "the message shows the line"); + } + + #[test] + fn a_data_set_that_fails_is_listed_with_its_step_error() { + let names = ["Alpha".to_string(), "Beta".to_string()]; + for (stop, listed) in [(false, vec!["Alpha", "Beta"]), (true, vec!["Alpha"])] { + let app = with_data_sets(vec![failing_align()], &names); + let panel = batch_in_panel(app, &[("source", json!("datasets")), ("destination", json!("none")), ("stopOnError", json!(stop))]); + let (message, lines) = told(&panel).expect("a message lists the failed data sets"); + assert_eq!(message, format!("Batch: {} processed, {} failed", listed.len(), listed.len())); + for (line, name) in lines.iter().zip(&listed) { + assert!(line.starts_with(&format!("{name}: action step 1 (`object.align`) failed: ")), "{lines:?}"); + } + let stopped = lines.last().is_some_and(|line| line == "Stop on Errors ended the batch at this error."); + assert_eq!(lines.len(), listed.len() + usize::from(stop), "{lines:?}"); + assert_eq!(stopped, stop, "{lines:?}"); + } + } + + #[test] + fn many_failures_list_the_first_and_count_the_rest() { + let names: Vec = (1..=25).map(|n| format!("Set {n}")).collect(); + let app = with_data_sets(vec![failing_align()], &names); + let panel = batch_in_panel(app, &[("source", json!("datasets")), ("destination", json!("none")), ("stopOnError", json!(false))]); + let (message, lines) = told(&panel).expect("a message lists the failed data sets"); + assert_eq!(message, "Batch: 25 processed, 25 failed"); + assert_eq!(lines.len(), LISTED_FAILURES + 1, "{lines:?}"); + for (line, name) in lines[..LISTED_FAILURES].iter().zip(&names) { + assert!(line.starts_with(&format!("{name}: action step 1")), "{lines:?}"); + } + assert_eq!(lines[LISTED_FAILURES], "and 15 more"); + } + + #[test] + fn a_batch_without_failures_shows_only_the_counts() { + let step = ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})); + let app = with_data_sets(vec![step], &["Alpha".to_string()]); + let panel = batch_in_panel(app, &[("source", json!("datasets")), ("destination", json!("none"))]); + assert_eq!(panel.app().ui.status, "Batch: 1 processed"); + assert!(told(&panel).is_none()); + assert!(!panel.app().any_dialog_open()); + } + + #[test] + fn a_long_error_is_cut_short() { + let long = "é".repeat(ERROR_CHARS + 50); + let result = json!({ + "processed": [{"path": "/in/a.svg", "error": long}, {"path": "/in/b.svg"}, {"dataset": "Alpha", "error": "short"}], + "count": 3, "failed": 2, "stopped": false, + }); + let lines = failure_lines(&result); + assert_eq!(lines, [format!("/in/a.svg: {}…", "é".repeat(ERROR_CHARS)), "Alpha: short".to_string()]); + assert_eq!(shortened(&"é".repeat(ERROR_CHARS)), "é".repeat(ERROR_CHARS), "an error of the length is kept whole"); + } + #[test] fn data_set_naming_params_follow_dialog_choice() { let mut fields = BatchFields::default(); diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index dd09594490..5812e37270 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -27,7 +27,7 @@ use std::borrow::Cow; use std::sync::{Arc, Weak}; -use craft::behavior::{Mixed, Selection, SelectionChange, keyed}; +use craft::behavior::{EditEvent, EditEvents, Mixed, Selection, SelectionChange, keyed}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; @@ -317,8 +317,20 @@ impl BulletsDialog { fn level(&mut self, ui: &mut Ui) { let value = self.fields.get("listLevel").and_then(Value::as_f64); let edit = NumberField::new(tl!("Level:"), Bind::given(value)).range(1.0..=LIST_LEVELS as f64).commit_decimals(0).show(ui); - if let Some(Some(v)) = edit.value().copied() { - self.fields.insert("listLevel".into(), json!(v)); + self.land("listLevel", &edit.edit.events); + } + + /// Sets `key` to the number its field's `events` leave: the number entered or the number a canceled edit + /// restores, and no number where a canceled edit restores a blank field. + fn land(&mut self, key: &str, events: &EditEvents>) { + match events.landed() { + Some(Some(v)) => { + self.fields.insert(key.into(), json!(v)); + } + Some(None) if matches!(events.ended(), Some(EditEvent::Cancel { .. })) => { + self.fields.remove(key); + } + _ => {} } } @@ -393,9 +405,7 @@ impl BulletsDialog { .enabled(on == Some(true)) .id_salt("startNumber") .show(ui); - if let Some(Some(v)) = edit.value().copied() { - self.fields.insert("startNumber".into(), json!(v)); - } + self.land("startNumber", &edit.edit.events); }); } @@ -415,9 +425,7 @@ impl BulletsDialog { fn indent(&mut self, ui: &mut Ui, key: &'static str, label: &'static str) { let value = self.fields.get(key).and_then(Value::as_f64); let edit = NumberField::length(label, Bind::given(value), self.lengths).range(INDENTS).show(ui); - if let Some(Some(v)) = edit.value().copied() { - self.fields.insert(key.into(), json!(v)); - } + self.land(key, &edit.edit.events); } } @@ -1239,4 +1247,41 @@ mod tests { ok(&mut app); assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Dot).at_level(3))); } + + /// Leaving Level, Start at or an indent on text that is not a number cancels the typing: the field goes back to + /// the number it had before it, or to blank where the paragraphs differ, and so does the type. + #[test] + fn a_canceled_number_edit_restores_the_field_and_the_type() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (mut app, id) = app(); + app.run("text.setFormat", json!({"number": "arabic"})).unwrap(); + app.run("text.setFormat", json!({"ids": [id], "leftIndent": 30, "start": 0, "end": 0})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1800.0)); + panel.app().run("ui.bulletsAndNumbering", json!({})).unwrap(); + panel.frame(); + set(&mut panel.app(), "startAt", json!(true)); + panel.frame(); + assert!(fields(&panel.app()).get("leftIndent").is_none(), "the paragraphs' left indents differ: blank"); + let state = |panel: &Panel| { + let app = panel.app(); + (sent(&app), first(&app, id)) + }; + for name in ["Level:", "Start at:", "Left Indent:", "First Line Indent:"] { + let before = state(&panel); + panel.click_role(name, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("7"); + assert_ne!(state(&panel).0, before.0, "typing into {name} proposes a number"); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel.app()), "leaving {name} keeps the dialog open"); + assert_eq!(state(&panel), before, "leaving {name} on text that is not a number restores it"); + } + } } diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 110c124717..f508f52904 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -93,8 +93,13 @@ impl Adjust { { old.preview.cancel(app); } + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); let dialog = HostedParamDialog::new(&ctx, self.kind, (self.initial)(), move |fields| { - ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true) + let dialog = ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }); let id = host::open_held(app, dialog, move |app, answer| self.commit(app, answer)).ok_or(NO_WINDOW)?; *(self.slot)(&mut app.color_dialogs) = Some(Open { id, document, preview: LivePreview::default() }); diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 6863ee28a7..d9d2fba515 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -8,7 +8,8 @@ //! //! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog //! and answers the row with its OK. Every picker has the Color Swatches view; one over Recolor -//! Artwork shows the library that Limit to Library limits to. The OK for a Save for Web colour table cell shifts the cell's +//! Artwork shows the library that Limit to Library limits to and the document's swatches as they +//! were before its preview, and its OK on a global or spot swatch gives the row that swatch. The OK for a Save for Web colour table cell shifts the cell's //! colour in the table instead ([`super::save_for_web::take_palette_pick`]). //! //! Fields agents set with `ui.dialog.set`: the framework picker's (`color`, `mode`, `webColors`, @@ -19,12 +20,13 @@ use std::sync::Arc; use craft::cms::Profile; use craft::cms::convert::CmykConverter; -use craft::color_ui::ui::{ColorPickerDialog, PickedColor, PickerLibrary, PickerSwatches}; +use craft::color_ui::ui::{ColorPickerDialog, PickedColor, PickedSwatch, PickerLibrary, PickerSwatches}; use craft::theme::Srgba; use craft::ui::dialog::{DialogId, DialogResult}; use craft::ui::runtime::env::Label; use serde_json::{Value, json}; use vectorcraft_color::cms; +use vectorcraft_color::recolor::ColorKey; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::ColorMode; use vectorcraft_engine::cmd::color_value; @@ -81,6 +83,11 @@ pub(crate) struct Open { pub keep: bool, /// The live preview of its colour on the target. pub preview: LivePreview, + /// What its Color Swatches view listed when it opened, over Recolor Artwork; empty otherwise. + pub view: ViewSwatches, + /// The Recolor Artwork row it opened for, as its `from` colors and its `to` color; `None` + /// otherwise. OK answers nothing when the row at its key no longer matches. + pub row: Option, } /// The records of the colour area's open dialogs: one holder, so the app has one field for them. @@ -127,23 +134,91 @@ pub(crate) fn open_picker(app: &VectorcraftApp) -> Option { /// The document's swatches and the swatch libraries as the picker's Color Swatches view: solid /// colours only, tints as their colour. pub(crate) fn swatch_view(app: &VectorcraftApp) -> PickerSwatches { - let solid = |swatches: &[vectorcraft_color::Swatch]| -> Vec<(Label, Srgba)> { - swatches.iter().filter_map(|s| Some((Label::from(s.name.clone()), srgba(&s.paint.color()?)))).collect() + swatch_view_of(app, false).0 +} + +/// [`swatch_view`], with the document's swatches as they were before the preview when +/// `before_preview` (over Recolor Artwork, whose `recolor.apply` reads them so), and the libraries +/// it lists, which a pick's place in the view is read against. +fn swatch_view_of(app: &VectorcraftApp, before_preview: bool) -> (PickerSwatches, ViewSwatches) { + let listed = view_libraries(app, before_preview); + let libraries = listed + .iter() + .map(|(_, name, swatches)| { + let cells = swatches.iter().filter_map(|s| Some((Label::from(s.name.clone()), srgba(&s.paint.color()?)))).collect(); + PickerLibrary::new(name.clone(), cells) + }) + .collect(); + let kept = listed.into_iter().map(|(key, _, swatches)| (key, swatches)).collect(); + (PickerSwatches::new(libraries, tl!("Open a document to see its swatches.")), kept) +} + +/// The libraries a picker's Color Swatches view lists, as it opened: each with its Limit to Library +/// key and its colour swatches, one for one with the view's cells. +pub(crate) type ViewSwatches = Vec<(String, Vec)>; + +/// The libraries of [`swatch_view_of`] in its order, each with its Limit to Library key, its name +/// and its colour swatches (the swatches the view lists, one for one). +fn view_libraries(app: &VectorcraftApp, before_preview: bool) -> Vec<(String, Label, Vec)> { + let solid = |swatches: &mut dyn Iterator| -> Vec { + swatches.filter(|s| s.paint.color().is_some()).cloned().collect() }; - let mut libraries = Vec::new(); - if let Some(st) = app.session.active() { - let all: Vec<_> = st.doc.swatches.iter().chain(st.doc.swatch_groups.iter().flat_map(|g| g.swatches.iter())).cloned().collect(); - libraries.push(PickerLibrary::new(Label::from(DOCUMENT_SWATCHES), solid(&all))); - } else { - libraries.push(PickerLibrary::new(Label::from(DOCUMENT_SWATCHES), Vec::new())); - } + let doc = app.session.active().map(|st| match &st.interaction { + Some(it) if before_preview => &it.doc, + _ => &st.doc, + }); + let mut libraries = vec![( + swatchlib::DOCUMENT_SWATCHES.to_string(), + Label::from(DOCUMENT_SWATCHES), + doc.map(|doc| solid(&mut doc.swatches.iter().chain(doc.swatch_groups.iter().flat_map(|g| g.swatches.iter())))).unwrap_or_default(), + )]; for lib in colour_libraries(app) { let swatches = swatchlib::library(&app.session, &lib.id) - .map(|(_, l)| solid(&l.swatches.iter().chain(l.groups.iter().flat_map(|g| g.swatches.iter())).cloned().collect::>())) + .map(|(_, l)| solid(&mut l.swatches.iter().chain(l.groups.iter().flat_map(|g| g.swatches.iter())))) .unwrap_or_default(); - libraries.push(PickerLibrary::new(Label::from(lib.name.clone()), swatches)); + libraries.push((lib.id.clone(), Label::from(lib.name.clone()), swatches)); } - PickerSwatches::new(libraries, tl!("Open a document to see its swatches.")) + libraries +} + +/// The swatch a Color Picker over Recolor Artwork answered with: `Some((swatch, color))` for a +/// global or spot swatch that is not a tint of another one (`{name, library}` and its colour, in its +/// own model), `None` for another swatch; outer `None` when the view has no such swatch. `view` is +/// what the picker's view listed when it opened. +fn picked_row_swatch(app: &mut VectorcraftApp, view: &ViewSwatches, picked: PickedSwatch) -> Option> { + let (key, swatches) = view.get(picked.library)?; + let s = swatches.get(picked.index)?; + let keeps = (s.global || s.spot) && matches!(s.paint, Paint::Solid { swatch: None, .. }); + let color = s.paint.color()?; + if keeps + && swatches[..picked.index].iter().any(|w| { + w.name == s.name + && matches!(w.paint, Paint::Solid { swatch: None, .. }) + && w.paint.color().is_some_and(|c| ColorKey::of(&c) == ColorKey::of(&color)) + }) + { + app.status(tl!("The swatch could not be kept because another swatch has its name and color.")); + return Some(None); + } + Some(keeps.then(|| (json!({"name": s.name, "library": key}), color))) +} + +/// Where the first swatch `name` of library `key` with colour `c` (compared as colour keys, as +/// `recolor.apply` finds it) stands in `view`, for a picker reopened over a Recolor Artwork row +/// that has it. +fn view_place(app: &VectorcraftApp, view: &ViewSwatches, name: &str, key: &str, c: &Color) -> Option { + let key = if key == swatchlib::DOCUMENT_SWATCHES { key.to_string() } else { swatchlib::library(&app.session, key)?.0.id }; + view.iter().enumerate().find_map(|(li, (k, swatches))| { + if k != &key { + return None; + } + let fits = |s: &vectorcraft_color::Swatch| { + s.name == name + && matches!(s.paint, Paint::Solid { swatch: None, .. }) + && s.paint.color().is_some_and(|w| ColorKey::of(&w) == ColorKey::of(c)) + }; + swatches.iter().position(fits).map(|i| PickedSwatch::new(li, i)) + }) } /// The index in [`swatch_view`]'s libraries of the library a Limit to Library key names @@ -212,6 +287,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if let Some((document, _, index, _)) = artboard { dialog = dialog.instance((document, index)); } + // The picker adds no dimming of its own over the canvas, so its live preview shows the true color; another open + // dialog's scrim can still dim the canvas. Presses on it stay blocked: + // the app does not take the picker's canvas eyedropper request. + if let Some(canvas) = crate::doc_windows::current(app).map(crate::canvas::canvas_id) { + dialog = dialog.canvas(canvas).canvas_samples(false); + } let id = dialogs.with(|h| h.open(dialog)); // A picker the open replaced leaves its preview behind: end it. if let Some(at) = app.color_dialogs.pickers.iter().position(|open| open.id == id) { @@ -228,10 +309,28 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { }; // OK with the artboard's color (or the white that stands in for none) unchanged keeps the artboard as it is. let keep = artboard.is_some() && p.get("color").is_none(); - app.color_dialogs.pickers.push(Open { id, target, start, keep, preview: LivePreview::default() }); + app.color_dialogs.pickers.push(Open { id, target, start, keep, preview: LivePreview::default(), view: Vec::new(), row: None }); Ok(Value::Null) } +/// The reason `ui.dialog.confirm` with `params` fails, when it would confirm a picker whose Recolor +/// Artwork row changed since the picker opened (OK would then answer nothing). The picker stays open. +pub(crate) fn check_confirm(app: &VectorcraftApp, host: &craft::ui::dialog::DialogHost, params: &Value) -> Result<(), String> { + let Ok(id) = craft::automation::dialogs::dialog_id(host, params) else { return Ok(()) }; + let Some(open) = app.color_dialogs.pickers.iter().find(|open| open.id == id) else { return Ok(()) }; + if let (Target::Answer { parent, key }, Some(row)) = (&open.target, &open.row) + && super::recolor::row_identity_in(host, *parent, key).as_ref() != Some(row) + { + return Err(rows_changed()); + } + Ok(()) +} + +/// Why a picker's OK answers nothing over Recolor Artwork. +pub(super) fn rows_changed() -> String { + tl!("The Recolor Artwork rows changed while the Color Picker was open").to_string() +} + /// Once per frame (after the shell pass): opens a picker for each dialog's colour request, previews /// each open picker's colour on the art, hands it the screen picks, and settles the ones that /// closed. @@ -241,12 +340,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let start = request.color.unwrap_or(Srgba { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }); let key = request.key.clone(); let library = super::recolor::limit_to(&dialogs, parent).and_then(|limit| library_index(app, &limit)); + let over_recolor = super::recolor::is_recolor(&dialogs, parent); + let (swatches, listed) = swatch_view_of(app, over_recolor); + let view = if over_recolor { listed } else { Vec::new() }; + // A row picked from a swatch has that swatch marked again, while the row's colour is its colour. + let row_swatch = super::recolor::row_swatch_of(&dialogs, parent, &key) + .and_then(|(name, lib, to)| view_place(app, &view, &name, &lib, &to)) + .filter(|p| picked_row_swatch(app, &view, *p).flatten().is_some()); let child = ColorPickerDialog::from_request(request) .eyedropper(true) .add_to_swatches(false) .gamut(gamut(app)) .working_rgb(WorkingRgb) - .swatch_view(swatch_view(app)); + .swatch_view(swatches); + let row = super::recolor::row_identity(&dialogs, parent, &key); let id = dialogs.with(|h| h.open_child(child, parent)); // Over Recolor Artwork, the swatches view shows the library that Limit to Library limits to. if let Some(i) = library @@ -254,7 +361,21 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { { app.status(e); } - app.color_dialogs.pickers.push(Open { id, target: Target::Answer { parent, key }, start, keep: false, preview: LivePreview::default() }); + // A picker set to a layout without the swatches view refuses the mark and keeps the colour. A + // swatch of another library than the one Limit to Library limits to is not marked, so the + // view keeps showing that library. + if let Some(p) = row_swatch.filter(|p| library.is_none_or(|i| p.library == i)) { + let _ = dialogs.with(|h| h.set_json_field(ctx, id, "swatch", json!([p.library, p.index]))); + } + app.color_dialogs.pickers.push(Open { + id, + target: Target::Answer { parent, key }, + start, + keep: false, + preview: LivePreview::default(), + view, + row, + }); } let busy = app.screen_pick.busy(); let mut pickers = std::mem::take(&mut app.color_dialogs.pickers); @@ -310,6 +431,19 @@ fn finish( let preview = std::mem::take(&mut open.preview); match (result, &open.target) { (Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => { + // A row that the dialog's rows changed under (`ui.dialog.set`) takes no answer. + if open.row.is_some() && super::recolor::row_identity(dialogs, *parent, key) != open.row { + app.status(rows_changed()); + return; + } + // Over Recolor Artwork, a colour picked from a swatch carries the swatch to the row. + if let Some(swatch) = r.swatch.and_then(|p| picked_row_swatch(app, &open.view, p)) + && super::recolor::is_recolor(dialogs, *parent) + { + super::recolor::answer_swatch(dialogs, *parent, key, swatch); + } + // The pump applies the answer later; it drops it when the row changed in between. + super::recolor::answer_row(dialogs, *parent, open.row.clone()); if !super::save_for_web::take_palette_pick(app, *parent, key, open.start, r.picked.color) { dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)); } diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 1abafe7025..4d7e820a29 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -451,3 +451,46 @@ fn the_artboard_picker_leaves_restored_artboards_unchanged() { assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#abcdef")); } } + +/// The picker keeps the document's canvas open under its modal layer (#10639): the canvas is not dimmed, so the live +/// preview shows the true color, and the wheel over the canvas still scrolls the view. +#[test] +fn the_canvas_stays_open_under_the_picker() { + let step = |app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0)); + crate::testing::app_frame(app, ctx, egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }); + }; + let (mut app, ctx) = app(); + for _ in 0..3 { + step(&mut app, &ctx, vec![]); + } + app.run("ui.colorPicker", json!({})).unwrap(); + for _ in 0..3 { + step(&mut app, &ctx, vec![]); + } + assert!(!app.color_dialogs.pickers.is_empty(), "the picker is open"); + let at = app.canvas_view().unwrap().rect.left_top() + egui::vec2(20.0, 20.0); + for _ in 0..3 { + step(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + } + let before = app.canvas_view().unwrap().center; + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -3.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::default(), + source: egui::MouseWheelSource::Unknown, + }; + for _ in 0..5 { + step(&mut app, &ctx, vec![egui::Event::PointerMoved(at), wheel.clone()]); + } + assert_ne!(app.canvas_view().unwrap().center, before, "the wheel over the canvas scrolls the view under the picker"); + // A click on the canvas stays blocked: it does not reach the tool and clear the selection. + let selected = app.session.doc().unwrap().selection.clone(); + let press = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::default() }; + step(&mut app, &ctx, vec![egui::Event::PointerMoved(at), press(true)]); + step(&mut app, &ctx, vec![press(false)]); + step(&mut app, &ctx, vec![]); + assert_eq!(app.session.doc().unwrap().selection, selected, "the click under the picker leaves the selection"); +} diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index 0465d1e322..5592a2c274 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -719,7 +719,7 @@ fn percent<'r>(list: ListRow<'r>, spec: &Percent, value: f64, at: usize, edits: let Percent { column, label, range, edit } = spec; let (edit, field) = (*edit, NumberField::new(*label, Bind::given(Some(value))).range((*range).clone()).unit("%")); list.cell_field(column.clone(), field, move |out| { - if let Some(Some(v)) = out.edit.value().copied() { + if let Some(Some(v)) = out.edit.events.landed().copied() { edits.borrow_mut().push((at, edit(v))); } }) diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index 48070f0b41..be02c8046c 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -650,6 +650,36 @@ fn a_highlighted_part_style_applies_only_once_it_is_chosen() { assert_ne!(parts(&p), before, "Enter sets the style"); } +/// Leaving a part's Size or Baseline on text that is not a number cancels the typing, and the part goes back to the +/// value it had before it. +#[test] +fn a_canceled_part_percentage_restores_the_part() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let mut p = Panel::new(app(), crate::tests::picks::dialogs); + p.room(egui::vec2(1280.0, 1100.0)); + open(&mut p.app()).unwrap(); + new_font(&mut p.app()); + p.frame(); + p.frame(); + let parts = |p: &Panel| dialog(&mut p.app(), |d| d.font().map(|f| f.parts.clone())); + for name in ["Size", "Baseline"] { + let before = parts(&p); + p.click_role(name, Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("37"); + assert_ne!(parts(&p), before, "typing into {name} proposes a value"); + p.type_text("x"); + p.key(Key::Tab, Modifiers::NONE); + p.frame(); + assert!(is_open(&p.app()), "leaving {name} keeps the dialog open"); + assert_eq!(parts(&p), before, "leaving {name} on text that is not a number restores the part"); + } +} + #[test] fn composite_fonts_approval_does_not_replace_definitions_restored_by_revert() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 057eac94eb..0020757e44 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -286,6 +286,8 @@ fn normalized(app: &VectorcraftApp, id: &str, values: Map, fresh: super::effect_rows::clamp_blur_center(&mut values); } else if id == vectorcraft_effects::RASTERIZE { super::raster_effects::preset_of(&mut values); + } else if id == vectorcraft_effects::addons::halftone::HALFTONE { + super::halftone::canonical_style(&mut values); } values } @@ -705,6 +707,19 @@ mod tests { app.session.doc().unwrap().history.undo.len() } + #[test] + fn halftone_dialog_normalizes_stored_style_case() { + let mut app = app(); + let node = rect(&mut app, 10); + let effect = vectorcraft_effects::addons::halftone::HALFTONE; + app.run("effect.apply", json!({"ids": [node], "effect": effect, "item": null, "params": {"style": "GRIDDOTS"}})).unwrap(); + app.run("select.set", json!({"ids": [node]})).unwrap(); + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + let open = app.effect_dialogs.effect.as_ref().unwrap(); + assert_eq!(open.opened["style"], json!("gridDots")); + assert_eq!(fields(&app, id(&app)).text("style"), Some("gridDots")); + } + #[test] fn edit_and_add_new_still_open_after_an_idle_effect_prompt() { for (choice, editing) in [("proceed", true), ("alternate", false)] { @@ -757,17 +772,17 @@ mod tests { assert_eq!((pa["detail"].as_f64(), pb["detail"].as_f64()), (Some(3.0), Some(8.0)), "each keeps its untouched value"); } - /// Zig Zag's Ridges per segment and Roughen's Detail are counts: their rows show no percent sign, while Size - /// with Relative, a share of the object's size, shows one. + /// Zig Zag's Ridges per segment is a plain count and Roughen's Detail a count per inch: neither row shows a + /// percent sign, while Size with Relative, a share of the object's size, shows one. #[test] - fn zig_zag_ridges_and_roughen_detail_show_no_percent_sign() { + fn zig_zag_ridges_and_roughen_detail_show_their_count_units() { use craft::ui::runtime::env::UnitKind; let app = app(); - for (effect, key) in [("distort.zigZag", "ridges"), ("distort.roughen", "detail")] { + for (effect, key, expected) in [("distort.zigZag", "ridges", None), ("distort.roughen", "detail", Some(UnitKind::PerInch))] { let cx = EffectCx::new(&app, effect, false); let rows = super::super::effect_rows::distort(&cx, &DialogFields::new()); let unit = |k: &str| rows.iter().find(|p| p.key == k).map(|p| p.unit); - assert_eq!(unit(key), Some(None), "{effect} {key}"); + assert_eq!(unit(key), Some(expected), "{effect} {key}"); assert_eq!(unit("size"), Some(Some(UnitKind::Percent)), "{effect} size"); } } @@ -1172,6 +1187,29 @@ mod tests { assert_eq!(params(&app, node)["size"], 12.0); } + #[test] + fn a_new_graphics_context_rolls_back_the_old_effect_preview_and_keeps_the_new_opening() { + let mut app = app(); + let node = rect(&mut app, 10); + standalone_effect_source(&mut app); + effect_frame(&mut app); + assert_eq!(params(&app, node)["size"], 16.0); + let history = steps(&app); + + app.adopt_context(&crate::testing::ui_context()); + effect_frame(&mut app); + assert!(!app.session.in_interaction(), "the old context's effect preview is still running"); + assert!(app.effect_dialogs.effect.is_none()); + assert!(app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(node)).unwrap().appearance.effects.is_empty()); + + standalone_effect_source(&mut app); + effect_frame(&mut app); + assert!(app.effect_dialogs.effect.is_some(), "the old opening's Cancel removed the new opening"); + ok(&mut app); + assert_eq!(params(&app, node)["size"], 16.0); + assert_eq!(steps(&app), history + 1); + } + #[test] fn standalone_effect_ok_cannot_change_the_reloaded_drawing() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/effect_rows.rs b/crates/ui-egui/src/dialogs/effect_rows.rs index 9ba4858116..023c67cba5 100644 --- a/crates/ui-egui/src/dialogs/effect_rows.rs +++ b/crates/ui-egui/src/dialogs/effect_rows.rs @@ -88,8 +88,11 @@ pub(super) fn transform(cx: &EffectCx, _fields: &DialogFields) -> Vec { /// Zig Zag and Roughen. pub(super) fn distort(cx: &EffectCx, fields: &DialogFields) -> Vec { let roughen = cx.id == "distort.roughen"; - // PLAN: production suffixes Detail with "/in"; `Param::unit` takes a `UnitKind` and none stands for it - let second = if roughen { count_range("detail", lbl!("Detail:"), 10.0) } else { count_range("ridges", lbl!("Ridges per segment:"), 4.0) }; + let second = if roughen { + count_range("detail", lbl!("Detail:"), 10.0).unit(UnitKind::PerInch) + } else { + count_range("ridges", lbl!("Ridges per segment:"), 4.0) + }; let points: Vec<(String, Label)> = choices(&cx.id, "points") .unwrap_or_default() .iter() diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index decb345a71..884e5848bf 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -697,7 +697,7 @@ impl ExportForScreensDialog { } }; screen_formats::rows(ui, fields, Some(&mut menu)); - let saved = screen_formats::save_preset_row(ui, fields); + let saved = screen_formats::save_preset_row(ui, fields, &mut false); if let Some(pick) = picked.or(saved) { self.pending = Some(pick); } diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 78a24f8868..fc62033bf9 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -17,6 +17,8 @@ //! `replace` text and `backwards`, the place it reached in `from` (`{id, start, end}`), the drawing's //! UID and Revert counter in `doc`, and the match in `found` (`{index, count}`). Changing the //! loaded drawing, Find text, or switches restarts the search. [`pump`] runs the requests each frame. +//! Automation presses the buttons through the dialog's `action` field and `ui.dialog.confirm` +//! ([`dialog_method`]). use craft::text::find::FindOptions; use craft::text::ui::find::{FindCheck, FindReplaceDialog, FindRequest, FindTab, ReplaceButtons}; @@ -109,6 +111,7 @@ pub fn open(app: &mut VectorcraftApp, params: &Map) -> Result replace_all(app, &form), _ => return None, }; + // A click presses a button as `ui.dialog.confirm` does: `action` goes back to find. + app.ui.find_action = None; Some(ran.unwrap_or_else(|e| said(&e))) }); + report(app, &form, message); +} + +/// Tells the open dialog `message`, or the refreshed match line when there is none, and whether a +/// match is current. +fn report(app: &mut VectorcraftApp, form: &Form, message: Option) { let (matched, match_message) = refresh_match(app, &form.query); + let Some(dialogs) = app.dialogs() else { return }; dialogs.with(|host| { if let Some(d) = host.get_mut::() { if let Some(message) = message.or(match_message) { @@ -351,5 +363,175 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }); } +/// The values the `action` field takes: the button `ui.dialog.confirm` presses. +const ACTIONS: [&str; 5] = ["find", "replace", "replaceFind", "replaceAll", "done"]; + +/// The `action` field a `ui.dialog.set` gives, as `field` and `value` or as an item of `fields`, taken +/// out of `params`: `Ok(None)` when it gives none, an error when it is not one of [`ACTIONS`]. +fn take_action(params: &mut Value) -> Result, String> { + let Some(o) = params.as_object_mut() else { return Ok(None) }; + // The host's setter refuses the same mix. + if o.contains_key("fields") && (o.contains_key("field") || o.contains_key("value")) { + return Err("`fields` takes the place of `field` and `value`".into()); + } + let mut given = None; + if o.get("field").and_then(Value::as_str) == Some("action") { + o.remove("field"); + given = Some(o.remove("value").unwrap_or(Value::Null)); + } + let mut only_action = false; + if let Some(list) = o.get_mut("fields").and_then(Value::as_array_mut) { + // The framework's limit counts `action` with the other items. + let most = craft::automation::dialogs::MAX_DIALOG_FIELDS; + if list.len() > most { + return Err(format!("`fields` holds {} items; at most {most}", list.len())); + } + let is_action = |item: &Value| item.get("field").and_then(Value::as_str) == Some("action"); + if let Some(last) = list.iter().rev().find(|item| is_action(item)) { + given = Some(last.get("value").cloned().unwrap_or(Value::Null)); + } + let before = list.len(); + list.retain(|item| !is_action(item)); + only_action = list.is_empty() && before > 0; + } + // A list that held only `action` sets nothing else. + if only_action { + o.remove("fields"); + } + match given { + None => Ok(None), + Some(Value::String(a)) if ACTIONS.contains(&a.as_str()) => Ok(Some(a)), + Some(_) => Err("`action` must be find, replace, replaceFind, replaceAll or done".into()), + } +} + +/// The open dialog as `ui.inspect` lists it, `{id, parent, key, fields}` with its `action`, or null. +fn listed(app: &VectorcraftApp) -> Value { + let Some(dialogs) = app.dialogs() else { return Value::Null }; + let mut open = dialogs.with(|host| craft::automation::dialogs::inspect(host)); + show_action(app, &mut open); + let id = dialogs.with(|host| host.get::().map(|d| d.id().value().to_string())); + open.as_array().and_then(|open| open.iter().find(|d| id.as_deref().is_some_and(|id| d["id"] == id)).cloned()).unwrap_or(Value::Null) +} + +/// Adds the `action` field to the open Find and Replace dialog in `ui.inspect`'s `dialogs`. +pub(crate) fn show_action(app: &VectorcraftApp, dialogs: &mut Value) { + let Some(id) = app.dialogs().and_then(|d| d.with(|host| host.get::().map(|d| d.id().value().to_string()))) else { return }; + let action = app.ui.find_action.clone().unwrap_or_else(|| "find".into()); + let shown = dialogs.as_array_mut().and_then(|open| open.iter_mut().find(|d| d["id"] == id.as_str())); + if let Some(fields) = shown.and_then(|d| d.get_mut("fields")).and_then(Value::as_object_mut) { + fields.insert("action".into(), json!(action)); + } +} + +/// `ui.dialog.set` and `ui.dialog.confirm` (`method`) on the open Find and Replace dialog, when +/// `params.dialog` names it: a set takes the `action` field and answers with the dialog as +/// `ui.inspect` lists it, `action` included, and `ui.dialog.confirm`, or a set with +/// `action: "confirm"`, presses the button it names (`find` when none is set) and leaves `action` at +/// `find` again. Every other request is the host's, as is a set with `action: "cancel"` that gives +/// no `action` field: `None`. +pub(crate) fn dialog_method(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: &Value) -> Option> { + if !matches!(method, "ui.dialog.set" | "ui.dialog.confirm") { + return None; + } + let dialogs = app.dialogs()?; + let ours = dialogs.with(|host| { + let id = host.get::().map(StackDialog::id); + id.is_some() && craft::automation::dialogs::dialog_id(host, params).ok() == id + }); + if !ours { + return None; + } + let keys: &[&str] = if method == "ui.dialog.set" { &["dialog", "field", "value", "fields", "action"] } else { &["dialog"] }; + let mut params = params.clone(); + let answer = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { Some(json!("confirm")) }; + let given = if method == "ui.dialog.set" { + match take_action(&mut params) { + Ok(given) => given, + Err(e) => return Some(Err(e)), + } + } else { + None + }; + let confirm = match answer.as_ref().map(Value::as_str) { + None => false, + Some(Some("confirm")) => true, + // Cancel closes it as the host closes any dialog. + Some(Some("cancel")) if given.is_none() => return None, + Some(Some("cancel")) => false, + Some(_) => return Some(Err("`action` must be confirm or cancel".into())), + }; + if let Err(e) = craft::automation::protocol::Params(¶ms).only(None, keys) { + return Some(Err(e)); + } + // The other fields are set first, all or none, as the host sets and checks them. A set that + // gives no `action` and does not confirm goes to the host's setter whole, which refuses one + // with nothing to set. + let sets = ["field", "value", "fields"].iter().any(|k| params.get(k).is_some()) || (given.is_none() && !confirm); + if sets && let Some(Err(e)) = dialogs.with(|host| craft::automation::dialogs::dialog_method(host, ctx, "ui.dialog.set", ¶ms)) { + return Some(Err(e)); + } + if let Some(given) = given { + app.ui.find_action = Some(given); + } + if answer.as_ref().and_then(Value::as_str) == Some("cancel") { + dialogs.with(|host| host.cancel::(ctx)); + return Some(Ok(Value::Null)); + } + Some(if confirm { press(app, ctx) } else { Ok(listed(app)) }) +} + +/// Whether the dialog's `tab` (its `tab` field: `find`, `replace` or `goTo`) shows the button +/// `action` presses, enabled. Every tab shows Done. The Find tab shows Find Next, and the Replace tab +/// shows Find Next, Replace, Replace & Find and Replace All. The Go To tab shows no Find Next: its +/// first button is Go To, which stays disabled while the dialog has no go-to kinds. +fn shown_on(tab: &str, action: &str) -> bool { + match action { + "done" => true, + "find" => matches!(tab, "find" | "replace"), + _ => tab == "replace", + } +} + +/// Presses the button the `action` field names, as a click on it does, and leaves `action` at +/// `find`. Replace and Replace & Find find a match when Find Next has reached none with the Find +/// text and the switches as they are now. Done closes the dialog → the dialog as listed, or null +/// once closed; a refusal is the dialog's message and the error. A button the open tab does not +/// show ([`shown_on`]) and, with an empty Find text, every button but Done run nothing, as a click +/// cannot press them: the press is an error that leaves the document, the message and `action` as +/// they were. +fn press(app: &mut VectorcraftApp, ctx: &egui::Context) -> Result { + let action = app.ui.find_action.clone().unwrap_or_else(|| "find".into()); + let dialogs = app.dialogs().ok_or("no window")?; + let (form, tab) = dialogs + .with(|host| host.get::().map(|d| (form(d), d.json_fields().and_then(|f| f["tab"].as_str().map(str::to_string))))) + .ok_or("no hosted dialog is open")?; + let tab = tab.unwrap_or_default(); + if !shown_on(&tab, &action) { + return Err(format!("the {tab} tab has no button for `action` {action}")); + } + if action == "done" { + app.ui.find_action = None; + dialogs.with(|host| host.cancel::(ctx)); + return Ok(Value::Null); + } + if form.query["find"].as_str().is_none_or(str::is_empty) { + return Err("the Find text is empty".into()); + } + app.ui.find_action = None; + let found = app.ui.last_find.as_ref().is_some_and(|last| current_match(app, last, &form.query).is_some()); + let ran = match action.as_str() { + "replace" | "replaceFind" if found => replace(app, &form, action == "replaceFind"), + "replaceAll" => replace_all(app, &form), + _ => find(app, &form), + }; + let message = match &ran { + Ok(m) => Some(m.clone()), + Err(e) => Some(said(e)), + }; + report(app, &form, message); + ran.map(|_| listed(app)) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index e90efe3f8a..dd1dc255e7 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -97,6 +97,213 @@ fn selected(p: &Panel) -> Vec { p.app().session.active().unwrap().selection.objects.iter().map(|id| id.0).collect() } +/// A control request answered at once → its result, or its error. +fn control(p: &Panel, method: &str, params: Value) -> Result { + let (req, _) = craft::automation::ControlRequest::new(method, params); + let craft::automation::Reply::Done(r) = crate::control::handle(&mut p.app(), p.ctx(), &req) else { panic!("{method} answered later") }; + match r.get("error") { + Some(e) if !e.is_null() => Err(e.as_str().map_or_else(|| e.to_string(), str::to_string)), + _ => Ok(r["result"].clone()), + } +} + +/// The open Find and Replace dialog's `action`, as `ui.inspect` lists it. +fn listed_action(p: &Panel) -> Value { + let r = control(p, "ui.inspect", json!({})).unwrap(); + let open = r["dialogs"].as_array().cloned().unwrap_or_default(); + open.last().map(|d| d["fields"]["action"].clone()).unwrap_or(Value::Null) +} + +fn set_action(p: &Panel, action: &str) { + control(p, "ui.dialog.set", json!({"dialog": "top", "field": "action", "value": action})).unwrap(); +} + +/// `ui.inspect` lists the dialog's `action`, `find` until a set changes it. `ui.dialog.confirm` +/// presses the button it names, as a click does, keeps the dialog open and puts `action` back to +/// find. Replace and Replace & Find find a match when Find Next reached none; done closes it. +#[test] +fn confirm_presses_the_button_the_action_names() { + let (app, ids) = app_with(&["cat cat cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + assert_eq!(listed_action(&p), json!("find")); + let fields = json!([{"field": "find", "value": "cat"}, {"field": "replace", "value": "dog"}]); + control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})).unwrap(); + let before = undo_steps(&p); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!(matched(&p), Some((ids[0], 0, 3)), "find runs without an action set"); + assert!(message(&p).starts_with("1 / 3"), "{}", message(&p)); + + set_action(&p, "replace"); + assert_eq!(listed_action(&p), json!("replace")); + let shown = control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!(plain(&p, ids[0]), "dog cat cat", "replace changes the match found"); + assert_eq!((undo_steps(&p), listed_action(&p)), (before + 1, json!("find"))); + assert_eq!(shown["fields"]["action"], json!("find")); + + // Replace & Find with no match found finds one and changes nothing. + set_action(&p, "replaceFind"); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!((plain(&p, ids[0]), matched(&p)), ("dog cat cat".to_string(), Some((ids[0], 4, 7)))); + set_action(&p, "replaceFind"); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!((plain(&p, ids[0]), matched(&p)), ("dog dog cat".to_string(), Some((ids[0], 8, 11)))); + + control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "action", "value": "replaceAll", "action": "confirm"})).unwrap(); + assert_eq!((plain(&p, ids[0]), message(&p)), ("dog dog dog".to_string(), "Matches replaced: 1".to_string())); + assert_eq!(undo_steps(&p), before + 3); + + // A set and confirm in one request closes the dialog with done. + let done = json!([{"field": "action", "value": "done"}]); + let closed = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": done, "action": "confirm"})).unwrap(); + assert_eq!(closed, Value::Null); + assert!(!is_open(&p)); +} + +/// An `action` that names no button is refused when it is set, as are the fields set with it, and +/// `action` stays as it was. A set and confirm whose set is refused presses no button. +#[test] +fn an_action_that_names_no_button_is_refused() { + let (app, ids) = app_with(&["cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + let refusal = "`action` must be find, replace, replaceFind, replaceAll or done"; + for v in [json!("jump"), json!(3), json!(null), json!("Replace")] { + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "action", "value": v})); + assert_eq!(r, Err(refusal.to_string()), "{v}"); + } + let fields = json!([{"field": "replace", "value": "dog"}, {"field": "action", "value": "skip"}]); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})); + assert_eq!(r, Err(refusal.to_string())); + assert_eq!((field(&p, "replace"), listed_action(&p)), (json!(""), json!("find"))); + // A field the dialog refuses leaves `action` as it was. + let fields = json!([{"field": "matchCase", "value": "yes"}, {"field": "action", "value": "replaceAll"}]); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})); + assert!(r.is_err(), "{r:?}"); + assert_eq!(listed_action(&p), json!("find")); + // A request with a key the method does not take is refused. + assert!(control(&p, "ui.dialog.confirm", json!({"dialog": "top", "action": "replace"})).is_err()); + // A set the host refuses presses nothing, even with `action: "confirm"`. + let fields = json!([{"field": "find", "value": "cat"}, {"field": "replace", "value": "dog"}, {"field": "action", "value": "replaceAll"}]); + control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})).unwrap(); + for bad in [json!({"fields": {}}), json!({"value": 1}), json!({"field": "nope", "value": 1})] { + let mut request = bad.clone(); + request["dialog"] = json!("top"); + request["action"] = json!("confirm"); + assert!(control(&p, "ui.dialog.set", request).is_err(), "{bad}"); + assert_eq!((plain(&p, ids[0]), listed_action(&p)), ("cat".to_string(), json!("replaceAll")), "{bad}"); + } + assert!(is_open(&p)); +} + +/// With an empty Find text a confirm presses nothing, as the dialog's buttons run nothing: it is +/// refused, and the text, the undo steps, the message and `action` stay as they were. Done still +/// closes the dialog. +#[test] +fn a_confirm_with_no_find_text_presses_nothing() { + let (app, ids) = app_with(&["cat cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "replace", "value": "dog"})).unwrap(); + assert_eq!(field(&p, "find"), json!("")); + let (before, said) = (undo_steps(&p), message(&p)); + for action in ["find", "replace", "replaceFind", "replaceAll"] { + set_action(&p, action); + let r = control(&p, "ui.dialog.confirm", json!({})); + assert_eq!(r, Err("the Find text is empty".to_string()), "{action}"); + assert_eq!((plain(&p, ids[0]), undo_steps(&p), message(&p)), ("cat cat".to_string(), before, said.clone()), "{action}"); + assert_eq!(listed_action(&p), json!(action)); + } + set_action(&p, "done"); + assert_eq!(control(&p, "ui.dialog.confirm", json!({})), Ok(Value::Null)); + assert!(!is_open(&p)); +} + +/// A confirm presses only a button the open tab shows enabled: on the Find tab the Replace buttons +/// and on the Go To tab Find Next are refused, naming the tab, and the text, the undo steps, the +/// message and `action` stay as they were. Find Next runs on the Find tab, and Done closes the +/// dialog from the Go To tab. +#[test] +fn a_confirm_presses_only_a_button_the_tab_shows() { + let (app, ids) = app_with(&["cat cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + let fields = json!([{"field": "find", "value": "cat"}, {"field": "replace", "value": "dog"}, {"field": "tab", "value": "find"}]); + control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})).unwrap(); + let (before, said) = (undo_steps(&p), message(&p)); + for action in ["replace", "replaceFind", "replaceAll"] { + set_action(&p, action); + let r = control(&p, "ui.dialog.confirm", json!({})); + assert_eq!(r, Err(format!("the find tab has no button for `action` {action}")), "{action}"); + assert_eq!((plain(&p, ids[0]), undo_steps(&p), message(&p)), ("cat cat".to_string(), before, said.clone()), "{action}"); + assert_eq!(listed_action(&p), json!(action)); + } + set_action(&p, "find"); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!(matched(&p), Some((ids[0], 0, 3)), "Find Next is on the Find tab"); + + control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "tab", "value": "goTo"})).unwrap(); + let (at, said) = (from(&p), message(&p)); + let r = control(&p, "ui.dialog.confirm", json!({})); + assert_eq!(r, Err("the goTo tab has no button for `action` find".to_string())); + assert_eq!((from(&p), message(&p), listed_action(&p)), (at, said, json!("find"))); + set_action(&p, "done"); + assert_eq!(control(&p, "ui.dialog.confirm", json!({})), Ok(Value::Null)); + assert!(!is_open(&p)); +} + +/// `fields` given with `field` or `value` is refused, as the host refuses it, even when the list +/// holds only `action`; nothing is set. +#[test] +fn fields_with_field_or_value_is_refused() { + let (app, _) = app_with(&["cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + let refusal = Err("`fields` takes the place of `field` and `value`".to_string()); + let only_action = json!([{"field": "action", "value": "replace"}]); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "find", "value": "cat", "fields": only_action})); + assert_eq!(r, refusal); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "value": "cat", "fields": only_action})); + assert_eq!(r, refusal); + assert_eq!((field(&p, "find"), listed_action(&p)), (json!(""), json!("find"))); +} + +/// A set of other fields answers with `action` listed. A click on a button, like a confirm, puts +/// `action` back to find, and so does opening the dialog again. A `fields` list of more than 256 +/// items is refused, `action` counted with the rest. +#[test] +fn action_is_listed_and_goes_back_to_find() { + let (app, _) = app_with(&["cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + set_action(&p, "replace"); + let shown = control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "find", "value": "cat"})).unwrap(); + assert_eq!((shown["fields"]["find"].clone(), shown["fields"]["action"].clone()), (json!("cat"), json!("replace"))); + assert!(control(&p, "ui.dialog.set", json!({"dialog": "top"})).is_err(), "a set with nothing to set"); + + let mut fields = vec![json!({"field": "find", "value": "cat"}); 256]; + fields.push(json!({"field": "action", "value": "replaceAll"})); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})); + assert_eq!(r, Err("`fields` holds 257 items; at most 256".to_string())); + assert_eq!(listed_action(&p), json!("replace")); + + p.click("Find Next"); + assert_eq!(listed_action(&p), json!("find"), "a click"); + + set_action(&p, "replace"); + control(&p, "ui.dialog.cancel", json!({"dialog": "top"})).unwrap(); + assert!(!is_open(&p)); + choose(&p); + p.frame(); + assert_eq!(listed_action(&p), json!("find"), "opening again"); +} + #[test] fn a_cached_match_cannot_replace_text_restored_by_revert() { let (mut app, ids) = app_with(&["Needle Needle"]); diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 2b3760f38f..796a829836 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -249,8 +249,13 @@ pub(crate) fn apply_custom(job: &mut SavePdfJob, parent: &HostedPdfExport, field /// Open Flatten Transparency for the selection with the default preset. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), |fields| { - ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).values(Bind::bound(fields)).previews(true) + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), move |fields| { + let dialog = ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).values(Bind::bound(fields)).previews(true); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }) // Flattening complex art is slow: the preview waits until it is turned on. .preview_off(); diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 7de36ba00e..4d4d38e372 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -134,7 +134,8 @@ pub(crate) fn fidelity_field(ui: &mut Ui, id: &str, v: f64, tool: &str) -> EditE } /// The Fidelity row: a logarithmic slider from the tool's lowest Fidelity to [`FIDELITY_MAX`] with the field at its -/// end, and Accurate and Smooth under the slider's ends. +/// end, and Accurate and Smooth under the slider's ends. The slider's keys and wheel step by [`fidelity_step`], as the +/// field's do. fn fidelity_row(ui: &mut Ui, fields: &mut DialogFields, tool: &str) -> Response { let min = vectorcraft_tools::draw2::min_fidelity(tool); let v = fields.number("fidelity").unwrap_or(1.5); @@ -142,6 +143,7 @@ fn fidelity_row(ui: &mut Ui, fields: &mut DialogFields, tool: &str) -> Response let shown = Row::new().show(ui, |ui, _| { let slid = Slider::new(Bind::given(v), min..=FIDELITY_MAX) .scale(SliderScale::Log) + .stepper(|v, dir, steps| fidelity_step(v, f64::from(dir) * steps)) .marks_labelled([(min, tl!("Accurate")), (FIDELITY_MAX, tl!("Smooth"))]) .label(tl!("Fidelity")) .id_salt("fidelity-slider") diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 790d5742e1..2542cfa6af 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -422,6 +422,43 @@ fn draft_fidelity(panel: &crate::tests::panel_harness::Panel) -> Option { panel.app().dialogs().and_then(|d| d.with(|host| host.get::().and_then(|dialog| dialog.fields().number("fidelity")))) } +/// The Fidelity slider of every freehand tool steps through the field's values: an arrow key takes the next hundredth +/// at the Accurate end, Shift with an arrow multiplies by ten, and a wheel notch takes one step back. +#[test] +fn the_fidelity_slider_keys_and_wheel_step_finely_at_the_low_end() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers, vec2}; + for tool in ["pencil", "paintbrush", "smooth", "blobBrush"] { + let min = vectorcraft_tools::draw2::min_fidelity(tool); + let mut app = app(); + app.run("tool.setOption", json!({"tool": tool, "values": {"fidelity": min}})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.room(vec2(1000.0, 1200.0)); + crate::toolbar::open_options(&mut panel.app(), tool).unwrap(); + panel.frame(); + assert_eq!(draft_fidelity(&panel), Some(min), "{tool}"); + // The field comes after the slider, so Shift+Tab from the field gives the slider the focus. + panel.click_role("Fidelity", Role::SPIN_BUTTON); + panel.key(Key::Tab, Modifiers::SHIFT); + let at = |hundredths: f64| fidelity_round(min + hundredths / 100.0); + panel.key(Key::ArrowRight, Modifiers::NONE); + assert_eq!(draft_fidelity(&panel), Some(at(1.0)), "{tool}: an arrow takes the next hundredth"); + panel.key(Key::ArrowRight, Modifiers::NONE); + assert_eq!(draft_fidelity(&panel), Some(at(2.0)), "{tool}"); + panel.key(Key::ArrowRight, Modifiers::SHIFT); + assert_eq!(draft_fidelity(&panel), Some(fidelity_round(at(2.0) * 10.0)), "{tool}: Shift multiplies by ten"); + panel.key(Key::ArrowLeft, Modifiers::NONE); + assert_eq!(draft_fidelity(&panel), Some(fidelity_step(fidelity_round(at(2.0) * 10.0), -1.0)), "{tool}"); + let before = draft_fidelity(&panel).unwrap(); + let thumb = panel.rect_role("Fidelity", Role::SLIDER).center(); + panel.frame_with(vec![egui::Event::PointerMoved(thumb)]); + panel.frame_with(vec![craft::ui::testing::pointer::wheel_lines(-1.0)]); + panel.frame(); + assert_eq!(draft_fidelity(&panel), Some(fidelity_step(before, -1.0)), "{tool}: a wheel notch takes one step"); + assert_eq!(panel.app().session.tool_options_of(tool)["fidelity"].as_f64(), Some(min), "{tool}: the tool changes only on OK"); + } +} + /// The Smooth tool's Fidelity slider and field: a drag or a typed value that Escape cancels leaves the dialog's Fidelity /// and the tool's as they were; a finished drag or a typed value left with Tab sets the dialog's, and OK sets the tool's. #[test] diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index e9e05185b5..2ed369d2da 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -105,6 +105,22 @@ impl TargetKey { } } +/// The swatch last picked in the Swatches view and the stop or point it is picked for. +#[derive(Clone)] +struct PickedSwatch { + target: TargetKey, + name: String, +} + +impl PickedSwatch { + /// The active document's swatch `name`, picked for `target`. + fn of(app: &VectorcraftApp, target: &Target, name: &str) -> Option { + let key = TargetKey::of(app, target)?; + app.session.active()?.doc.swatch(name)?; + Some(Self { target: key, name: name.to_owned() }) + } +} + /// A Color mode command from the popover's menu that has not been seen to finish. struct OwnMode { /// The document's history step when it ran. @@ -262,11 +278,42 @@ fn recolor(mut stops: Vec, i: usize, color: Color, link: Option<(S stops } -/// Solid colours of the document's swatches (groups included), with their names. -fn swatch_colors(app: &VectorcraftApp) -> Vec<(String, Color)> { - let Some(st) = app.session.active() else { return vec![] }; - let d = &st.doc; - d.swatches.iter().chain(d.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter_map(|s| Some((s.name.clone(), s.paint.color()?))).collect() +/// Solid colors of the document's swatches (groups included), with their names, and the entry the target's color +/// comes from: a linked color's tint swatch for that tint, or its global swatch at 100%; an unlinked color's process +/// swatch of that very color. Where several entries qualify, `picked`, the swatch last picked in the popover for this +/// target, is the one. +fn swatch_colors(app: &VectorcraftApp, target: &Target, picked: Option<&PickedSwatch>) -> (Vec<(String, Color)>, Option) { + let Some(st) = app.session.active() else { return (vec![], None) }; + let picked = picked.filter(|p| p.target.matches(app, target)); + let (link, color) = match target { + Target::Stop(paint, i) => { + let stop = &paint.gradient.stops[*i]; + (stop.swatch.as_deref().map(|base| (base, stop.tint)), stop.color) + } + Target::Point(_, point, _) => (None, point.color), + }; + let mut colors = Vec::new(); + let mut selected = None; + for swatch in st.doc.swatches_iter() { + let is_picked = picked.is_some_and(|p| p.name == swatch.name); + let Some(own) = swatch.paint.color() else { continue }; + // Picking this swatch would give the target the color and link it has now. + let source = match (link, swatch.tint_of()) { + (Some((base, tint)), Some((of, own_tint))) => of == base && same_tint(tint, own_tint), + (Some((base, tint)), None) => swatch.global && swatch.name == base && same_tint(tint, 1.0), + (None, _) => !swatch.global && matches!(swatch.paint, Paint::Solid { color: c, swatch: None, .. } if c == color), + }; + if source && (selected.is_none() || is_picked) { + selected = Some(colors.len()); + } + colors.push((swatch.name.clone(), own)); + } + (colors, selected) +} + +/// Whether two tints are the same: stop commands carry a tint as a floating-point percentage. +fn same_tint(first: f32, second: f32) -> bool { + (first - second).abs() <= 2.0 * f32::EPSILON } /// The popover's two views. @@ -317,6 +364,10 @@ struct Feed { /// Percent: the stop's location or the point's spread. amount: f64, swatches: Vec<(String, Color)>, + /// The entry of `swatches` the target's color comes from. + selected_swatch: Option, + /// Picking the displayed swatch changes at least one edited paint. + displayed_swatch_changes_paints: bool, /// `swatches` as the palette draws them, in the same order. tiles: Vec<(Label, Srgba)>, shown: ColorPanelShown, @@ -327,6 +378,8 @@ struct Feed { struct Filed { fields: PopoverFields, swatch: Option<(String, Color)>, + /// Whether the pending swatch pick applies paint. + swatch_changes_paints: bool, eyedropper: bool, panels: Vec, /// Only an actual Shift-cycle changes this; an unchanged local snapshot must not overwrite a menu command. @@ -346,6 +399,8 @@ pub(crate) struct GradientStopPopover { at: Pos2, panel: ColorPanelState, feed: Option, + /// The swatch last picked in the Swatches view and the stop or point it was picked for. + picked_swatch: Option, /// The fields set from outside, applied at confirm. set: PopoverFields, filed: Filed, @@ -363,6 +418,7 @@ impl GradientStopPopover { at: Pos2::ZERO, panel: ColorPanelState::default(), feed: None, + picked_swatch: None, set: PopoverFields::default(), filed: Filed::default(), own_mode: None, @@ -522,19 +578,27 @@ fn swatches(ui: &mut Ui, feed: &Feed, filed: &mut Filed) { Notice::new(Tone::Info, tl!("The document has no colour swatches.").to_owned()).show(ui); return; } - let shown = SwatchPalette::new("Swatches", Bind::given(feed.current), &feed.tiles).show(ui); - let Some(picked) = shown.edit.as_ref().and_then(|edit| edit.value()) else { return }; - // The first swatch of that colour: the palette reports colours, not cells. - let at = feed.tiles.iter().position(|(_, c)| c.to_rgba() == picked.to_rgba()); - filed.swatch = at.and_then(|i| feed.swatches.get(i)).cloned(); + // Only the entry the target's color comes from is selected, and none when no entry is: a swatch that only draws + // the same color, such as a spot ink an unlinked stop has the color of, is not. + let shown = + SwatchPalette::new("Swatches", Bind::given(feed.current), &feed.tiles).selected_swatch(feed.selected_swatch).select_by_color(false).show(ui); + // Every click remembers the pick. The displayed swatch applies only when an edited paint differs at this stop or point. + // Other swatches apply even when they have the same color. + if let Some(i) = shown.picked_swatch + && let Some(swatch) = feed.swatches.get(i) + { + filed.swatch = Some(swatch.clone()); + filed.swatch_changes_paints = feed.displayed_swatch_changes_paints || Some(i) != feed.selected_swatch; + } } -/// A percent field named `label` over `value`; the number the user entered in this pass. +/// A percent field named `label` over `value`; the number the user entered in this pass, or the number a canceled +/// typing gives back. fn percent_field(ui: &mut Ui, label: String, value: f64) -> Option { let field = Field::new(label.clone()).show(ui, |ui, _| { NumberField::new(label.clone(), Bind::given(Some(value))).unit_kind(UnitKind::Percent).range(0.0..=100.0).step(1.0).show(ui) }); - field.inner?.value().copied().flatten() + field.inner?.edit.events.landed().copied().flatten() } /// The popover's size before it has been drawn, for placing it. @@ -580,10 +644,11 @@ fn place(app: &VectorcraftApp, ctx: &egui::Context, anchor: Anchor) -> Pos2 { } } -/// `target`'s values, the document's swatches and what the Color panel shows, for the popover's body. -fn feed(app: &VectorcraftApp, target: &Target) -> Feed { +/// `target`'s values, the document's swatches with the one `picked` for it selected, and what the Color panel shows, +/// for the popover's body. +fn feed(app: &VectorcraftApp, target: &Target, picked: Option<&PickedSwatch>) -> Feed { let shown = crate::panels::color::shown(app, &crate::panels::color::target_now(app)); - let swatches = swatch_colors(app); + let (swatches, selected_swatch) = swatch_colors(app, target, picked); Feed { point: matches!(target, Target::Point(..)), color: target.color(), @@ -592,6 +657,19 @@ fn feed(app: &VectorcraftApp, target: &Target) -> Feed { amount: f64::from(target.amount()) * 100.0, tiles: swatches.iter().map(|(name, c)| (Label::from(name.clone()), Srgba::from(c32(c)))).collect(), swatches, + selected_swatch, + displayed_swatch_changes_paints: app.session.gradient_edit_paints(!app.session.fill_active).map_or(true, |paints| { + !paints.all_paints_match(|paint| { + let Paint::Gradient(paint) = paint else { return false }; + match target { + Target::Stop(shown, i) => paint.gradient.stops.get(*i).is_some_and(|stop| { + let shown = &shown.gradient.stops[*i]; + stop.swatch == shown.swatch && stop.tint == shown.tint && stop.color == shown.color + }), + Target::Point(_, shown, i) => shown_points(paint).points.get(*i).is_some_and(|point| point.color == shown.color), + } + }) + }), shown, } } @@ -599,8 +677,12 @@ fn feed(app: &VectorcraftApp, target: &Target) -> Feed { /// Pushes `target`'s values, the swatches, what the Color panel shows and the place into the open popover `id`. fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Target) { let Some(dialogs) = app.dialogs() else { return }; - let Some(anchor) = dialogs.with(|host| host.get_by_id::(id).map(|popover| popover.anchor)) else { return }; - let feed = feed(app, target); + let Some((anchor, picked)) = + dialogs.with(|host| host.get_by_id::(id).map(|popover| (popover.anchor, popover.picked_swatch.clone()))) + else { + return; + }; + let feed = feed(app, target, picked.as_ref()); let at = place(app, ctx, anchor); dialogs.with(|host| { if let Some(popover) = host.get_mut_by_id::(id) { @@ -612,6 +694,23 @@ fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Tar }); } +/// After the swatch `from` of the document `uid` was renamed `to`, the open popover's remembered pick takes the new name +/// when it is that swatch, picked for the selected stop or point. +pub(crate) fn follow_swatch_rename(app: &VectorcraftApp, uid: u64, from: &str, to: &str) { + let Some(target) = selected(app) else { return }; + let Some(dialogs) = app.dialogs() else { return }; + dialogs.with(|host| { + if let Some(popover) = host.get_mut_by_id::(dialog_id(KIND)) + && let Some(picked) = &mut popover.picked_swatch + && picked.target.document.0 == uid + && picked.target.matches(app, &target) + && picked.name == from + { + picked.name = to.to_owned(); + } + }); +} + /// Opens the popover on the selected stop (a freeform gradient's selected point) of the active gradient, the stop /// at `index` when it is not the selected one. Nothing opens without a window or a stop to edit. pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { @@ -639,6 +738,9 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { /// Once per frame: applies what the user did in the popover and its confirmed answer, closes it when its stop or /// point goes away, and pushes the target's values for the next frame. One line of `dialogs::host::pump`. pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { + for (uid, from, to) in app.session.take_swatch_renames() { + follow_swatch_rename(app, uid, &from, &to); + } let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KIND); match dialogs.with(|host| host.take_by_id::(id)) { @@ -696,13 +798,31 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { && !owner.key.point && let Some(index) = app.session.selected_stop() { - // The stop can cross its neighbor when its location changes. + // The stop can cross its neighbor when its location changes. A swatch picked for it moves with it. + let moved = owner.key.clone(); owner.key.index = index; + dialogs.with(|host| { + if let Some(popover) = host.get_mut_by_id::(id) + && let Some(picked) = &mut popover.picked_swatch + && picked.target == moved + { + picked.target.index = index; + } + }); } if let Some((name, color)) = filed.swatch && let Some(target) = selected(app) { - pick_swatch(app, &target, &name, color); + if filed.swatch_changes_paints { + pick_swatch(app, &target, &name, color); + } + // Swatches of one color draw alike: the Swatches view shows the one picked, not the first of them. + let picked = selected(app).and_then(|target| PickedSwatch::of(app, &target, &name)); + dialogs.with(|host| { + if let Some(popover) = host.get_mut_by_id::(id) { + popover.picked_swatch = picked; + } + }); } for output in &filed.panels { // PLAN: assumed `panels::color::apply_output(app, &ColorPanelOutput)` (color-w9's decision). @@ -865,6 +985,370 @@ mod tests { } } + /// The popover over `app`, drawn and pumped each frame, open on stop 1 at its Swatches view. + fn swatches_view(app: VectorcraftApp) -> crate::tests::panel_harness::Panel { + let mut panel = crate::tests::panel_harness::Panel::new(app, |app, ui| { + app.dialogs().unwrap().with(|host| host.run(ui)); + host::pump(app, ui.ctx()); + }); + // The popover opens on the fixture's window, which the panel made the app's. + open_popover(&mut panel.app()); + set(&panel.app(), "tab", json!("swatches")).unwrap(); + panel.frame(); + panel + } + + #[test] + fn picking_one_of_two_spot_colors_of_one_color_links_the_stop_to_that_one() { + let mut app = app(); + for name in ["First green ink", "Second green ink"] { + app.run("swatch.new", json!({"name": name, "color": "#00ff00", "spot": true})).unwrap(); + } + let target = selected(&app).unwrap(); + pick_swatch(&mut app, &target, "First green ink", Color::from_hex("#00ff00").unwrap()); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First green ink")); + panel.click("Second green ink"); + assert_eq!(stops(&panel.app())[1].swatch.as_deref(), Some("Second green ink")); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second green ink"), "the view shows the swatch picked"); + panel.app().run("swatch.edit", json!({"name": "Second green ink", "color": "#123456"})).unwrap(); + assert_eq!(stops(&panel.app())[1].color.to_hex(), "#123456", "the stop follows the swatch it was given"); + } + + /// The swatch the open popover's Swatches view shows as the target's, after two fresh frames: the first one's pump + /// feeds the view an edit made outside it, and the second draws that feed. The view draws that swatch's cell + /// selected and no other, and no cell selected when it shows none. + fn shown_swatch(panel: &mut crate::tests::panel_harness::Panel) -> Option { + panel.frame(); + panel.frame(); + let (names, shown) = panel.app().dialogs().unwrap().with(|host| { + let feed = host.get_by_id::(dialog_id(KIND)).and_then(|popover| popover.feed.as_ref()).expect("the view's feed"); + let shown = feed.selected_swatch.and_then(|i| feed.swatches.get(i)).map(|(name, _)| name.clone()); + (feed.swatches.iter().map(|(name, _)| name.clone()).collect::>(), shown) + }); + let drawn: Vec = + names.into_iter().filter(|name| panel.selected_role(name, craft::ui::contract::Role::LIST_BOX_OPTION) == Some(true)).collect(); + assert_eq!(drawn, shown.iter().cloned().collect::>(), "the cells the view draws selected"); + shown + } + + #[test] + fn the_swatches_view_shows_the_process_swatch_picked_among_two_of_one_color() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel), None, "the stop's green is no swatch's"); + panel.click("Second teal"); + assert_eq!(stops(&panel.app())[1].color.to_hex(), "#008080"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click("First teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal")); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "the same color again is no edit"); + } + + #[test] + fn the_swatches_view_remembers_a_pick_of_the_fallback_swatch_after_reordering() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + crate::panels::gradient::recolor_selected(&mut app, Color::from_hex("#008080").unwrap(), &json!({})); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "the first matching process swatch is the fallback"); + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click("First teal"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "the displayed swatch changes no paint"); + let first = panel.app().session.active().unwrap().doc.swatches_iter().position(|s| s.name == "First teal").unwrap(); + panel.app().run("swatch.move", json!({"name": "Second teal", "to": first})).unwrap(); + assert_eq!( + shown_swatch(&mut panel).as_deref(), + Some("First teal"), + "the explicit pick stays selected after the other swatch moves before it" + ); + } + + #[test] + fn the_swatches_view_keeps_the_picked_process_swatch_through_a_rename() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel.app().run("swatch.edit", json!({"name": "Second teal", "newName": "Renamed teal"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Renamed teal"), "the renamed swatch stays the one shown"); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "Undo of the rename falls back to the first qualifying swatch"); + panel.click("Second teal"); + panel.app().run("swatch.edit", json!({"name": "First teal", "newName": "Other teal"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "a rename of the other swatch moves nothing"); + let first = panel.app().session.active().unwrap().doc.swatches_iter().position(|s| s.name == "Other teal").unwrap(); + panel.app().run("swatch.move", json!({"name": "Second teal", "to": first})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "the picked swatch moved before the other stays the one shown"); + } + + #[test] + fn the_swatches_view_keeps_the_picked_swatch_when_the_popover_moves_its_stop_past_a_neighbor() { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#008080"}, {"offset": 0.7, "color": "#000000"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [100, 150], "end": [200, 150]}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel.app().dialogs().unwrap().with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).expect("the popover").filed.fields.location = Some(90.0); + }); + panel.frame(); + assert_eq!(panel.app().session.selected_stop(), Some(2), "the stop crossed its neighbor"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "the pick moved with its stop"); + } + + #[test] + fn the_swatches_view_keeps_the_picked_swatch_through_a_rename_in_a_batch() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + panel + .app() + .run("command.batch", json!({"commands": [{"command": "swatch.edit", "params": {"name": "Second teal", "newName": "Renamed teal"}}]})) + .unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Renamed teal")); + } + + #[test] + fn the_swatches_view_keeps_the_pick_when_a_batch_renames_a_swatch_in_another_document() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel + .app() + .run( + "command.batch", + json!({"commands": [ + {"command": "document.activate", "params": {"index": 1}}, + {"command": "swatch.edit", "params": {"name": "Second teal", "newName": "Renamed teal"}}, + {"command": "document.activate", "params": {"index": 0}} + ]}), + ) + .unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + assert!(panel.app().session.documents()[1].doc.swatch("Renamed teal").is_some()); + } + + #[test] + fn the_swatches_view_follows_renames_that_bypass_app_run() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + panel.app().session.execute("swatch.edit", &json!({"name": "Second teal", "newName": "Renamed teal"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Renamed teal")); + } + + #[test] + fn the_swatches_view_does_not_give_a_deleted_picked_swatch_to_its_neighbor() { + let mut app = app(); + for name in ["First teal", "Second teal", "Third teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel.app().run("swatch.delete", json!({"name": "Second teal"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "the swatch after the deleted one is not taken for it"); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "Undo of the deletion shows the picked swatch again"); + } + + #[test] + fn the_swatches_view_does_not_give_a_deleted_picked_swatch_to_a_replacement() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel.app().run("swatch.delete", json!({"name": "Second teal"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal")); + panel.app().run("swatch.new", json!({"name": "New teal", "color": "#008080"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "a new swatch in the deleted one's place is not taken for it"); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal")); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "Undo of the deletion shows the picked swatch again"); + } + + #[test] + fn the_swatches_view_does_not_follow_a_replacement_in_a_batch() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel + .app() + .run( + "command.batch", + json!({"commands": [ + {"command": "swatch.delete", "params": {"name": "Second teal"}}, + {"command": "swatch.new", "params": {"name": "New teal", "color": "#008080"}} + ]}), + ) + .unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "the replacement does not inherit the pick"); + } + + #[test] + fn the_swatches_view_shows_the_tint_swatch_picked_among_two_of_one_tint() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap(); + let tints: Vec = + (0..2).map(|_| app.run("swatch.new", json!({"swatch": "Green ink", "tint": 40})).unwrap()["name"].as_str().unwrap().to_owned()).collect(); + assert_ne!(tints[0], tints[1]); + let mut panel = swatches_view(app); + panel.click(&tints[1]); + let stop = stops(&panel.app())[1].clone(); + assert_eq!((stop.swatch.as_deref(), (stop.tint * 100.0).round()), (Some("Green ink"), 40.0)); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some(tints[1].as_str())); + panel.click(&tints[0]); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some(tints[0].as_str())); + panel.click("Green ink"); + assert_eq!(stops(&panel.app())[1].tint, 1.0); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Green ink")); + } + + #[test] + fn a_spot_color_of_the_stop_color_links_the_stop_and_its_base_resets_a_tint() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap(); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel), None, "the stop's green is not linked to the ink"); + panel.click("Green ink"); + assert_eq!(stops(&panel.app())[1].swatch.as_deref(), Some("Green ink")); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Green ink")); + + // Two spot inks of the stop's green: the unlinked stop shows neither, and a pick links the stop to that one. + let mut app = self::app(); + for name in ["First green ink", "Second green ink"] { + app.run("swatch.new", json!({"name": name, "color": "#00ff00", "spot": true})).unwrap(); + } + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel), None, "the stop's green is linked to neither ink"); + panel.click("Second green ink"); + assert_eq!(stops(&panel.app())[1].swatch.as_deref(), Some("Second green ink")); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second green ink")); + + let mut app = self::app(); + app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap(); + crate::panels::gradient::recolor_selected(&mut app, Color::from_hex("#00ff00").unwrap(), &json!({"swatch": "Green ink", "tint": 40})); + assert_eq!((stops(&app)[1].tint * 100.0).round(), 40.0); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel), None, "a 40% tint is not the ink at 100%"); + panel.click("Green ink"); + let stop = stops(&panel.app())[1].clone(); + assert_eq!((stop.swatch.as_deref(), stop.tint), (Some("Green ink"), 1.0)); + } + + #[test] + fn picking_the_displayed_swatch_recolors_every_selected_objects_stop() { + let mut app = app(); + let first = app.session.active().unwrap().selection.objects[0]; + let mut second_stops = stops(&app); + second_stops[1].set_color(Color::from_hex("#0000ff").unwrap(), None); + let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"gradient": {"stops": vectorcraft_tools::params::stops_json(&second_stops)}})).unwrap(); + app.run("swatch.new", json!({"name": "Stop green", "color": "#00ff00"})).unwrap(); + app.run("select.set", json!({"ids": [first.0, second]})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Stop green")); + panel.click("Stop green"); + let app = panel.app(); + let st = app.session.active().unwrap(); + for id in &st.selection.objects { + let Paint::Gradient(paint) = st.doc.node(*id).unwrap().appearance.paint_at(None, true).unwrap() else { + panic!("expected a gradient"); + }; + assert_eq!(paint.gradient.stops[1].color.to_hex(), "#00ff00"); + } + assert_eq!(st.selection.objects.len(), 2); + } + + #[test] + fn picking_the_displayed_swatch_keeps_every_selected_objects_gradient_swatch_link() { + let mut app = app(); + let first = app.session.active().unwrap().selection.objects[0]; + app.run("swatch.new", json!({"name": "Stop green", "color": stops(&app)[1].color.to_hex()})).unwrap(); + let mut params = crate::panels::swatch_paint_params(&active_paint(&app)); + params["name"] = json!("Linked gradient"); + app.run("swatch.new", params).unwrap(); + app.run("paint.setFill", json!({"swatch": "Linked gradient"})).unwrap(); + let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"swatch": "Linked gradient"})).unwrap(); + app.run("select.set", json!({"ids": [first.0, second]})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Stop green")); + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click("Stop green"); + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.selection.objects.len(), 2); + for id in &st.selection.objects { + let Paint::Gradient(paint) = st.doc.node(*id).unwrap().appearance.paint_at(None, true).unwrap() else { + panic!("expected a gradient"); + }; + assert_eq!(paint.swatch.as_deref(), Some("Linked gradient")); + } + assert_eq!(st.history.undo.len(), undo, "the displayed swatch changes no paint"); + } + + #[test] + fn picking_the_stop_swatch_again_keeps_the_gradient_swatch_link() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap(); + let green = Color::from_hex("#00ff00").unwrap(); + let target = selected(&app).unwrap(); + pick_swatch(&mut app, &target, "Green ink", green); + let mut params = crate::panels::swatch_paint_params(&active_paint(&app)); + params["name"] = json!("Linked gradient"); + app.run("swatch.new", params).unwrap(); + app.run("paint.setFill", json!({"swatch": "Linked gradient"})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Green ink")); + panel.click("Green ink"); + let Paint::Gradient(paint) = active_paint(&panel.app()) else { panic!("expected a gradient") }; + assert_eq!(paint.swatch.as_deref(), Some("Linked gradient")); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + #[test] fn confirm_applies_colour_opacity_and_location() { let mut app = app(); @@ -886,6 +1370,33 @@ mod tests { assert!(set(&app, "color", json!("red")).is_err()); } + /// Leaving Opacity or Location on text that is not a number cancels the typing, and OK then leaves the stop as it + /// was. + #[test] + fn a_canceled_opacity_or_location_leaves_the_stop_as_it_was() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + for name in ["Opacity", "Location"] { + let mut panel = Panel::new(app(), crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open_popover(&mut panel.app()); + panel.frame(); + let before = stops(&panel.app()); + panel.click_role(name, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("40"); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel.app()), "leaving {name} keeps the popover open"); + confirm(&mut panel.app()); + assert_eq!(stops(&panel.app()), before, "OK after leaving {name} on text that is not a number leaves the stop as it was"); + } + } + #[test] fn the_popover_discards_a_pending_edit_after_selecting_other_art() { let mut app = app(); @@ -1231,7 +1742,7 @@ mod tests { let mut fx = Fixture::new(move |ui| { let mut app = app.borrow_mut(); let Some(target) = selected(&app) else { return }; - let feed = feed(&app, &target); + let feed = feed(&app, &target, None); let mut filed = Filed::default(); body(ui, &feed, &mut tab, &mut panel, &mut filed); for output in &filed.panels { diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 1eb37190e5..9cd2da74a4 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -20,7 +20,7 @@ use std::collections::BTreeMap; use std::sync::Arc; -use craft::behavior::{EditEvent, NumberCodec}; +use craft::behavior::{CancelReason, EditEvent, NumberCodec}; use craft::host::{PickRequest, Picked}; use craft::table::ui::{ CellAt, CellDirection, CellEdit, CellGrid, CellSelection, CellSpace, ColumnEdges, GridEdit, GridModel, GridState, LineIndex, Positions, @@ -140,6 +140,8 @@ struct Lines { columns: LineIndex, /// The own width of the column whose edge a drag holds, as it was when the drag began. resize_from: Option>, + /// Cell Style's Column Width and the columns' own widths, as they were when typing a Column Width began. + width_from: Option<(u64, Vec>)>, } impl Lines { @@ -149,6 +151,7 @@ impl Lines { rows: LineIndex::uniform(ROW_H, 0), columns: LineIndex::uniform(digits_px(DEFAULT_WIDTH), MAX_COLS as u32), resize_from: None, + width_from: None, } } @@ -397,7 +400,7 @@ fn graph_grid(app: &mut VectorcraftApp, graph: Option) -> Result bool { file_asks::can(app, craft::host::PickKind::Open) - && (app.host.files().browser_saves() || app.services.read_head.is_some() || app.services.read.is_some()) + && (app.files_host().files().browser_saves() || app.services.read_head.is_some() || app.services.read.is_some()) } /// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it. @@ -633,16 +636,31 @@ fn body(ui: &mut egui::Ui, values: &mut Sheet, pane: &mut Pane<'_>) -> bool { let field = whole(&units, tl!("Number of Decimals"), values.decimals.unwrap_or(DEFAULT_DECIMALS), MAX_DECIMALS) .enabled(values.decimals.is_some()) .show(ui); - if let Some(n) = digits(field.edit.value().copied().flatten(), MAX_DECIMALS) { + if let Some(n) = digits(field.edit.events.landed().copied().flatten(), MAX_DECIMALS) { values.decimals = Some(n); } Text::new(tl!("Column Width:")).show(ui); let field = whole(&units, tl!("Column Width"), width(values), MAX_WIDTH).show(ui); - // A value entered with Enter sets every column, also when it is the width shown. Leaving the - // field without a new value keeps the columns' own widths. - let typed = digits(field.edit.value().copied().flatten(), MAX_WIDTH); - if typed.is_some() || field.edit.submitted { - set_width(values, typed.unwrap_or_else(|| width(values))); + let events = &field.edit.events; + if events.began() { + lines.width_from = Some((values.width, values.widths.clone())); + } + if let Some(reason) = events.cancel_reason() { + // A user rollback restores Cell Style's width and the columns' own widths; other cancels keep the host's values. + if let Some((shown, own)) = lines.width_from.take().filter(|_| matches!(reason, CancelReason::Escape | CancelReason::Blur)) { + values.width = shown; + values.widths = own; + } + } else { + // A value entered with Enter sets every column, also when it is the width shown. Leaving the + // field without a new value keeps the columns' own widths. + let typed = digits(events.value().copied().flatten(), MAX_WIDTH); + if typed.is_some() || field.edit.submitted { + set_width(values, typed.unwrap_or_else(|| width(values))); + } + if events.ended().is_some() { + lines.width_from = None; + } } }); lines.sync(extent(values, active(state)), values); @@ -830,6 +848,9 @@ impl StackDialog for GraphDataDialog { load(&self.sheet, &self.state, &mut self.entry); } } + if matches!(field, "width" | "widths") { + self.lines.width_from = None; + } Ok(()) } } @@ -1127,8 +1148,8 @@ mod tests { app.services.read = None; app.services.read_head = None; let files = Arc::new(ScriptedFiles::held().in_browser()); + // The web shell installs its browser file service in the window's context only. app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap()); - app.host = Arc::new(app.host.with_files(files.clone())); open(&mut app).unwrap(); let mut h = harness(app); h.run_steps(4); @@ -1399,4 +1420,82 @@ mod tests { edit(&app, |d| set_col_digits(&mut d.sheet, 1, 4)); assert_eq!(read(&app, |d| (col_digits(&d.sheet, 1), col_digits(&d.sheet, 3))), (4, 7), "a drag after it gives that column its own width"); } + + /// Leaving Number of Decimals or Column Width on text that is not a number cancels the typing: the decimals go back + /// to what they were, and so do Column Width and the widths columns were given of their own. + #[test] + fn a_canceled_cell_style_number_restores_the_decimals_and_the_widths() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (app, _) = app_with(",a,b\nQ1,1,2", "column"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app()).unwrap(); + panel.frame(); + set_field(&panel.app(), "decimals", json!(2)).unwrap(); + edit(&panel.app(), |d| set_col_digits(&mut d.sheet, 1, 4)); + panel.frame(); + let style = |panel: &Panel| read(&panel.app(), |d| (d.sheet.decimals, d.sheet.width, d.sheet.widths.clone())); + for name in ["Number of Decimals", "Column Width"] { + let before = style(&panel); + panel.click_role(name, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + assert_ne!(style(&panel), before, "typing into {name} proposes a value"); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert_eq!(style(&panel), before, "leaving {name} on text that is not a number restores Cell Style"); + } + } + + /// An outside Column Width replaces a running edit and keeps the columns at the assigned width. + #[test] + fn an_outside_column_width_survives_a_running_edit() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (app, _) = app_with(",a,b\nQ1,1,2", "column"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app()).unwrap(); + panel.frame(); + edit(&panel.app(), |d| set_col_digits(&mut d.sheet, 1, 4)); + panel.frame(); + panel.click_role("Column Width", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + set_field(&panel.app(), "width", json!(13)).unwrap(); + let assigned = read(&panel.app(), |d| (d.sheet.width, d.sheet.widths.clone())); + panel.frame(); + assert_eq!(read(&panel.app(), |d| (d.sheet.width, d.sheet.widths.clone())), assigned, "the host's column widths survive cancellation"); + } + + /// Outside per-column widths survive invalid Column Width text. + #[test] + fn an_outside_per_column_width_survives_a_running_edit() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (app, _) = app_with(",a,b\nQ1,1,2", "column"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app()).unwrap(); + panel.frame(); + panel.click_role("Column Width", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + set_field(&panel.app(), "widths", json!([null, 13, null])).unwrap(); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert_eq!(read(&panel.app(), |d| d.sheet.widths.clone()), vec![None, Some(13), None], "invalid Column Width text preserves assigned widths"); + } } diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index ebc54223f6..893f2f1c38 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -2,7 +2,7 @@ //! or CMYK screens, Invert, Clip to Art and Keep Original, previewed live on the canvas; OK keeps //! the preview as one undo step (`object.vectorHalftone`). //! -//! Fields: `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal` (the +//! Fields: `style`, `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal` (the //! command's parameters). The live effect's dialog shows the same rows but Keep Original //! ([`screen_params`]). @@ -33,7 +33,20 @@ pub(crate) struct Open { /// The dialog's fields as it opens: the command's defaults. pub fn fields() -> Value { - json!({"shape": "circle", "frequency": 20, "angle": 45, "mode": "mono", "color": "#000000", "invert": false, "clip": true, "keepOriginal": false}) + json!({"style": "custom", "shape": "circle", "frequency": 20, "angle": 45, "mode": "mono", "color": "#000000", "invert": false, "clip": true, "keepOriginal": false}) +} + +/// The Style picker's choices: their ids and labels. +const STYLES: [(&str, &str); 5] = + [("custom", "Custom"), ("grid", "Grid"), ("gridAngle", "Grid Angle"), ("gridDots", "Grid Dots"), ("gridDotsAngle", "Grid Dots Angle")]; + +/// Spells a stored `style` as the picker's id, matched in any letter case as the effect reads it, +/// so the picker shows it selected and the choice ids stay the ones the dialog accepts. +pub(crate) fn canonical_style(values: &mut serde_json::Map) { + let Some(stored) = values.get("style").and_then(Value::as_str) else { return }; + if let Some((id, _)) = STYLES.iter().find(|(id, _)| id.eq_ignore_ascii_case(stored)) { + values.insert("style".into(), json!(id)); + } } /// A choice's options from `(id, label)` pairs, the labels translated. @@ -56,12 +69,17 @@ pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec { ("euclidean", "Euclidean"), ("elliptical", "Elliptical"), ]; - let mut rows = vec![ - Param::new("shape", tl!("Shape"), ParamKind::choice(options(&shapes), Some("circle".into()))), - Param::new("frequency", tl!("Frequency"), ParamKind::range(1.0, 150.0, 20.0, SliderScale::Linear)).unit(UnitKind::LinesPerInch), - Param::new("angle", tl!("Angle"), ParamKind::range(-90.0, 90.0, 45.0, SliderScale::Linear)).unit(UnitKind::Degrees), - Param::new("mode", tl!("Screens"), ParamKind::choice(options(&[("mono", "Mono"), ("cmyk", "CMYK")]), Some("mono".into()))), - ]; + let styles = STYLES; + let custom = !named_style(fields); + let mut rows = vec![Param::new("style", tl!("Style"), ParamKind::choice(options(&styles), Some("custom".into())))]; + if custom { + rows.push(Param::new("shape", tl!("Shape"), ParamKind::choice(options(&shapes), Some("circle".into())))); + } + rows.push(Param::new("frequency", tl!("Frequency"), ParamKind::range(1.0, 150.0, 20.0, SliderScale::Linear)).unit(UnitKind::LinesPerInch)); + if custom { + rows.push(Param::new("angle", tl!("Angle"), ParamKind::range(-90.0, 90.0, 45.0, SliderScale::Linear)).unit(UnitKind::Degrees)); + } + rows.push(Param::new("mode", tl!("Screens"), ParamKind::choice(options(&[("mono", "Mono"), ("cmyk", "CMYK")]), Some("mono".into())))); if live { rows.push(Param::new("fromArt", tl!("Dot Color from Art"), ParamKind::bool(false)).visible_when("mode", "mono")); } @@ -84,9 +102,14 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let defaults = fields(); let rows = screen_params(false, &DialogFields::new()); let initial = fields_of(&rows, defaults.as_object().unwrap_or(&Default::default())); - let dialog = HostedParamDialog::command(&ctx, CMD, initial, |fields| { + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::command(&ctx, CMD, initial, move |fields| { let rows = screen_params(false, fields); - ParamDialog::command(CMD, tl!("Vector Halftone"), rows).previews(true).values(Bind::bound(fields)) + let dialog = ParamDialog::command(CMD, tl!("Vector Halftone"), rows).previews(true).values(Bind::bound(fields)); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }); let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let open = app.effect_dialogs.halftone.as_ref().ok_or("the dialog is closed")?; @@ -98,7 +121,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { }; return Err(why.into()); } - let params = Value::Object(json_of(&screen_params(false, &result.fields), &result.fields)); + let params = Value::Object(command_params(&result.fields)); let mut open = app.effect_dialogs.halftone.take().ok_or("the dialog is closed")?; let done = std::mem::take(&mut open.preview).commit(app, CMD, params); if done.is_err() { @@ -119,6 +142,23 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { Ok(Value::Null) } +/// The command's parameters from the dialog's fields. With a named style, the stored Shape and +/// Angle are left out so that the style's own shape and angle apply. +pub(crate) fn command_params(fields: &DialogFields) -> serde_json::Map { + let mut params = json_of(&screen_params(false, fields), fields); + if named_style(fields) { + params.remove("shape"); + params.remove("angle"); + } + params +} + +/// Whether the stored style is a named one, which sets the shape and the angle; Custom, no style +/// and a style this build does not know keep the stored Shape and Angle, so their rows show. +fn named_style(fields: &DialogFields) -> bool { + matches!(fields.text("style").and_then(vectorcraft_effects::addons::halftone::style), Some(Some(_))) +} + /// Runs or ends the open dialog's preview for this frame. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.effect_dialogs.halftone.take() else { return }; @@ -130,7 +170,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let shown = app.dialogs().and_then(|host| { host.with(|h| { h.get_by_id::(open.id).map(|d| { - let params = json_of(&screen_params(false, d.fields()), d.fields()); + let params = command_params(d.fields()); (d.is_previewing(), Value::Object(params)) }) }) @@ -278,6 +318,77 @@ mod tests { assert_eq!(undo_steps(&panel), undo + 1, "the reopened dialog's OK is one undo step"); } + /// A named style sends no Shape or Angle, so the style's own apply; Custom sends both. + #[test] + fn a_named_style_hides_shape_and_angle() { + for (style, shown) in [("custom", true), ("gridDots", false)] { + let mut values = fields(); + values["style"] = json!(style); + let rows = screen_params(false, &DialogFields::new()); + let f = fields_of(&rows, values.as_object().unwrap()); + let sent = command_params(&f); + assert_eq!(sent.get("style"), Some(&json!(style))); + assert_eq!((sent.contains_key("shape"), sent.contains_key("angle")), (shown, shown), "{style}: {sent:?}"); + } + } + + #[test] + fn style_picker_selects_stored_styles_in_any_case() { + for (style, label) in [("GRIDDOTS", "Grid Dots"), ("CUSTOM", "Custom")] { + let mut values = fields(); + values["style"] = json!(style); + let mut values = values.as_object().unwrap().clone(); + canonical_style(&mut values); + let f = fields_of(&screen_params(false, &DialogFields::new()), &values); + let rows = screen_params(false, &f); + let row = rows.iter().find(|p| p.key == "style").unwrap(); + let ParamKind::Choice { options, .. } = &row.kind else { panic!("Style is not a choice") }; + let ids: Vec<&str> = options.iter().map(|(id, _)| id.as_str()).collect(); + assert_eq!(ids, STYLES.map(|(id, _)| id), "{style}: the choice ids stay as the dialog accepts them"); + let selected = options.iter().find(|(id, _)| Some(id.as_str()) == f.text("style")); + assert_eq!(selected.map(|(_, label)| label.as_str()), Some(label), "{style}"); + } + } + + /// A stored style matches Custom in any letter case, as the effect reads it, so Shape and + /// Angle stay on screen and OK sends both. + #[test] + fn custom_style_in_any_case_keeps_shape_and_angle() { + let mut values = fields(); + values["style"] = json!("CUSTOM"); + let f = fields_of(&screen_params(false, &DialogFields::new()), values.as_object().unwrap()); + let rows = screen_params(false, &f); + let shown = |k: &str| rows.iter().any(|p| p.key == k); + assert!(shown("shape") && shown("angle"), "Shape and Angle rows are hidden"); + let sent = command_params(&f); + assert!(sent.contains_key("shape") && sent.contains_key("angle"), "{sent:?}"); + } + + #[test] + fn only_recognized_presets_hide_shape_and_angle() { + for style in [None, Some("custom"), Some("CUSTOM"), Some(""), Some("unknown"), Some("GRIDDOTS")] { + let mut values = fields().as_object().unwrap().clone(); + values.remove("style"); + if let Some(style) = style { + values.insert("style".into(), json!(style)); + } + values.insert("shape".into(), json!("diamond")); + values.insert("angle".into(), json!(23)); + let f = fields_of(&screen_params(false, &DialogFields::new()), &values); + let shown = style != Some("GRIDDOTS"); + for live in [false, true] { + let rows = screen_params(live, &f); + for key in ["shape", "angle"] { + assert_eq!(rows.iter().any(|p| p.key == key), shown, "{style:?}, live={live}, {key}"); + } + } + let sent = command_params(&f); + for key in ["shape", "angle"] { + assert_eq!(sent.get(key), if shown { values.get(key) } else { None }, "{style:?}, {key}"); + } + } + } + /// With Preview off, OK after File > Revert is refused and leaves the restored drawing as it is. #[test] fn vector_halftone_without_preview_refuses_ok_after_file_revert() { diff --git a/crates/ui-egui/src/dialogs/host.rs b/crates/ui-egui/src/dialogs/host.rs index 38c572c1c9..82987ab202 100644 --- a/crates/ui-egui/src/dialogs/host.rs +++ b/crates/ui-egui/src/dialogs/host.rs @@ -7,6 +7,7 @@ use craft::ui::shell::WindowDialogs; use serde_json::Value; use crate::VectorcraftApp; +use crate::graphics::context_tag; /// The most dialogs waiting for an answer at once. pub(crate) const MAX_WAITING: usize = 16; @@ -45,6 +46,8 @@ type Drain = Box Option>; struct Record { id: DialogId, + /// The egui context whose dialog host shows the dialog ([`context_tag`]). + context: u64, drain: Drain, cancel: Option, } @@ -59,6 +62,20 @@ impl Held { } } +/// Cancels the held dialogs opened in another egui context than the app's current one, so every record left is +/// served by the current window's host. Each context has its own host, which numbers its openings from the start: a +/// record of the old host is never answered, and its serial can match an opening of the same key in the new one. +fn retire_other_contexts(app: &mut VectorcraftApp) { + let current = app.ui_ctx.as_ref().map(context_tag); + let (retired, kept): (Vec, Vec) = std::mem::take(&mut app.held.0).into_iter().partition(|record| Some(record.context) != current); + app.held.0 = kept; + for mut record in retired { + if let Some(cancel) = record.cancel.take() { + cancel(app); + } + } +} + fn drain(id: DialogId, serial: u64, mut ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static) -> Drain { Box::new(move |app| { // Without a window nothing can answer: the dialog counts as cancelled so its rollback runs. @@ -106,7 +123,9 @@ pub(crate) fn open_held_with( ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static, options: HeldOptions, ) -> Option { - let host = app.dialogs()?; + retire_other_contexts(app); + let ctx = app.ui_ctx.clone()?; + let host = window_dialogs(&ctx); let dialog = dialog.held_ok(); let (id, serial) = host.with(|h| { let id = match options.parent { @@ -117,7 +136,7 @@ pub(crate) fn open_held_with( })?; // A host key can be reopened before the previous result has been pumped. app.held.0.retain(|record| record.id != id); - app.held.0.push(Record { id, drain: drain::(id, serial, ok), cancel: options.cancel }); + app.held.0.push(Record { id, context: context_tag(&ctx), drain: drain::(id, serial, ok), cancel: options.cancel }); Some(id) } @@ -154,6 +173,8 @@ macro_rules! pumps { /// Runs once per frame after the shell pass: every dialog module's pump, then the held dialogs. pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { + // The dialog modules see the rollbacks of the dialogs a replaced graphics context took with it. + retire_other_contexts(app); sync(app); pumps!(app, ctx; crate::file_asks::pump, @@ -379,4 +400,56 @@ mod opening_tests { pump(&mut app, &ctx); assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted)); } + + /// Opens the test dialog with an OK and a Cancel that write `name` to `log`. + fn open_logged(app: &mut VectorcraftApp, ctx: &egui::Context, log: &Rc>>, name: &'static str) -> DialogId { + let (answered, cancelled) = (log.clone(), log.clone()); + open_held_with( + app, + dialog(ctx), + move |_, _| { + answered.borrow_mut().push(format!("{name} ok")); + Ok(()) + }, + HeldOptions { parent: None, cancel: Some(Box::new(move |_| cancelled.borrow_mut().push(format!("{name} cancel")))) }, + ) + .unwrap() + } + + #[test] + fn a_new_graphics_context_cancels_the_old_contexts_opening() { + let (mut app, ctx) = app(); + let log = Rc::new(RefCell::new(Vec::new())); + let first = open_logged(&mut app, &ctx, &log, "old"); + let old_serial = app.dialogs().unwrap().with(|h| h.open_serial(first)); + + let fresh = crate::testing::ui_context(); + app.adopt_context(&fresh); + // The new context's host numbers its openings from the start: the same key gets the old opening's serial. + let host = app.dialogs().unwrap(); + let id = host.with(|h| h.open(dialog(&fresh).held_ok())); + assert_eq!((id, host.with(|h| h.open_serial(id))), (first, old_serial)); + assert!(!host.with(|h| h.confirm_by_id(&fresh, id))); + pump(&mut app, &fresh); + assert_eq!(*log.borrow(), ["old cancel"], "the old opening's OK answered the new context's dialog"); + pump(&mut app, &fresh); + assert_eq!(*log.borrow(), ["old cancel"]); + } + + #[test] + fn reopening_a_key_in_a_new_graphics_context_cancels_the_old_opening_first() { + let (mut app, ctx) = app(); + let log = Rc::new(RefCell::new(Vec::new())); + open_logged(&mut app, &ctx, &log, "old"); + + let fresh = crate::testing::ui_context(); + app.adopt_context(&fresh); + let id = open_logged(&mut app, &fresh, &log, "new"); + assert_eq!(*log.borrow(), ["old cancel"], "the old opening's rollback was dropped"); + let host = app.dialogs().unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&fresh, id))); + pump(&mut app, &fresh); + assert_eq!(*log.borrow(), ["old cancel", "new ok"]); + assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted)); + } } diff --git a/crates/ui-egui/src/dialogs/hyphenation.rs b/crates/ui-egui/src/dialogs/hyphenation.rs index 4e9fae0914..d6767ba3bc 100644 --- a/crates/ui-egui/src/dialogs/hyphenation.rs +++ b/crates/ui-egui/src/dialogs/hyphenation.rs @@ -3,14 +3,16 @@ //! Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone and Hyphenate Capitalized //! Words. The dialog opens on the values the Paragraph panel shows (blank fields and dashed //! checkboxes where paragraphs in scope disagree). OK runs `text.setFormat` with the values that -//! changed, as one undo step, and paragraphs that differ keep the values left alone. +//! changed, as one undo step, and paragraphs that differ keep the values left alone. The options +//! below the checkbox take input only while Hyphenation is on, and Hyphenation Zone, which applies +//! only to a single-line composer, is disabled when every paragraph in scope uses another composer. //! //! Fields: `hyphenate`, `wordsLongerThan` (letters, 1..25), `afterFirst` and `beforeLast` //! (letters, 1..15), `hyphenLimit` (hyphens, 0..25, 0: no limit), `hyphenationZone` (pt) and //! `hyphenateCapitalized`, as `text.setFormat` takes them. use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; // PLAN: assumed paths of `UnitKind` and `LengthUnits` use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Map, Value, json}; @@ -27,18 +29,21 @@ const FLAGS: [&str; 2] = ["hyphenate", "hyphenateCapitalized"]; const NUMBERS: [(&str, i64, i64); 5] = [("wordsLongerThan", 1, 25), ("afterFirst", 1, 15), ("beforeLast", 1, 15), ("hyphenLimit", 0, 25), ("hyphenationZone", 0, 0)]; -/// The rows of the dialog; the zone is shown in `lengths`. -fn rows(lengths: LengthUnits) -> Vec { +/// The rows of the dialog; the zone is shown in `lengths`. Every row below the checkbox takes input +/// only while Hyphenation is on, and Hyphenation Zone is disabled when `zone` is false. +fn rows(lengths: LengthUnits, zone: bool) -> Vec { + let on = |param: Param| param.enabled_when(FLAGS[0], FieldValue::Bool(true)); let count = - |(key, lo, hi): (&str, i64, i64), label, default, unit| Param::new(key, label, ParamKind::int(Some(lo), Some(hi), default)).unit(unit); + |(key, lo, hi): (&str, i64, i64), label, default, unit| on(Param::new(key, label, ParamKind::int(Some(lo), Some(hi), default)).unit(unit)); + let zone_row = on(Param::number(NUMBERS[4].0, tl!("Hyphenation Zone:"), 0.0, 1.0, 2).length(lengths).bounds(Some(0.0), None)); vec![ Param::new(FLAGS[0], tl!("Hyphenation"), ParamKind::bool(false)), count(NUMBERS[0], tl!("Words Longer Than:"), 5, UnitKind::Letters), count(NUMBERS[1], tl!("After First:"), 3, UnitKind::Letters), count(NUMBERS[2], tl!("Before Last:"), 3, UnitKind::Letters), count(NUMBERS[3], tl!("Hyphen Limit:"), 0, UnitKind::Hyphens), - Param::number(NUMBERS[4].0, tl!("Hyphenation Zone:"), 0.0, 1.0, 2).length(lengths).bounds(Some(0.0), None), - Param::new(FLAGS[1], tl!("Hyphenate Capitalized Words"), ParamKind::bool(true)), + if zone { zone_row } else { zone_row.disabled() }, + on(Param::new(FLAGS[1], tl!("Hyphenate Capitalized Words"), ParamKind::bool(true))), ] } @@ -76,11 +81,12 @@ pub fn open(app: &mut VectorcraftApp) -> Result { set_shared(&mut fields, NUMBERS[2].0, crate::panels::paragraph::shared_hyphenation_field(app, |h| h.before_last).map(i64::from)); set_shared(&mut fields, NUMBERS[3].0, crate::panels::paragraph::shared_hyphenation_field(app, |h| h.hyphen_limit).map(i64::from)); set_shared(&mut fields, NUMBERS[4].0, crate::panels::paragraph::shared_hyphenation_zone(app)); + let zone = crate::panels::paragraph::shared_para(app, |p| p.composer.is_single_line()) != Some(false); let initial = fields.clone(); let ctx = app.ui_ctx.clone().ok_or("no window")?; let lengths = crate::canvas::rulers::general_lengths(app); let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { - ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths)).values(Bind::bound(fields)) + ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths, zone)).values(Bind::bound(fields)) }); super::host::open_held(app, dialog, move |app, result| { let mut p = params(&result.fields, &initial); @@ -221,27 +227,40 @@ mod tests { let modal = control(&tree, "Hyphenation", Role::Dialog, None); let count = control(&tree, "Words Longer Than:", Role::SpinButton, Some(modal)); let enabled = control(&tree, "Hyphenation", Role::CheckBox, Some(modal)); + let capitalized = control(&tree, "Hyphenate Capitalized Words", Role::CheckBox, Some(modal)); let footer = control(&tree, if apply { "OK" } else { "Cancel" }, Role::Button, Some(modal)); assert!(screen.expand(0.5).contains_rect(modal)); - for bounds in [count, enabled, footer] { + for bounds in [count, enabled, capitalized, footer] { assert!(bounds.is_positive() && modal.expand(0.5).contains_rect(bounds), "{lang}: {bounds:?} outside {modal:?}"); } let before = driver::fields(&app); assert_eq!(before.number("wordsLongerThan"), Some(5.0)); assert_eq!(before.bool("hyphenate"), Some(false)); assert!(before.is_mixed("afterFirst")); + assert_eq!(before.bool("hyphenateCapitalized"), Some(true)); + // The counts take input once Hyphenation is on. + click(&mut app, &mut frame, enabled.center()); + settle(&mut app, &mut frame); + let checked = draft(&app, &ctx)["hyphenate"].as_bool(); click(&mut app, &mut frame, count.center()); press(&mut app, &mut frame, Key::A, Modifiers::COMMAND); frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("8".into())]); press(&mut app, &mut frame, Key::Tab, Modifiers::NONE); settle(&mut app, &mut frame); - let typed = draft(&app, &ctx)["wordsLongerThan"].as_f64(); - click(&mut app, &mut frame, enabled.center()); let inspected = draft(&app, &ctx); let kept = (inspected["wordsLongerThan"].as_f64(), inspected["hyphenate"].as_bool()); - eprintln!("{lang}, {answer}: {modal:?}; ui.inspect after typing {typed:?}, after checkbox {kept:?}"); - if typed != Some(8.0) || kept != (Some(8.0), Some(true)) || !driver::fields(&app).is_mixed("afterFirst") { - failures.push(format!("{lang} {answer}: {typed:?}, {kept:?}")); + eprintln!("{lang}, {answer}: {modal:?}; ui.inspect after checkbox {checked:?}, after typing {kept:?}"); + if checked != Some(true) || kept != (Some(8.0), Some(true)) || !driver::fields(&app).is_mixed("afterFirst") { + failures.push(format!("{lang} {answer}: {checked:?}, {kept:?}")); + } + // Clicking another option after typing keeps the typed count. + click(&mut app, &mut frame, capitalized.center()); + settle(&mut app, &mut frame); + let inspected = draft(&app, &ctx); + let other = (inspected["wordsLongerThan"].as_f64(), inspected["hyphenateCapitalized"].as_bool()); + eprintln!("{lang}, {answer}: ui.inspect after the second checkbox {other:?}"); + if other != (Some(8.0), Some(false)) { + failures.push(format!("{lang} {answer}: after the second checkbox {other:?}")); } assert_eq!(paras(&app, id), original, "{lang}: only the draft changes while open"); if answer == "ui.dialog.confirm" { @@ -271,6 +290,7 @@ mod tests { for p in [&mut expected.0, &mut expected.1] { p.hyphenation.words_longer_than = 8; p.hyphenate = true; + p.hyphenation.capitalized = false; } if actual != expected || undo_delta != 1 { failures.push(format!( @@ -293,6 +313,7 @@ mod tests { #[test] fn hyphenation_dialog_sets_the_paragraphs_options() { let (mut app, id) = app(); + app.run("text.setFormat", json!({"ids": [id], "composer": "singleLine"})).unwrap(); app.run("ui.hyphenation", json!({})).unwrap(); let f = driver::fields(&app); assert_eq!((f.bool("hyphenate"), f.number("wordsLongerThan"), f.number("hyphenLimit")), (Some(false), Some(5.0), Some(0.0))); @@ -322,6 +343,7 @@ mod tests { app.run("text.setFormat", json!({"ids": [id], "afterFirst": 2, "start": 5, "end": 5})).unwrap(); app.run("ui.hyphenation", json!({})).unwrap(); assert!(driver::fields(&app).is_mixed("afterFirst")); + driver::set(&mut app, "hyphenate", json!(true)); driver::set(&mut app, "beforeLast", json!(4)); driver::ok(&mut app); let (first, second) = paras(&app, id); @@ -337,6 +359,82 @@ mod tests { assert!(!driver::is_open(&app)); } + /// The options below the checkbox take input only while Hyphenation is on, on screen and through + /// automation, including while the paragraphs in scope disagree on Hyphenation. + #[test] + fn hyphenation_options_take_input_only_with_hyphenation_on() { + let options = [ + ("Words Longer Than", "wordsLongerThan", json!(8)), + ("After First", "afterFirst", json!(2)), + ("Before Last", "beforeLast", json!(4)), + ("Hyphen Limit", "hyphenLimit", json!(2)), + ("Hyphenation Zone", "hyphenationZone", json!(12)), + ("Hyphenate Capitalized Words", "hyphenateCapitalized", json!(false)), + ]; + for mixed in [false, true] { + let (mut app, id) = app(); + app.run("text.setFormat", json!({"ids": [id], "composer": "singleLine"})).unwrap(); + if mixed { + app.run("text.setFormat", json!({"ids": [id], "hyphenate": true, "start": 5, "end": 5})).unwrap(); + } + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.app().run("ui.hyphenation", json!({})).unwrap(); + panel.frame(); + assert_eq!(driver::fields(&panel.app()).is_mixed("hyphenate"), mixed); + for (label, key, value) in &options { + assert!(!panel.enabled(label), "mixed {mixed}: {label} takes input with Hyphenation off"); + assert!(driver::try_set(&mut panel.app(), key, value.clone()).is_err(), "mixed {mixed}: automation set {key}"); + } + driver::set(&mut panel.app(), "hyphenate", json!(true)); + panel.frame(); + for (label, key, value) in &options { + assert!(panel.enabled(label), "mixed {mixed}: {label} is disabled with Hyphenation on"); + driver::try_set(&mut panel.app(), key, value.clone()).unwrap_or_else(|e| panic!("mixed {mixed}: {key} refused: {e}")); + } + driver::ok(&mut panel.app()); + let want = HyphenationOptions { words_longer_than: 8, after_first: 2, before_last: 4, hyphen_limit: 2, zone: 12.0, capitalized: false }; + let (first, second) = paras(&panel.app(), id); + for p in [first, second] { + assert!(p.hyphenate && p.hyphenation == want, "mixed {mixed}: {p:?}"); + } + } + } + + /// Hyphenation Zone applies only to a single-line composer: it is disabled while every paragraph + /// in scope uses another composer, and takes input when any of them uses a single-line one. The + /// other options stay available either way. + #[test] + fn hyphenation_zone_takes_input_only_with_a_single_line_composer() { + let cases = [ + (["everyLine", "everyLine"], false), + (["standardEveryLine", "everyLine"], false), + (["singleLine", "singleLine"], true), + (["standardSingleLine", "standardSingleLine"], true), + (["everyLine", "standardSingleLine"], true), + ]; + for (composers, zone) in cases { + let (mut app, id) = app(); + app.run("text.setFormat", json!({"ids": [id], "hyphenate": true})).unwrap(); + for (at, composer) in [0, 5].into_iter().zip(composers) { + app.run("text.setFormat", json!({"ids": [id], "composer": composer, "start": at, "end": at})).unwrap(); + } + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.app().run("ui.hyphenation", json!({})).unwrap(); + panel.frame(); + assert_eq!(panel.enabled("Hyphenation Zone"), zone, "{composers:?}: Hyphenation Zone on screen"); + assert!(panel.enabled("Words Longer Than"), "{composers:?}"); + let set = driver::try_set(&mut panel.app(), "hyphenationZone", json!(36)); + assert_eq!(set.is_ok(), zone, "{composers:?}: automation set the zone: {set:?}"); + driver::set(&mut panel.app(), "wordsLongerThan", json!(7)); + driver::ok(&mut panel.app()); + let want = if zone { 36.0 } else { 0.0 }; + let (first, second) = paras(&panel.app(), id); + for p in [first, second] { + assert_eq!((p.hyphenation.zone, p.hyphenation.words_longer_than), (want, 7), "{composers:?}"); + } + } + } + #[test] fn hyphenation_confirm_keeps_the_opening_selection() { let (mut app, first) = app(); diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index d128aba2e4..0c2f8503ef 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -647,14 +647,16 @@ pub(crate) fn preferred_text_as(app: &VectorcraftApp) -> TextAs { /// or `.ait` file opens as it says: Outlines would open it from its PDF content, without its /// editing data. So does an open with `linkPages`, which refuses Outlines: a linked page shows the /// file's own text. -pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], p: &Value) -> Value { +pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], mut p: Value) -> Value { let given = p.get("textAs").is_some_and(|v| !v.is_null()); let linked = p.get("linkPages").and_then(Value::as_bool) == Some(true); let options = p.is_object() || p.is_null(); if given || linked || !options || preferred_text_as(app) == TextAs::Text || fileio::detect(name, bytes).map(|f| f.id) != Some("pdf") { - return p.clone(); + return p; + } + if !p.is_object() { + p = json!({}); } - let mut p = if p.is_object() { p.clone() } else { json!({}) }; p["textAs"] = json!(TextAs::Outlines.id()); p } diff --git a/crates/ui-egui/src/dialogs/indexed_color.rs b/crates/ui-egui/src/dialogs/indexed_color.rs index 0f1aec1462..d9850c0edd 100644 --- a/crates/ui-egui/src/dialogs/indexed_color.rs +++ b/crates/ui-egui/src/dialogs/indexed_color.rs @@ -103,7 +103,11 @@ pub fn open(app: &mut VectorcraftApp) { if let Some(old) = app.object_dialogs.indexed.take() { old.cancel_preview(app); } - let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::new(), build); + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::new(), move |fields| match canvas { + Some(canvas) => build(fields).canvas(canvas), + None => build(fields), + }); let opening = Arc::new(()); let cancelled = Arc::clone(&opening); let ok = |app: &mut VectorcraftApp, r: &ParamResult| { diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index 0553775449..0b4f34e7bc 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -11,6 +11,7 @@ use std::cell::RefCell; +use craft::behavior::CancelReason; // PLAN: `craft::color_ui` and `craft::theme` need the `craft` facade (feature `color-ui`) in ui-egui's Cargo.toml, which has only `craft-ui`; the owner of the craft-libs pin adds it. use craft::color_ui::ui::{ChosenColor, ColorChoice, NamedColor}; use craft::theme::Srgba; @@ -72,6 +73,8 @@ pub(crate) struct LayerOptionsValue { ids: Vec, /// The fields set in the dialog, by its controls or `ui.dialog.set`. set: Vec<&'static str>, + /// While a typed percentage runs: whether the percentage was set in the dialog when the typing began. + dim_set_before_typing: Option, opened: Option, } @@ -93,6 +96,7 @@ impl Default for LayerOptionsValue { mode: "edit", ids: Vec::new(), set: Vec::new(), + dim_set_before_typing: None, opened: None, } } @@ -362,10 +366,22 @@ fn body(ui: &mut egui::Ui, v: &mut LayerOptionsValue, requested: &RefCell