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 becfca919b..53a9be4e4a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,24 +9,28 @@ 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: # Same craft-fonts commit as release.yml. - craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c # A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change) # took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with # those steps and the save it needs about two hours. @@ -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/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index c74a3e83ab..4edc2fbfdc 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -29,7 +29,7 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: require-craft-fonts: true - craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c run-package-check: true # The test builds of this workspace's largest crates (engine, ui-egui) need more than the # VM's 12 GB when two compile at once: the build was killed (exit 137) every night with diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml index 59536dcf36..2ae797d92d 100644 --- a/.github/workflows/nightly-macos.yml +++ b/.github/workflows/nightly-macos.yml @@ -47,7 +47,7 @@ jobs: - name: Check out craft-fonts uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main with: - ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c - id: rust uses: storytold/craft-common-actions/actions/rust-channel@main with: diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index c2224a81ba..4d11ae3d96 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -28,7 +28,7 @@ jobs: tooling-revision: main app-name: vectorcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' - craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c # One producer run builds every listed platform for one all-or-nothing release. The pin is the # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, # #369 and #364). diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ea3bf92583..020f90e1ec 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,7 +44,7 @@ jobs: app-title: VectorCraft macos-runner: macos-15 macos-split-build: true - craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c web-craft-fonts: true version: ${{ inputs.version }} contributors-artifact: ${{ needs.credits.outputs.artifact-name }} diff --git a/AGENTS.md b/AGENTS.md index a8f8b84f7e..2e02266c6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,14 +69,14 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- - `crates/*`: engine, tools, format, svg, pdf, text, theme, mcp and the egui frontend `crates/ui-egui`; `apps/{vectorcraft, vectorcraft-cli, vectorcraft-web}`; `xtask`. `cargo xtask layers` enforces the layering: nothing below L6 depends on egui, eframe, winit or rfd. - Commands live in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`); UI-only commands in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). Colours come from `theme::Tokens`. - Control channel methods: `crates/ui-egui/src/control.rs`. MCP: `docs/mcp.md`. -- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch. +- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch. Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `docs/ui-parity.md` has a Headless column on the Summary table and every behaviour table; every row is `unknown` until checked (350 unknown today). A checked row may be marked `no ()` or `partial ()` with `window`, `os` or `engine-gap` (a `partial` row's notes say which part works); `yes` only when the row cites a registry command id (LightCraft's `cmd:` is the model). Some rows already cite ids such as `toolbar.show`, but none is a registry command id yet, and desktop-only ids (including `crates/mcp/src/ui_catalog.rs`) do not count. Update the summary counts when you mark rows. - Build, test, fonts, localisation, cursors and robustness details: [`docs/development.md`](docs/development.md). Releases: [`docs/releasing.md`](docs/releasing.md). ### Checks 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 9a3010412f..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", @@ -1231,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-automation", "craft-behavior", @@ -1272,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "crc32fast", "flate2", @@ -1283,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1295,7 +1295,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "rustix 1.1.6", ] @@ -1303,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-docpath", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "crc32fast", "flate2", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "md-5", "rayon", @@ -1390,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-cms", @@ -1415,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1426,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1436,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1470,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "blake3", "craft-ecproj-format", @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1513,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-codepage", "encoding_rs", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", "serde_json", @@ -1535,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1574,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1583,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "cap-primitives", "craft-atomic", @@ -1606,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1640,7 +1640,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-dds", "craft-jpeg", @@ -1697,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1715,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "thiserror 2.0.21", ] @@ -1723,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1734,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-host", "craft-i18n", @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-i18n", @@ -1763,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -1781,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1793,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "encoding_rs", "image", @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "chrono", "craft-codepage", @@ -1814,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "uds_windows", "winsafe", @@ -1823,7 +1823,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-keymap", @@ -1836,10 +1836,19 @@ 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" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", "serde", @@ -1850,7 +1859,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1862,7 +1871,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "async-channel", "async-io", @@ -1895,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1904,7 +1913,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -1928,7 +1937,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1939,7 +1948,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-eps", "flate2", @@ -1953,7 +1962,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "encoding_rs", "flate2", @@ -1964,7 +1973,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "dispatch2", "egui", @@ -1977,7 +1986,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1996,7 +2005,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-atomic", "craft-host", @@ -2013,7 +2022,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "fax", "hayro-ccitt", @@ -2024,7 +2033,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2045,7 +2054,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2057,7 +2066,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2079,10 +2088,18 @@ 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" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2097,7 +2114,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-atomic", "craft-behavior", @@ -2112,7 +2129,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2122,7 +2139,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2131,7 +2148,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2146,12 +2163,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2165,9 +2182,10 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", + "craft-font-catalog", "craft-i18n", "craft-keymap", "craft-theme", @@ -2181,7 +2199,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "accesskit", "craft-behavior", @@ -2219,7 +2237,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2230,7 +2248,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2248,7 +2266,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2269,7 +2287,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2290,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2309,7 +2327,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.22.1", "chrono", @@ -2341,7 +2359,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", "serde", @@ -2352,7 +2370,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2362,7 +2380,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "js-sys", "serde_json", @@ -2373,7 +2391,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "winsafe", ] @@ -2381,7 +2399,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-appkit", "craft-atomic", @@ -2413,7 +2431,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2758,7 +2776,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "bytemuck", "emath", @@ -2791,7 +2809,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "bytemuck", @@ -2826,7 +2844,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "accesskit", "ahash", @@ -2845,7 +2863,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "bytemuck", @@ -2864,7 +2882,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "accesskit_winit", "arboard", @@ -2882,6 +2900,7 @@ dependencies = [ "raw-window-handle", "smithay-clipboard", "web-time", + "webbrowser", "windows-sys 0.61.2", "winit", ] @@ -2889,7 +2908,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "egui", @@ -2903,7 +2922,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "bytemuck", "egui", @@ -2916,7 +2935,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "dify", "eframe", @@ -2942,7 +2961,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "bytemuck", ] @@ -3023,7 +3042,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "bytemuck", @@ -3049,7 +3068,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -3772,7 +3791,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3781,7 +3800,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3799,7 +3818,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3817,12 +3836,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", "hayro-ccitt", @@ -4805,7 +4824,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4962,7 +4981,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -8740,6 +8759,7 @@ dependencies = [ "skrifa 0.47.0", "thiserror 2.0.21", "tiff", + "unicode-normalization", "vectorcraft-affinity", "vectorcraft-apischema", "vectorcraft-brush", @@ -9100,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", @@ -9622,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" @@ -10417,7 +10454,9 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" name = "xtask" version = "0.25.1" dependencies = [ + "craft-fonts-build", "serde_json", + "tempfile", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index e1a20cac68..7dab0c8895 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,51 +10,53 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +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 = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -194,22 +196,22 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } 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 894065391d..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. @@ -155,6 +160,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen arc size with Ctrl+wheel: over the canvas, a touchpad scroll or a mouse wheel turned with Ctrl makes the arc size 15° larger or smaller per step, as `]` and `[` do, and the view stays put (`tool.quickPen.arcLarger`, `tool.quickPen.arcSmaller`; part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. @@ -171,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. @@ -182,6 +189,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged. +- 2026-12-01: Common Tangents and Smooth Bridge are one dialog, Common Tangents… (#10465): Connect tangents joins the two tangents of each kind into one closed shape, and with External, Straight or Curved picks between the tangent lines and Smooth Bridge's curved outline, with Radius, Constant Gap, Reach and Keep Originals; the Smooth Bridge… menu item is gone, and `addon.pathtools.bridge` still runs and opens the dialog with External and Curved (`connect` and `curved` on `addon.pathtools.commonTangents`). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. 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/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index e533d00b73..e4d26a0b6a 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -629,6 +629,7 @@ mod tests { /// On Windows `busy_cores` gives a number between 0 and the cores. #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_reads_how_many_cores_are_busy() { let cores = std::thread::available_parallelism().map_or(1, |c| c.get()); @@ -639,6 +640,7 @@ mod tests { /// On Windows `rss_mb` gives this process's working set: more than 0 MB and less than /// 10,000 MB. #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_reads_the_working_set() { let mb = rss_mb().map(|(mb, _)| mb); @@ -654,8 +656,7 @@ mod tests { let held = rss_mb(); drop(buffer); let (Some((held, _)), Some((now, peak))) = (held, rss_mb()) else { - eprintln!("no memory reading (Linux without `ps`): nothing to check"); - return; + panic!("rss_mb gave no memory reading"); }; assert!(peak.is_some_and(|peak| peak > held - 16.0), "holding 64 MB: {held:.1} MB, after freeing it: {now:.1} MB, peak {peak:?}"); } 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-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 30d529a5e7..70aae32f73 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } 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/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index 4b660854f6..118a78006c 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -553,10 +553,9 @@ fn the_saved_engine_preference_is_found() { let saved = prefs.to_json(); assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power); } - // Every choice Preferences offer means something here. - for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES { - assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}"); - } + // Preferences offer the three choices read above, and no other. + let offered: Vec<&str> = vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES.iter().map(|(value, _)| *value).collect(); + assert_eq!(offered, ["automatic", "lowPower", "highPerformance"]); } #[test] diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 47813f192e..9e416d7711 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -188,7 +188,7 @@ pub(crate) fn services(window: Parent) -> Services { check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))), open_in_application: Some(Box::new(open_in_application)), // File → Print: the system's printers and print queue. - print: Some(Box::new(printing::SystemPrint)), + print: Some(Box::new(printing::SystemPrint::default())), // The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens // only while the active tool uses the wheel. #[cfg(all(windows, not(target_vendor = "win7")))] diff --git a/apps/vectorcraft/src/mac_color_space.rs b/apps/vectorcraft/src/mac_color_space.rs index 3fa1394804..ccdb340ec2 100644 --- a/apps/vectorcraft/src/mac_color_space.rs +++ b/apps/vectorcraft/src/mac_color_space.rs @@ -99,6 +99,7 @@ mod tests { } /// A layer without a color space is tagged sRGB once; the second call leaves it as it is. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn an_untagged_layer_becomes_srgb() { let layer = CAMetalLayer::new(); @@ -110,6 +111,7 @@ mod tests { } /// A layer with a color space of its own keeps it. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn a_layer_with_a_color_space_keeps_it() { let layer = CAMetalLayer::new(); @@ -121,6 +123,7 @@ mod tests { /// The Metal layer is found as the view's layer or as one of its sublayers, and only Metal /// layers are returned. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn metal_layers_are_found_under_the_view_layer() { let metal = CAMetalLayer::new(); diff --git a/apps/vectorcraft/src/mac_fonts.rs b/apps/vectorcraft/src/mac_fonts.rs index 36223c559f..4e9f996d62 100644 --- a/apps/vectorcraft/src/mac_fonts.rs +++ b/apps/vectorcraft/src/mac_fonts.rs @@ -52,6 +52,7 @@ mod tests { use objc2_core_text::{CTFontManagerRegisterFontsForURL, CTFontManagerScope, CTFontManagerUnregisterFontsForURL}; /// CoreText lists the installed fonts, by their files' full paths. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn coretext_lists_the_installed_font_files() { let files = super::font_files(); @@ -61,6 +62,7 @@ mod tests { /// A font registered with CoreText from another folder, as apps and font managers register /// fonts, is listed while it is registered. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn fonts_registered_from_other_folders_are_listed() { let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap(); diff --git a/apps/vectorcraft/src/open_documents.rs b/apps/vectorcraft/src/open_documents.rs index 67f409b0e8..a126618ee0 100644 --- a/apps/vectorcraft/src/open_documents.rs +++ b/apps/vectorcraft/src/open_documents.rs @@ -94,6 +94,7 @@ mod tests { use super::*; /// Files queue until the UI takes them; URLs that aren't files are left out. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn opened_files_wait_for_the_ui() { let web = NSURL::URLWithString(&NSString::from_str("https://example.com/a.svg")).unwrap(); diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index 09c57f22e4..636b8c81ef 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -4,7 +4,7 @@ use std::path::PathBuf; use std::sync::{Mutex, PoisonError}; use std::time::{Duration, Instant}; -use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings}; +use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SectionError, SettingsStore, SharedSettings}; use vectorcraft_ui_egui::{AppSettings, from_app, parse_legacy}; use super::{VectorcraftApp, prefs_dir}; @@ -18,6 +18,15 @@ fn legacy_dir() -> Option { prefs_dir::profile::prefs_dir(true) } +/// Parses the one `ui.json` slot of a legacy import: its bytes, or why it could not be read. +fn parse_legacy_slot(slots: &[Result, &std::io::Error>]) -> Result<(AppSettings, Vec), String> { + match slots.first() { + Some(Ok(Some(bytes))) => parse_legacy(bytes), + Some(Err(e)) => Err(e.to_string()), + _ => Err("the preferences file is missing".to_string()), + } +} + /// Where the log files live: `logs` in the preferences folder (see `logging`). pub(crate) fn log_dir() -> Option { Some(prefs_dir::prefs_dir()?.join("logs")) @@ -34,7 +43,7 @@ pub(crate) fn prefs_enabled() -> bool { pub(crate) fn open_store() -> (SharedSettings, LoadReport) { let (location, legacy) = match prefs_dir::prefs_dir().filter(|_| prefs_enabled()) { Some(dir) => { - let file = |dir: PathBuf| LegacyFile { path: dir.join(LEGACY_FILE), parse: parse_legacy }; + let file = |dir: PathBuf| LegacyFile { paths: vec![dir.join(LEGACY_FILE)], parse: parse_legacy_slot }; let legacy = std::iter::once(file(dir.clone())).chain(legacy_dir().map(file)).collect(); (Location::Dir(dir), legacy) } diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index fb28192f05..651be6f6a3 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -1,11 +1,16 @@ //! Desktop printer transport. VectorCraft composes every page and copy before submission; //! craft-print owns discovery and spooling. use std::process::Command; -use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer}; +use vectorcraft_ui_egui::print::{Paper, Papers, PrintJob, PrintService, Printer}; mod direct_pdf; -pub struct SystemPrint; +#[derive(Default)] +pub struct SystemPrint { + /// The paper-size lookup in flight, dropped when its worker answers or disconnects. + papers: PaperLookup, +} + impl PrintService for SystemPrint { fn printers(&mut self) -> Vec { system::printers() @@ -14,8 +19,14 @@ 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| SystemPrint.print(job))) + 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 @@ -28,6 +39,102 @@ impl PrintService for SystemPrint { fn setup(&mut self, printer: Option<&str>) -> Result<(), String> { system::setup(printer) } + fn scripts_may_print(&self) -> bool { + true + } + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + self.papers.poll(printer, fresh, std::time::Instant::now(), |printer| installed_papers(&printer)) + } +} + +/// 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 { + 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 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)); + } + 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.current = None; + result + } +} + +/// Look up only an installed printer's own name. +fn installed_papers(printer: &str) -> Vec { + if printer.is_empty() || !system::printers().iter().any(|p| p.name == printer) { + return Vec::new(); + } + system::papers(printer) } /// The status after the job `title` went to `printer` (the default one without a name), with the @@ -40,18 +147,256 @@ fn sent(title: &str, printer: Option<&str>, note: &str) -> String { } mod system { - use super::{Command, PrintJob, Printer}; + use super::{Command, Paper, PrintJob, Printer}; 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)] + { + // The name goes in as an environment variable, never into the script's text. + const SCRIPT: &str = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Add-Type -AssemblyName System.Drawing; $s = New-Object System.Drawing.Printing.PrinterSettings; \ + $s.PrinterName = $env:VC_PRINTER; foreach ($p in $s.PaperSizes) { \"$($p.RawKind)`t$($p.PaperName)`t$($p.Width)`t$($p.Height)\" }"; + use std::os::windows::process::CommandExt as _; + // CREATE_NO_WINDOW: no console window opens over the app. + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let mut command = Command::new("powershell.exe"); + command.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("VC_PRINTER", printer).creation_flags(CREATE_NO_WINDOW); + paper_output(&mut command).map(|out| vectorcraft_ui_egui::print::windows_papers(&String::from_utf8_lossy(&out))).unwrap_or_default() + } + #[cfg(not(windows))] + { + use std::io::Read as _; + // CUPS queue names never hold `/`, so the name can't leave the PPD folder. + if printer.contains(['/', '\\']) || printer.starts_with('.') { + 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; + } + } + // 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. + fn paper_output(command: &mut Command) -> Option> { + use std::io::Read as _; + use std::process::Stdio; + use std::time::{Duration, Instant}; + + const LIMIT: Duration = Duration::from_secs(10); + let started = Instant::now(); + let mut child = command.stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?; + let (send, receive) = std::sync::mpsc::channel(); + let stdout = child.stdout.take(); + let reader = std::thread::Builder::new().name("printer-paper-output".into()).spawn(move || { + let mut bytes = Vec::new(); + // Retain at most 16 MiB, but drain the rest so the child can finish. + let read = stdout.map(|mut out| { + out.by_ref().take(16 << 20).read_to_end(&mut bytes)?; + std::io::copy(&mut out, &mut std::io::sink()) + }); + let _ = send.send(read.and_then(Result::ok).map(|_| bytes)); + }); + if reader.is_err() { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + loop { + match child.try_wait() { + Ok(Some(status)) => { + return if status.success() { receive.recv_timeout(LIMIT.saturating_sub(started.elapsed())).ok().flatten() } else { None }; + } + Ok(None) if started.elapsed() < LIMIT => std::thread::sleep(Duration::from_millis(25)), + _ => { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + } + } + } pub fn print(job: &PrintJob) -> Result { 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 { @@ -130,6 +475,158 @@ mod tests { } } +#[cfg(test)] +mod paper_lookup_tests { + use super::PaperLookup; + use vectorcraft_ui_egui::print::{Paper, Papers}; + + fn paper(key: &str) -> Vec { + vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }] + } + + /// 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 lookup.poll(printer, false, now, |_| panic!("polling starts no lookup")) { + Papers::Ready(papers) => return papers, + Papers::Pending => std::thread::yield_now(), + } + } + } + + /// 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)), + } + } + + /// A read that answers `key` once `gate` lets it. + fn gated(key: &'static str) -> (std::sync::mpsc::Sender<()>, impl FnOnce(String) -> Vec + Send + 'static) { + let (open, gate) = std::sync::mpsc::channel::<()>(); + (open, move |_| { + let _ = gate.recv(); + paper(key) + }) + } + + #[test] + 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, at(0), read), Papers::Pending)); + let (other, read) = gated("Office"); + 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, 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)] mod turn_tests { use super::sent; @@ -146,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/brush/src/tests.rs b/crates/brush/src/tests.rs index 01821a08f1..7abfb33a4e 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2220,7 +2220,10 @@ fn brushes_without_modes_vary_randomly_as_before() { serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"]) ); - assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id())); + let ids: Vec<&str> = Variation::ALL.iter().map(|v| v.id()).collect(); + assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(ids), "saved names are the ids"); + assert_eq!(Variation::parse("stylusWheel"), Some(Variation::StylusWheel)); + assert_eq!(Variation::parse("wheel"), None); assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel)); } @@ -2228,6 +2231,7 @@ fn brushes_without_modes_vary_randomly_as_before() { #[test] fn junk_pressure_brushes_draw_finite_art() { let bp = preview_path(120.0, 24.0); + let mut drawn = 0; for (size, var) in [(1e308, 1e308), (-1e308, 1e308), (0.0, -1e308), (f64::MAX, f64::MAX)] { for profile in [vec![], vec![(0.0, 2.0), (0.0, -1.0), (5.0, 0.5)], vec![(1.0, 1.0), (0.0, 0.0)]] { let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(size, var), &bp, &pressed(profile)); @@ -2236,8 +2240,10 @@ fn junk_pressure_brushes_draw_finite_art() { all_points(n, &mut pts); } assert!(pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{size} {var}"); + drawn += usize::from(!pts.is_empty()); } } + assert_eq!(drawn, 12, "brushes that draw"); } /// A scatter brush of 10 × 4 pt rectangles whose size goes from `lo` % to `hi` % as `mode` says. diff --git a/crates/cad/src/hpgl/tests.rs b/crates/cad/src/hpgl/tests.rs index 9a350707a6..fdc31cb6cf 100644 --- a/crates/cad/src/hpgl/tests.rs +++ b/crates/cad/src/hpgl/tests.rs @@ -131,7 +131,7 @@ fn pens_pick_colors_and_widths() { let i = plot("IN;SP1;PW1;PD0,0,10,0;PU;PW2,2;SP2;PD0,10,10,10;PU;SP1;PD0,20,10,20;PU;IN;SP1;PD0,30,10,30;"); let widths: Vec = leaves(&i.document).iter().map(|n| stroke(n).width).collect(); let want = [MM, 2.0 * MM, MM, 0.35 * MM]; - assert!(widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}"); + assert!(widths.len() == want.len() && widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}"); } #[test] 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/cad/src/tests.rs b/crates/cad/src/tests.rs index 6140395323..16f4f97082 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1448,7 +1448,8 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() { let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 50.0, 140.0, 90.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let o = DxfOptions { crop: true, ..opts(&d) }; - assert!(!kinds(&export(&d, &o).unwrap()).is_empty()); + // The red fill: its outline and its hatch. + assert_eq!(kinds(&export(&d, &o).unwrap()), ["LWPOLYLINE", "HATCH"]); } /// An instance stained blue by its fill writes its symbol's red art in blue, as the canvas draws it. diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index c4338c289e..d622332c32 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -313,8 +313,10 @@ mod tests { assert_eq!(BlendMode::parse("ColorBurn"), Some(BlendMode::ColorBurn)); assert_eq!(BlendMode::parse("soft_light"), Some(BlendMode::SoftLight)); assert_eq!(BlendMode::parse("nope"), None); - for m in BlendMode::ALL { - assert_eq!(BlendMode::parse(m.label()), Some(m)); - } + assert_eq!(BlendMode::parse(""), None); + // A label that starts another one names its own mode. + assert_eq!(BlendMode::parse("Color"), Some(BlendMode::Color)); + assert_eq!(BlendMode::parse("Color Dodge"), Some(BlendMode::ColorDodge)); + assert_eq!(BlendMode::parse("HARD-LIGHT"), Some(BlendMode::HardLight)); } } diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 761a121191..47131dc678 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -15,11 +15,14 @@ fn de(a: [f32; 3], b: [f32; 3]) -> f32 { #[test] fn intents_parse_and_name() { - for i in Intent::ALL { - assert_eq!(Intent::parse(i.id()), Some(i)); - assert_eq!(Intent::parse(i.label()), Some(i)); - } + // The id settings save and the label the menu shows both read back, in any case and spacing. + assert_eq!(Intent::RelativeColorimetric.id(), "relative"); + assert_eq!(Intent::parse("relative"), Some(Intent::RelativeColorimetric)); + assert_eq!(Intent::parse("Relative Colorimetric"), Some(Intent::RelativeColorimetric)); + assert_eq!(Intent::parse("absolute_colorimetric"), Some(Intent::AbsoluteColorimetric)); + assert_eq!(Intent::parse("PERCEPTUAL"), Some(Intent::Perceptual)); assert_eq!(Intent::parse("bogus"), None); + assert_eq!(Intent::parse(""), None); } #[test] @@ -322,21 +325,29 @@ fn bad_icc_rejected() { assert!(matches!(register_icc(b"not a profile", None), Err(CmsError::BadProfile(_)))); } -#[cfg(target_os = "macos")] +/// A profile file is read and registered as its bytes are: a missing file is an I/O error naming +/// the path, a file that is not a profile is refused as one, and a file holding a built-in +/// profile is refused for its name. +#[cfg(not(target_arch = "wasm32"))] #[test] -fn loads_system_cmyk_icc() { - let path = std::path::Path::new("/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc"); - if !path.exists() { - return; +fn loads_icc_files_and_refuses_bad_ones() { + let dir = std::env::temp_dir().join(format!("vectorcraft-color-icc-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let missing = dir.join("missing.icc"); + match load_icc_file(&missing) { + Err(CmsError::Io(e)) => assert!(e.contains("missing.icc"), "{e}"), + other => panic!("{other:?}"), } - let info = load_icc_file(path).unwrap(); - assert_eq!(info.kind, ProfileKind::Cmyk); - assert!(profiles().iter().any(|p| p.name == info.name && !p.builtin)); - let c = Cms::new(&ColorSettings { cmyk: info.name.clone(), ..Default::default() }).unwrap(); - let rgb = [0.7, 0.5, 0.4]; - let back = c.cmyk_to_srgb(c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric), false); - assert!(de(rgb, back) < 5.0, "{back:?}"); - assert_eq!(c.cmyk_to_srgb([0.0; 4], false).map(|v| (v * 255.0).round() as u8), [255, 255, 255]); + let junk = dir.join("junk.icc"); + std::fs::write(&junk, b"not a profile").unwrap(); + assert!(matches!(load_icc_file(&junk), Err(CmsError::BadProfile(_)))); + let builtin = dir.join("generic.icc"); + std::fs::write(&builtin, &*icc_bytes(GENERIC_CMYK).unwrap()).unwrap(); + match load_icc_file(&builtin) { + Err(CmsError::Unsupported(e)) => assert!(e.contains("built-in"), "{e}"), + other => panic!("{other:?}"), + } + std::fs::remove_dir_all(&dir).unwrap(); } /// With black-point compensation, sRGB black separates to the press's black point and that black @@ -568,10 +579,10 @@ fn a_document_gets_the_same_context_for_the_same_profiles() { /// settings saved before the policies existed read with the default policy. #[test] fn policies_parse_and_default_in_saved_settings() { - for p in Policy::CMYK { - assert_eq!(Policy::parse(p.id()), Some(p)); - } + assert_eq!(Policy::parse("preserveNumbers"), Some(Policy::PreserveNumbers)); + assert_eq!(Policy::parse("convert"), Some(Policy::Convert)); assert_eq!(Policy::parse("bogus"), None); + assert_eq!(Policy::parse("Preserve Numbers"), None, "only ids parse"); assert!(!Policy::RGB.contains(&Policy::PreserveNumbers)); let old: ColorSettings = serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap(); diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index 3506bcb856..8cefd7cfe5 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -395,5 +395,5 @@ fn cmyk_to_cmyk_compensates_the_black_point() { assert_ne!(convert(true), convert(false)); // White is untouched. let white = generic.to_same_model_of(&device, &[0.0; 4], rel, true).unwrap(); - assert!(white.iter().all(|v| *v < 0.01), "{white:?}"); + assert!(white.len() == 4 && white.iter().all(|v| *v < 0.01), "{white:?}"); } diff --git a/crates/color/src/cms/tests_measured.rs b/crates/color/src/cms/tests_measured.rs index 7bf5735c7a..cd2e06a70e 100644 --- a/crates/color/src/cms/tests_measured.rs +++ b/crates/color/src/cms/tests_measured.rs @@ -108,6 +108,7 @@ fn the_fit_predicts_patches_it_left_out() { let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0); let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0); let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p)); + assert!(!left.is_empty(), "{}: nothing left out", c.reference); assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference); let kept: Vec = kept.into_iter().copied().collect(); let left: Vec = left.into_iter().copied().collect(); diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 5982e37552..0f520b2f9d 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -464,9 +464,10 @@ impl Gradient { self.repeats.clamp(1, MAX_REPEATS) } /// Does it paint something other than its end colors past the ends of its stops, or run its - /// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects? + /// stops more than once: a linear, radial, conic or diamond gradient with stops that repeats or + /// reflects? One without stops paints as one that pads. pub fn is_spread(&self) -> bool { - !self.spread.is_pad() && self.kind != GradientKind::Freeform + !self.spread.is_pad() && self.kind != GradientKind::Freeform && !self.stops.is_empty() } /// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever /// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal diff --git a/crates/color/src/gradient/spread/tests.rs b/crates/color/src/gradient/spread/tests.rs index ab088293da..c42b1acd61 100644 --- a/crates/color/src/gradient/spread/tests.rs +++ b/crates/color/src/gradient/spread/tests.rs @@ -36,6 +36,10 @@ fn spread_maps_the_parameter_to_a_place_along_the_stops() { let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3); assert_eq!(free.spread_param(0.7), 0.7); assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread()); + // Without stops it paints as one that pads. + let empty = Gradient { stops: vec![], ..repeat.clone() }; + assert!(!empty.is_spread()); + assert_eq!(empty.painted_spread(), (GradientSpread::Pad, 1)); assert!(repeat.spread_param(f64::NAN).is_nan()); // A count out of range (set in code) counts as the nearest one in range. assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1); diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 4d5c84c01f..fd39d0b94e 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -184,6 +184,7 @@ fn reverse_mirrors_midpoints() { r.reverse(); let mids: Vec = r.stops.iter().map(|s| s.midpoint).collect(); let want: Vec = g.stops.iter().rev().skip(1).map(|s| 1.0 - s.midpoint).chain([0.5]).collect(); + assert_eq!(mids.len(), g.stops.len(), "reversing keeps every stop"); assert!(mids.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6), "{mids:?} {want:?}"); for i in 0..=20 { let t = i as f32 / 20.0; @@ -291,6 +292,7 @@ fn remove_keeps_two() { fn move_reorders_and_tracks_index() { let g = g3(); let (v, i) = move_stop(&g.stops, 0, 0.8); + assert_eq!(v.len(), g.stops.len(), "moving keeps every stop"); assert_eq!(i, 1); assert_eq!(v[1].color.to_hex(), "#ffffff"); assert!(v.windows(2).all(|w| w[0].offset <= w[1].offset)); @@ -1176,7 +1178,8 @@ fn a_conic_with_no_extent_or_bad_numbers_still_sweeps() { assert!(t(90.0, 50.0).abs() < 1e-12, "{g:?}"); assert!((t(50.0, 90.0) - 0.25).abs() < 1e-12, "{g:?}"); let wedges = g.conic_wedges(Rect::new(0.0, 0.0, 100.0, 100.0), 4, false); - assert!(wedges.iter().flat_map(|(pts, _)| pts).all(|p| p.is_finite()), "{g:?}"); + assert_eq!(wedges.len(), 4, "{g:?}"); + assert!(wedges.iter().all(|(pts, _)| pts.len() >= 3 && pts.iter().all(|p| p.is_finite())), "{g:?}: {wedges:?}"); } // A flat extent keeps the vector's direction and the sign of its aspect. let down = GradientGeom { end: Point::new(50.0, 80.0), ..conic_at(c, 30.0, 0.0) }; diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 58fcd886ee..e7c613bf56 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -177,23 +177,31 @@ mod tests { fn harmonies_keep_the_base_model() { let base = Color::cmyk(0.0, 1.0, 1.0, 0.0); for h in Harmony::ALL { - assert!(apply(h, base).iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}", label(h)); + let colors = apply(h, base); + assert!(colors.len() >= 2 && colors.iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}: {colors:?}", label(h)); } let Color::Cmyk { c, m, y, .. } = apply(Harmony::Complementary, base)[1] else { panic!("a CMYK complement") }; assert!(c > m && c > y, "the complement of red is a cyan: {c} {m} {y}"); let g = Guide::new(Color::gray(0.4), Harmony::Triad, &GuideOptions::default()); - assert!(g.grid.iter().flatten().all(|c| matches!(c, Color::Gray { .. }))); + let cells: Vec<&Color> = g.grid.iter().flatten().collect(); + assert!(!cells.is_empty() && cells.iter().all(|c| matches!(c, Color::Gray { .. })), "{cells:?}"); } #[test] fn rules_parse_by_id_and_label() { - for h in Harmony::ALL { - assert_eq!(parse(h.id()), Some(h)); - assert_eq!(parse(label(h)), Some(h)); - } + // A label reads back as its rule, its spaces and case ignored, and so does an id. + assert_eq!(parse("Split Complementary"), Some(Harmony::SplitComplementary)); + assert_eq!(parse("high contrast 3"), Some(Harmony::HighContrast3)); + assert_eq!(parse("tetrad2"), Some(Harmony::Tetrad2)); + assert_eq!(parse(""), None); 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/color/src/libraries.rs b/crates/color/src/libraries.rs index b4197ca0ef..f7e482e567 100644 --- a/crates/color/src/libraries.rs +++ b/crates/color/src/libraries.rs @@ -825,16 +825,4 @@ mod tests { let [l, ..] = to_oklab(&stop("Violet Edge", 4)); assert!(l < 0.5 && to_oklab(&stop("Prism Veil", 2))[0] > 0.95, "{l}"); } - - #[test] - fn the_other_libraries_keep_classic_mixing_and_centered_midpoints() { - for b in builtins().filter(|b| !["organic-fades", "holographic"].contains(&b.id)) { - for s in builtin_library(b.id).unwrap().iter() { - if let Paint::Gradient(g) = &s.paint { - assert_eq!(g.gradient.method, GradientMethod::Classic, "{}", s.name); - assert!(g.gradient.stops.iter().all(|st| st.midpoint == 0.5), "{}", s.name); - } - } - } - } } diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index 05c386e405..c90257b9f1 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -796,12 +796,12 @@ mod tests { #[test] fn methods_parse_by_id_and_label() { - for m in Method::ALL { - assert_eq!(Method::parse(m.id()), Some(m)); - assert_eq!(Method::parse(m.label()), Some(m)); - } + assert_eq!(Method::parse("preserveTints"), Some(Method::PreserveTints)); + assert_eq!(Method::parse("Hue Shift"), Some(Method::HueShift)); + assert_eq!(Method::parse("Tints and Shades"), Some(Method::TintsShades)); assert_eq!(Method::parse("tints & shades"), Some(Method::TintsShades)); assert_eq!(Method::parse("nope"), None); + assert_eq!(Method::parse(""), None); } #[test] diff --git a/crates/color/src/swatch.rs b/crates/color/src/swatch.rs index 12ae31220a..b9ce45b1df 100644 --- a/crates/color/src/swatch.rs +++ b/crates/color/src/swatch.rs @@ -186,13 +186,20 @@ mod tests { #[test] fn default_swatches_parse() { - // `solid`/`grad` fall back to black or white on a bad literal instead of panicking; make sure - // none falls back. - let src = include_str!("swatch.rs"); - let hexes: Vec<&str> = src.split('"').filter(|t| t.starts_with('#') && t.len() == 7).collect(); - assert!(hexes.len() > 30); - for h in hexes { - assert!(Color::from_hex(h).is_some(), "{h}"); - } + // `solid` and `grad` fall back to black or white on a bad hex literal. A fallback gives a + // solid the color of Black or White, and a gradient a stop that differs from the swatch + // its hex literal names. + let (s, g) = default_swatches(Model::Rgb); + let solids: Vec = s.iter().chain(g.iter().flat_map(|g| &g.swatches)).filter_map(|w| w.paint.color()).collect(); + assert!(solids.len() > 40, "{}", solids.len()); + let repeated: Vec<&Color> = solids.iter().enumerate().filter(|(i, c)| solids[..*i].contains(c)).map(|(_, c)| c).collect(); + assert_eq!(repeated, Vec::<&Color>::new(), "colors of more than one default swatch"); + let color = |name: &str| s.iter().find(|w| w.name == name).and_then(|w| w.paint.color()); + let stops = |name: &str| match s.iter().find(|w| w.name == name).map(|w| &w.paint) { + Some(Paint::Gradient(gp)) => gp.gradient.stops.iter().map(|st| Some(st.color)).collect::>(), + other => panic!("{name}: {other:?}"), + }; + assert_eq!(stops("Sunset"), [color("Amber"), color("Rose")]); + assert_eq!(stops("Ocean"), [color("Cyan"), color("Blue")]); } } diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs index ba5bb3b974..9abb0d80ea 100644 --- a/crates/color/src/wcag.rs +++ b/crates/color/src/wcag.rs @@ -208,10 +208,11 @@ mod tests { #[test] fn category_ids_parse_back() { - for c in Category::ALL { - assert_eq!(Category::parse(c.id()), Some(c)); - } + // Commands and saved settings name a category by its id, exactly. + assert_eq!(Category::parse("largeText"), Some(Category::LargeText)); + assert_eq!(Category::parse("graphics"), Some(Category::Graphics)); assert_eq!(Category::parse("NormalText"), None); + assert_eq!(Category::parse("Large Text"), None, "a label is not an id"); } fn hue(srgb: [f32; 3]) -> f64 { diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 2770471f70..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() { @@ -2784,10 +2957,13 @@ mod tests { Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() }))) }; let Paint::Gradient(m) = lerp_paint(&spot_gradient(0.2), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops); let Paint::Gradient(m) = lerp_paint(&tinted(0.2), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops); let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none()), "{:?}", m.gradient.stops); } @@ -2840,6 +3016,7 @@ mod tests { let a = gradient_paint(vec![spot_stop(0.0, 0.2, Some(p)), spot_stop(1.0, 0.2, Some(p))]); let b = gradient_paint(vec![spot_stop(0.0, 1.0, Some(q)), spot_stop(1.0, 1.0, Some(q))]); let Paint::Gradient(m) = lerp_paint(&a, &b, 0.25) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); for s in &m.gradient.stops { assert_eq!(s.swatch.as_deref(), Some("Spot")); assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint); @@ -2848,6 +3025,7 @@ mod tests { // Without plates on either side the steps print the spot ink alone, as before. let bare = |tint| gradient_paint(vec![spot_stop(0.0, tint, None), spot_stop(1.0, tint, None)]); let Paint::Gradient(m) = lerp_paint(&bare(0.2), &bare(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops); } @@ -2882,10 +3060,12 @@ mod tests { let with = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]); let without = gradient_paint(vec![spot_stop(0.0, 1.0, None), spot_stop(1.0, 1.0, None)]); let Paint::Gradient(m) = lerp_paint(&without, &with, 0.25) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops); m.gradient.stops.iter().for_each(|s| assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05])); // The ends keep their own plates. let Paint::Gradient(m) = lerp_paint(&without, &with, 0.0) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops); // Another swatch, or an unlinked stop: process steps with no plates, as before. @@ -2897,6 +3077,7 @@ mod tests { let plain = gradient_paint(vec![plain.clone(), GradientStop { offset: 1.0, ..plain }]); for b in [&other, &plain] { let Paint::Gradient(m) = lerp_paint(&with, b, 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops); } } @@ -2906,11 +3087,14 @@ mod tests { let p = [0.4, 0.8, 0.0, 0.2]; let gradient = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]); let Paint::Gradient(g) = &gradient else { panic!() }; - assert!(solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient).stops.iter().all(|s| s.plates.is_none())); + let linked = solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient); + assert_eq!(linked.stops.len(), 2); + assert!(linked.stops.iter().all(|s| s.plates.is_none() && s.swatch.as_deref() == Some("Spot") && s.tint == 0.2), "{:?}", linked.stops); let solid = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(0.2), swatch: Some("Spot".into()), tint: 0.2 }; // The solid's end has no plates: they grow from none toward the gradient's, both ways round. for (a, b, t) in [(&solid, &gradient, 0.25), (&gradient, &solid, 0.75)] { let Paint::Gradient(m) = lerp_paint(a, b, t) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); for s in &m.gradient.stops { assert_eq!(s.swatch.as_deref(), Some("Spot")); assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint); @@ -2919,6 +3103,7 @@ mod tests { } // A process solid unlinks the steps, and they take no plates. let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &gradient, 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops); } @@ -3401,7 +3586,8 @@ mod tests { #[test] fn odd_dash_blends_to_solid_with_closed_gaps() { let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap(); - assert!(d.pattern.iter().skip(1).step_by(2).all(|g| *g == 0.0), "{:?}", d.pattern); + // Doubled to dash, gap, dash, gap, dash, gap; each dash takes the gap after it. + assert_eq!(d.pattern, [5.0, 0.0, 6.0, 0.0, 7.0, 0.0]); } #[test] @@ -3412,7 +3598,8 @@ mod tests { let mid = lerp_node(&a, &b, 0.4); let mut ids = vec![]; mid.walk(&mut |n| ids.push(n.id)); - assert!(ids.iter().all(|i| *i == NodeId(0)), "{ids:?}"); + // The step and its two members, all of them new. + assert_eq!(ids, [NodeId(0); 3]); } /// A blend of `a` and `b` spaced by `spacing`. diff --git a/crates/doc/src/compound_shape.rs b/crates/doc/src/compound_shape.rs index 3b36ff86dd..f3f4b83939 100644 --- a/crates/doc/src/compound_shape.rs +++ b/crates/doc/src/compound_shape.rs @@ -64,11 +64,10 @@ mod tests { #[test] fn modes_read_back_and_unknown_ones_are_add() { - for m in ShapeMode::ALL { - let v = serde_json::to_value(m).unwrap(); - assert_eq!(v, serde_json::json!(m.name())); - assert_eq!(serde_json::from_value::(v).unwrap(), m); - } + assert_eq!(serde_json::to_value(ShapeMode::Subtract).unwrap(), serde_json::json!("subtract")); + assert_eq!(serde_json::from_value::(serde_json::json!("exclude")).unwrap(), ShapeMode::Exclude); + assert_eq!(ShapeMode::parse("intersect"), Some(ShapeMode::Intersect)); + assert_eq!(ShapeMode::parse("Intersect"), None); for v in [serde_json::json!("divide"), serde_json::json!(3), serde_json::json!(null), serde_json::json!({"a": [1]})] { assert_eq!(serde_json::from_value::(v).unwrap(), ShapeMode::Add); } 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/depth.rs b/crates/doc/src/depth.rs index c846dfc1c6..3872e16a54 100644 --- a/crates/doc/src/depth.rs +++ b/crates/doc/src/depth.rs @@ -613,6 +613,7 @@ mod tests { d.limit_depth_noting(&mut warnings); assert_eq!(warnings, [symbols_note()]); assert!(!d.too_deep(None), "{count} {last}"); + assert_eq!(d.symbols.len(), count, "every symbol is kept"); assert!(d.symbols.iter().all(|s| s.art.children().is_some()), "the art is still a group"); } // An edit that makes one hold itself is seen, whatever else stayed as it was. 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/symbol_overrides.rs b/crates/doc/src/symbol_overrides.rs index 241c61fba8..d9017815c7 100644 --- a/crates/doc/src/symbol_overrides.rs +++ b/crates/doc/src/symbol_overrides.rs @@ -253,6 +253,7 @@ mod tests { let mut a = Node::group(NodeId(1), vec![Arc::new(text)]); apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]); let Some(NodeKind::Text(t)) = part(&a, &[0]).map(|n| &n.kind) else { panic!("type") }; + assert_eq!(t.runs.len(), 1); assert!(t.runs.iter().all(|r| r.style.stroke == red && r.style.stroke_width == 1.0), "the stroke draws at 1 pt"); // A path whose stroke has neither paint nor weight gets 1 pt too. 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/text.rs b/crates/doc/src/text.rs index 073a0f2efd..7ba5cb6199 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -44,7 +44,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_sources, wrap_work}; +pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_source_objects, wrap_sources, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 9371947565..cc119c80b6 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -217,11 +217,10 @@ fn indic_digits_map_to_their_scripts_block() { assert_eq!(map(d, "a-Z ٪"), "a-Z ٪"); } assert_eq!(map(Digits::Devanagari, "page 12"), "page १२"); - for d in Digits::ALL { - assert_eq!(serde_json::to_value(d).unwrap(), d.id()); - assert_eq!(serde_json::from_value::(d.id().into()).unwrap(), d); - assert_eq!(Digits::from_id(d.id()), Some(d)); - } + assert_eq!(serde_json::to_value(Digits::Devanagari).unwrap(), "devanagari"); + assert_eq!(serde_json::from_value::("farsi".into()).unwrap(), Digits::Farsi); + assert_eq!(Digits::Malayalam.id(), "malayalam"); + assert_eq!(Digits::from_id("default"), Some(Digits::Default)); assert_eq!(Digits::from_id("roman"), None); assert!(serde_json::from_value::("roman".into()).is_err()); } @@ -695,6 +694,15 @@ fn a_wrap_object_below_every_area_type_object_makes_no_outline() { }); assert_eq!(sources, 1); assert_eq!(wrap::OUTLINES_MADE.with(|c| c.get()), 1, "only the wrap object above the type is outlined"); + // The objects alone come without a copy of any shape into text space. + let mut found = vec![]; + wrap_source_objects(&d, |n, objects| found.push((n.id, objects.iter().map(|o| o.id).collect::>()))); + let mut expected = vec![]; + wrap_sources(&d, |n, objects, _| expected.push((n.id, objects.iter().map(|o| o.id).collect::>()))); + assert_eq!(found, expected); + wrap::SHAPES_COPIED.with(|c| c.set(0)); + wrap_source_objects(&d, |_, _| {}); + assert_eq!(wrap::SHAPES_COPIED.with(|c| c.get()), 0, "no wrap shape is copied"); } #[test] diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 33fdcb4687..2061de7092 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -11,6 +11,8 @@ use crate::{Document, Node, NodeId, NodeKind}; thread_local! { /// How many wrap outlines [`each_text`] has made on this thread (for tests). pub(super) static OUTLINES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many wrap shapes [`shapes_of`] has copied into text space on this thread (for tests). + pub(super) static SHAPES_COPIED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Outline of a wrap object in document coordinates: its paths, or its bounds for other art. @@ -167,6 +169,8 @@ fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec { .iter() .rev() .map(|(_, s)| { + #[cfg(test)] + SHAPES_COPIED.with(|c| c.set(c.get() + 1)); let mut path = s.path.clone(); path.transform(inv); WrapShape { path, wrap: s.wrap } @@ -189,6 +193,18 @@ pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a N } } +/// [`wrap_sources`] without the shapes: each area text object that gets wrap shapes, with the wrap +/// objects whose outlines make them, bottom first. No shape is copied into text space. +pub fn wrap_source_objects<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>)) { + for layer in &doc.layers { + each_text(layer, |n, above| { + if matches!(n.kind, NodeKind::Text(_)) && !above.is_empty() { + f(n, above.iter().rev().map(|(s, _)| *s).collect()); + } + }); + } +} + /// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the /// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged /// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index a2d17cc990..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)] @@ -98,11 +166,10 @@ mod tests { #[test] fn ids_round_trip_and_unknown_views_show_the_result() { - for v in TraceView::ALL { - assert_eq!(TraceView::from_id(v.id()), Some(v)); - assert_eq!(TraceView::from_id(&v.id().to_ascii_uppercase()), Some(v)); - assert!(v.shows_result() || v.shows_outlines() || v.shows_source(), "{v:?} shows something"); - } + assert_eq!(TraceView::Source.id(), "sourceImage"); + assert_eq!(TraceView::from_id("outlinesWithSourceImage"), Some(TraceView::OutlinesWithSource)); + assert_eq!(TraceView::from_id("TRACINGRESULT"), Some(TraceView::Result), "case does not matter"); + assert_eq!(TraceView::from_id("tracing"), None); let mut g = Node::group(crate::NodeId(1), vec![]); assert_eq!(g.trace_view(), TraceView::Result); g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "outlines"}))); @@ -111,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/color.rs b/crates/effects/src/addons/color.rs index d6edf5f576..3cb72f60d4 100644 --- a/crates/effects/src/addons/color.rs +++ b/crates/effects/src/addons/color.rs @@ -109,10 +109,9 @@ mod tests { #[test] fn the_effects_are_colour_adjustments_in_their_own_menu() { - for id in EFFECTS { - assert!(crate::is_adjustment(id), "{id}"); - assert_eq!(crate::effect_info(id).unwrap().menu, ["Effect", "Color Effects"]); - } + assert!(crate::is_adjustment(DUOTONE)); + assert_eq!(crate::effect_info(DUOTONE).unwrap().menu, ["Effect", "Color Effects"]); + assert!(!crate::is_adjustment("stylize.dropShadow"), "an effect outside the add-on is not one"); } #[test] diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index 371f664781..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,17 +106,15 @@ 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 => { - let r = s * (t / std::f64::consts::PI).sqrt(); - shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.0 * r, 2.0 * r))) - } - DotShape::Ellipse => { - let r = s * (t / std::f64::consts::PI).sqrt(); - shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.6 * r, 2.0 * r / 1.3))) - } + DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle), + DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse), DotShape::Square => square(s * t.sqrt()), - DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)), + DotShape::Diamond => cell_dot(t, s / 2.0, CellKind::Diamond), // Cells along a row join into a line as thick as the tone. DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))), DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)), @@ -179,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 { @@ -296,33 +312,172 @@ fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec { /// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the /// light becomes holes. fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath { + if t <= 0.5 { + 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); } }; - if t <= 0.5 { - let q1 = spot_quadrant(t, h, kind); - add(q1.clone(), 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); - } else { - // 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); - } + // 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)))); + 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 } +/// The dots that grow past their cell's sides: drawn clipped to the cell, so neighbors meet along +/// the shared side instead of overlapping, sized so the clipped dot covers the tone, and the whole +/// cell at full tone. +#[derive(Clone, Copy)] +enum CellKind { + Circle, + /// 1.69 times as wide as tall. + Ellipse, + Diamond, +} + +static CELL_CIRCLE: OnceLock> = OnceLock::new(); +static CELL_ELLIPSE: OnceLock> = OnceLock::new(); +static CELL_DIAMOND: OnceLock> = OnceLock::new(); + +impl CellKind { + /// The first quadrant of the dot of size `r` clipped to the quadrant [0, 1]², from the x axis to + /// the y axis. Circle: radius `r`; Ellipse: semi-axes 1.3 `r` and `r` / 1.3; Diamond: half + /// diagonal `r`. + fn quadrant(self, r: f64) -> Vec { + let corner = Point::new(1.0, 1.0); + match self { + CellKind::Diamond if r <= 1.0 => vec![segment(Point::new(r, 0.0), Point::new(0.0, r))], + CellKind::Diamond if r < 2.0 => vec![ + segment(Point::new(1.0, 0.0), Point::new(1.0, r - 1.0)), + segment(Point::new(1.0, r - 1.0), Point::new(r - 1.0, 1.0)), + segment(Point::new(r - 1.0, 1.0), Point::new(0.0, 1.0)), + ], + CellKind::Diamond => vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))], + CellKind::Circle | CellKind::Ellipse => { + let (a, b) = if matches!(self, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) }; + // The ellipse stays inside x ≤ 1 from angle tx and inside y ≤ 1 up to angle ty. + let tx = (1.0 / a).min(1.0).acos(); + let ty = (1.0 / b).min(1.0).asin(); + if tx >= ty { + return vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))]; + } + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let mut out = vec![]; + if a > 1.0 { + out.push(segment(Point::new(1.0, 0.0), at(tx))); + } + ellipse_arc(&mut out, a, b, tx, ty); + if b > 1.0 { + out.push(segment(at(ty), Point::new(0.0, 1.0))); + } + out + } + } + } + + /// The size at which the dot covers the whole quadrant. + fn max_size(self) -> f64 { + match self { + CellKind::Circle => std::f64::consts::SQRT_2, + // 1 / (1.3 r)² + (1.3 / r)² = 1 at the corner. + CellKind::Ellipse => (1.0 / 1.69 + 1.69_f64).sqrt(), + CellKind::Diamond => 2.0, + } + } + + fn table(self) -> &'static OnceLock> { + match self { + CellKind::Circle => &CELL_CIRCLE, + CellKind::Ellipse => &CELL_ELLIPSE, + CellKind::Diamond => &CELL_DIAMOND, + } + } + + /// For tones `k / SIZE_STEPS`, the size of the dot whose clipped quadrant covers that tone. + fn sizes(self) -> Vec { + (0..=SIZE_STEPS) + .map(|k| { + let target = k as f64 / SIZE_STEPS as f64; + let (mut lo, mut hi) = (0.0, self.max_size()); + for _ in 0..50 { + let mid = (lo + hi) / 2.0; + if curves_area(&self.quadrant(mid)) < target { lo = mid } else { hi = mid } + } + (lo + hi) / 2.0 + }) + .collect() + } +} + +/// The `kind` dot for tone `t` (0..1) in a cell of half side `h` centered on the origin, clipped to +/// the cell ([`CellKind`]). +fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData { + let sizes = kind.table().get_or_init(|| kind.sizes()); + let x = t.clamp(0.0, 1.0) * SIZE_STEPS as f64; + 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. 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 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 { + 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()); + 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 +} + /// One screen: its ink and angle, and how to read its tone from a sampled pixel. struct Screen { paint: Color, @@ -419,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), @@ -625,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) { @@ -659,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(); @@ -695,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] { @@ -709,6 +952,49 @@ mod tests { assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical))); } + #[test] + fn round_and_diamond_dots_stay_in_their_cell_and_fill_it_at_full_tone() { + for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond] { + for t in [0.2, 0.6, 0.85, 0.97] { + // The dot never reaches into a neighbor's cell, so dots of different tones meet + // along the shared side instead of overlapping into notches. + let b = shape.path(t, 2.0).control_bounds().unwrap(); + assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}"); + // What it covers of the cell is the tone. + let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0; + assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}"); + } + // Full tone is the whole cell, its corners included. + assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{shape:?}"); + assert!(!covers(shape, 0.9, (0.499, 0.499)), "{shape:?}"); + } + } + + #[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/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index b0c5332c29..f389c399e7 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -1065,60 +1065,6 @@ fn linear_light_blur_mixes_light_not_values() { } } -/// Timings on a 2000 × 2000 raster (`cargo test -p vectorcraft-effects --release -- --ignored -/// --nocapture pixel_timings`). -#[test] -#[ignore] -fn pixel_timings() { - let (w, h) = (2000, 2000); - let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]); - let s = PixelSpace { - to_doc: Affine::IDENTITY, - px: 1.0, - center: Point::new(1000.0, 1000.0), - size: vectorcraft_geom::Vec2::new(2000.0, 2000.0), - channels: Channels::Rgb, - line: 1.0, - extent: 0.0, - }; - let cases = [ - ("blur.radial", json!({"quality": "draft"})), - ("blur.radial", json!({"quality": "good"})), - ("blur.radial", json!({"quality": "best", "method": "zoom"})), - ("blur.smart", json!({"quality": "low"})), - ("blur.smart", json!({"quality": "high", "radius": 30})), - ("sharpen.unsharpMask", json!({"radius": 20})), - ("brushStrokes.accentedEdges", json!({"edgeWidth": 14})), - ("brushStrokes.angledStrokes", json!({"strokeLength": 50})), - ("brushStrokes.crosshatch", json!({"strokeLength": 50, "strength": 3})), - ("brushStrokes.darkStrokes", json!({})), - ("brushStrokes.inkOutlines", json!({"strokeLength": 50})), - ("brushStrokes.spatter", json!({"sprayRadius": 25})), - ("brushStrokes.sprayedStrokes", json!({"strokeLength": 20, "sprayRadius": 25})), - ("brushStrokes.sumiE", json!({"strokeWidth": 15})), - ("pixelate.colorHalftone", json!({"maxRadius": 4})), - ("pixelate.crystallize", json!({"cellSize": 3})), - ("pixelate.crystallize", json!({"cellSize": 300})), - ("pixelate.mezzotint", json!({"type": "grainyDots"})), - ("pixelate.pointillize", json!({"cellSize": 3})), - ("pixelate.pointillize", json!({"cellSize": 300})), - ("texture.craquelure", json!({"crackSpacing": 2})), - ("texture.craquelure", json!({"crackSpacing": 100})), - ("texture.grain", json!({"grainType": "clumped"})), - ("texture.mosaicTiles", json!({"tileSize": 2})), - ("texture.patchwork", json!({"squareSize": 0})), - ("texture.stainedGlass", json!({"cellSize": 2})), - ("texture.texturizer", json!({"texture": "sandstone", "scaling": 50})), - ("texture.texturizer", json!({"texture": "burlap"})), - ]; - for (id, p) in cases { - let mut d = src.clone(); - let t = std::time::Instant::now(); - fx(id, p.clone()).apply(&mut d, w, h, &s); - println!("{id} {p}: {:?}", t.elapsed()); - } -} - #[test] fn pixelate_params_take_defaults_and_stay_in_range() { assert_eq!(fx("pixelate.colorHalftone", json!({})), PixelFx::ColorHalftone { max_radius: 8.0, angles: [108.0, 162.0, 90.0, 45.0] }); 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/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs index cb92d59e72..b20d0fedf0 100644 --- a/crates/effects/src/solids/wireframe/tests.rs +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -466,14 +466,16 @@ fn wireframe_mode_is_checked_against_the_edges_it_draws() { assert!(refused.contains("simplify the gradient"), "{refused}"); assert_eq!(crate::validate_revolve(&n, &wire), Ok(())); n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &wire).unwrap()); - assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some())); + let edges = leaves(&drawn(&n)); + assert!(!edges.is_empty() && edges.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{} pieces", edges.len()); // On the fill. let fx = n.appearance.effects.remove(0); let at = n.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Fill(_))).unwrap(); assert!(crate::revolve::validate_item_revolve(&n, &shaded, at, 0).is_err()); assert_eq!(crate::revolve::validate_item_revolve(&n, &wire, at, 0), Ok(())); n.appearance.items[at].effects_mut().push(fx); - assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some())); + let edges = leaves(&drawn(&n)); + assert!(!edges.is_empty() && edges.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{} pieces", edges.len()); } /// A 3D (Classic) effect ignores a `render` it does not take in a loaded file: it draws as before. diff --git a/crates/effects/src/stroke/tests_fit.rs b/crates/effects/src/stroke/tests_fit.rs index f7fecb9abc..343ef29c50 100644 --- a/crates/effects/src/stroke/tests_fit.rs +++ b/crates/effects/src/stroke/tests_fit.rs @@ -155,6 +155,7 @@ fn fitted_dashes_on_curves_and_degenerate_paths_stay_finite() { s.profile = profile.clone(); }); let o = line_outline(&mixed, &st, 4.0, 0.01); + assert!(!o.elements().is_empty(), "{pat:?}: the curve's dashes are drawn"); assert!(o.elements().iter().filter_map(|e| e.end_point()).all(|p| p.x.is_finite() && p.y.is_finite()), "{pat:?}"); } } diff --git a/crates/effects/src/stroke/tests_gradient.rs b/crates/effects/src/stroke/tests_gradient.rs index 55aeda8d7f..42a6723597 100644 --- a/crates/effects/src/stroke/tests_gradient.rs +++ b/crates/effects/src/stroke/tests_gradient.rs @@ -301,7 +301,9 @@ fn a_spread_gradient_runs_its_stops_along_the_stroke_that_many_times() { let mut st = stroke(10.0, mode); let g = Gradient { spread, repeats: 3, ..Gradient::default() }; st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone()))); - for s in slices(&bp, &st) { + let pieces = slices(&bp, &st); + assert!(!pieces.is_empty(), "{mode:?} {spread:?}: the stroke is painted in slices"); + for s in pieces { let Paint::Gradient(p) = s.paint(&g.unrolled()) else { panic!("a gradient slice") }; let geom = p.geom.unwrap(); for u in [0.1, 0.5, 0.9] { diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index aa77e45b2f..dadbd35ae8 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -247,15 +247,14 @@ fn a_warp_draws_with_the_map_its_version_names() { fn a_warp_bends_a_flat_box_as_the_middle_of_its_patch() { let anchors = |p: &PathData| p.subpaths.iter().flat_map(|s| s.anchors.clone()).collect::>(); let vertical = shapes::line(Point::new(100.0, 0.0), Point::new(100.0, 100.0)); - let out = run("warp.arc", json!({"bend": 50, "version": 1}), &vertical); - assert!(anchors(&out).iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}"); + let out = anchors(&run("warp.arc", json!({"bend": 50, "version": 1}), &vertical)); + assert!(out.len() >= 2, "{out:?}"); + assert!(out.iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}"); let horizontal = shapes::line(Point::new(0.0, 50.0), Point::new(200.0, 50.0)); for style in ["bulge", "fisheye", "inflate", "squeeze"] { - let out = run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal); - assert!( - anchors(&out).iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)), - "{style}: {out:?}" - ); + let out = anchors(&run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal)); + assert!(out.len() >= 2, "{style}: {out:?}"); + assert!(out.iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)), "{style}: {out:?}"); } } @@ -2084,18 +2083,6 @@ fn bad_params_fall_back_to_defaults() { assert!(close(out.bounds().unwrap().width(), 124.0, 0.1)); } -#[test] -#[ignore] -fn bench_catalog_lookup() { - let t = std::time::Instant::now(); - let mut n = 0; - for _ in 0..10_000 { - n += crate::is_geometry("distort.roughen") as usize; - n += crate::merged_params("stylize.dropShadow", &serde_json::Value::Null).as_object().unwrap().len(); - } - eprintln!("10k lookups: {:?} ({n})", t.elapsed()); -} - #[test] fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { use std::sync::Arc; diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index db34010c22..d0e4939e8e 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -1035,10 +1035,11 @@ fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() { use vectorcraft_doc::text::{CharStyle, TextObject}; let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); - if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } + assert!(crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0), "the type outlines to paths"); let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]); let b = baked(g); assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b)); @@ -1640,6 +1641,17 @@ fn type_node(id: u64, effects: Vec) -> Node { n } +/// Whether the face of the default character style is installed, so that type lays out glyphs. +/// When it is, `type_node`'s type must outline to paths. +fn fonts() -> bool { + let style = vectorcraft_doc::text::CharStyle::default(); + if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() { + return false; + } + assert!(crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0), "{}: the type outlines to paths", style.font_family); + true +} + /// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square /// centered on its origin. fn instance(id: u64, effects: Vec) -> (Node, Node) { @@ -1660,7 +1672,7 @@ fn instance(id: u64, effects: Vec) -> (Node, Node) { /// image and the instance are checked. #[test] fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() { - let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0); + let fonts = fonts(); if !fonts { eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); } @@ -1702,7 +1714,7 @@ fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_bef /// listed before that effect, as the canvas draws it, rather than staying type under one shadow. #[test] fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() { - if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } @@ -1738,7 +1750,7 @@ fn type_carries_its_fills_shadow_on_each_copy() { n }; let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]; - if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } 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 8e8d96ea66..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; @@ -1002,7 +1012,8 @@ pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). -pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; +pub const ALIASES: &[(&str, &str)] = + &[("object.convertDocumentColorMode", "file.documentColorMode"), ("addon.pathtools.bridge", "addon.pathtools.commonTangents")]; /// Is `id` an [`ALIASES`] entry? pub fn is_alias(id: &str) -> bool { 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 fc01a8730d..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, and objects without bounds such as empty groups, 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 )] @@ -55,10 +70,16 @@ fn corners(r: Rect) -> Vec<(Point, f64, f64)> { out } +/// The lengths of the across and down legs of the corner marks of `r`: `length`, at most half the +/// side each runs along. +fn legs(r: Rect, length: f64) -> (f64, f64) { + (length.min(r.width() / 2.0), length.min(r.height() / 2.0)) +} + /// The corner marks of `r` with legs `length` long, each at most half its side: one open path per /// corner, a line where `r` has no width or no height. fn corner_paths(r: Rect, length: f64) -> Vec { - let (lx, ly) = (length.min(r.width() / 2.0), length.min(r.height() / 2.0)); + let (lx, ly) = legs(r, length); corners(r) .into_iter() .filter_map(|(p, sx, sy)| { @@ -75,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; @@ -89,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"); @@ -100,17 +171,47 @@ 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) }; - if let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) { - marked.push((anchor(d, id), r)); + 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 { + 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; } } if marked.is_empty() { + if too_small { + return Err(bad(C, "nothing to mark: the selection is too small for corner marks")); + } return Err(bad(C, "nothing to mark: the selection has no bounds")); } let ap = Appearance::basic(Paint::None, Paint::solid(color), weight); diff --git a/crates/engine/src/cmd/addons/arrange/marks/tests.rs b/crates/engine/src/cmd/addons/arrange/marks/tests.rs index dc44f47d5b..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(); @@ -325,6 +547,28 @@ fn flat_objects_get_lines_and_guides_and_empty_groups_none() { assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0))); } +#[test] +fn an_object_too_small_for_corner_legs_gets_no_empty_group() { + let mut s = session(); + // Wider than the flat limit, but each leg (half the side at most) is shorter than it. + let tiny = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 1.5e-9, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[tiny]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(refused.contains("nothing to mark") && refused.contains("too small for corner marks"), "{refused}"); + assert_eq!(steps(&s), n, "no undo step"); + assert!(*s.doc().unwrap().doc == *before); + // The rectangle style still marks it, and a real object beside it gets its corner marks alone. + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + assert_eq!(r["count"], 1); + s.execute("edit.undo", &json!({})).unwrap(); + let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0); + select(&mut s, &[tiny, a]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(r["count"], 1); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0))); +} + #[test] fn bad_params_are_refused_and_it_is_off_without_a_selection() { 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/image/mask/tests.rs b/crates/engine/src/cmd/addons/image/mask/tests.rs index 46c33a3871..b1e76927c6 100644 --- a/crates/engine/src/cmd/addons/image/mask/tests.rs +++ b/crates/engine/src/cmd/addons/image/mask/tests.rs @@ -449,6 +449,7 @@ fn cropping_off_the_pixel_grid_keeps_the_hidden_colors_in_the_pixels() { }) .unwrap() .to_rgba8(); + assert_eq!(own.dimensions(), (6, 5), "the cut's pixels"); assert!(own.pixels().all(|p| p.0[3] == 255), "the cut pixels are the image's own, white included"); assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden"); s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap(); diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 2f56079b18..6e02292917 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -32,15 +32,15 @@ pub(super) fn specs() -> Vec { vec![cmd!( "addon.pathtools.bridge", "Smooth Bridge", - ["Object", "Plug-ins", "Path Precision Tools"], + [], None, - "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", + "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles (kept for older scripts: Common Tangents makes the same outline with `curved`, and the command palette leaves this command out)", has_selection, bridge )] } -fn bridge(s: &mut Session, p: &Value) -> Result { +pub(super) fn bridge(s: &mut Session, p: &Value) -> Result { let percent = given(p, "radius", Some(RADII), C)?; let gap = given(p, "gap", Some(GAPS), C)?; let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index e47c009062..372ceb6e12 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -31,7 +31,7 @@ pub(super) fn specs() -> Vec { "Common Tangents", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), connect?: bool (false: true joins the two tangents of each kind into one closed path, along the chords between where they touch each path; a kind with one tangent stays a line), curved?: bool (false: true joins the selected circles into one outline along concave arcs that touch both, as `addon.pathtools.bridge` does, in place of the external tangents; `tangents` other than \"external\", `centerline` and `connect: false` are then an error), radius?: % 1..1000 (100; with curved, as for `addon.pathtools.bridge`), gap?: pt 0..1000 (with curved, instead of radius), reach?: pt 0..10000 (10; with curved, for three or more circles), keepOriginals?: bool (false; with curved), ids?: [id, id] (default: the selection; with curved, two or more circles)} add the common tangent lines of two convex closed paths (with curved, join circles with a smooth bridge into metaball, aka meatball, shapes instead) as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}, or with curved `addon.pathtools.bridge`'s {ids, alone, id?}", has_selection, common_tangents )] @@ -71,9 +71,36 @@ fn refusal(e: pt::OutlineError) -> EngineError { ) } +/// The parameters that shape a curved bridge. +const CURVED_KEYS: [&str; 4] = ["radius", "gap", "reach", "keepOriginals"]; + fn common_tangents(s: &mut Session, p: &Value) -> Result { const C: &str = COMMON_TANGENTS; - let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all"); + let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null()); + let kinds = choice(p, C, "tangents", &KINDS)?; + let connect = if given("connect") { Some(switch_or(p, "connect", false, C)?) } else { None }; + if switch_or(p, "curved", false, C)? { + if kinds.is_some_and(|k| k != "external") { + return Err(bad(C, "`curved` joins the circles along their external tangents: give `tangents` \"external\" or leave it out")); + } + if given("centerline") { + return Err(bad(C, "`centerline` applies to the tangent lines: leave it out with `curved`")); + } + if connect == Some(false) { + return Err(bad(C, "a curved bridge is always connected: leave `connect` out or set it true")); + } + // The outline is Smooth Bridge's. + let mut bridged = serde_json::Map::new(); + for key in CURVED_KEYS.iter().chain(&["ids"]).filter(|k| given(k)) { + bridged.insert((*key).to_owned(), p[*key].clone()); + } + return super::bridge::bridge(s, &Value::Object(bridged)); + } + if let Some(key) = CURVED_KEYS.iter().find(|k| given(k)) { + return Err(bad(C, format!("`{key}` applies to a curved bridge: give `curved` with it"))); + } + let kinds = kinds.unwrap_or("all"); + let connect = connect.unwrap_or(false); let centerline = switch_or(p, "centerline", false, C)?; let roots = checked_ids_or_selection(s, p, C)?; let d = &s.doc()?.doc; @@ -105,6 +132,33 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { _ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)), }; let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + // With `connect`, the two tangents of each kind and the chords between their ends on each path make one closed + // shape; a kind with one tangent (paths that touch) keeps it as a line. A point's lines are all one kind. + let shapes: Vec<(Vec, bool)> = if connect { + let mut out = vec![]; + for kind in [pt::TangentKind::External, pt::TangentKind::Internal] { + let of: Vec<&pt::Tangent> = kept.iter().copied().filter(|t| point || t.kind == kind).collect(); + match of.as_slice() { + [l, m] => { + // A point's two lines share the point, which then closes the ring once. + let same = |q: Point, p: Point| (q - p).hypot() <= 1e-9 * a.size().max(b.size()); + let mut ring = vec![l.from, l.to, m.to, m.from]; + ring.dedup_by(|q, p| same(*q, *p)); + if ring.len() > 2 && same(ring[0], ring[ring.len() - 1]) { + ring.pop(); + } + out.push((ring, true)); + } + _ => out.extend(of.iter().map(|t| (vec![t.from, t.to], false))), + } + if point { + break; + } + } + out + } else { + lines.iter().map(|&(from, to)| (vec![from, to], false)).collect() + }; if lines.is_empty() && point { // Written as `EngineError::Other` so that the i18n message scan finds it. let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into()); @@ -133,13 +187,14 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?; let mut ids = vec![]; let mut center_id = None; - for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() { + let center = center.map(|(from, to)| (vec![from, to], false)); + for (k, (points, closed)) in shapes.iter().cloned().chain(center).enumerate() { let id = d.alloc_id(); - let path = PathData::single(SubPath::polyline(&[from, to], false)); + let path = PathData::single(SubPath::polyline(&points, closed)); let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }); look.apply(d, &mut n); d.insert(parent, idx + 1 + k, n)?; - if k == lines.len() { + if k == shapes.len() { center_id = Some(id); } ids.push(id); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index 7ab6b32838..1653089520 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -354,3 +354,113 @@ fn bad_selections_and_params_are_refused() { let g = group_of(&mut s, &[b]); assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths")); } + +/// The one closed outline of path `id`. +fn outline(s: &Session, id: NodeId) -> vectorcraft_geom::SubPath { + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") }; + let [sp] = path.subpaths.as_slice() else { panic!("{} subpaths", path.subpaths.len()) }; + assert!(sp.closed); + sp.clone() +} + +/// The anchors of path `id`'s one closed outline. +fn corners(s: &Session, id: NodeId) -> Vec { + outline(s, id).anchors.iter().map(|a| a.p).collect() +} + +#[test] +fn connect_joins_the_external_tangents_and_the_chords_into_one_closed_shape_in_one_step() { + let mut s = session(); + let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0)); + let (before, count) = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"tangents": "external", "connect": true, "ids": [a.0, b.0]})).unwrap(); + assert_eq!(steps(&s), before + 1, "one undo step"); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1, "one shape in place of two lines"); + assert_eq!(s.doc().unwrap().doc.node_count(), count + 1, "the circles stay"); + let found = corners(&s, NodeId(ids[0].as_u64().unwrap())); + assert_eq!(found.len(), 4); + // The tangents above and below both circles, joined by each circle's vertical diameter. + for p in [Point::new(100.0, 80.0), Point::new(200.0, 80.0), Point::new(200.0, 120.0), Point::new(100.0, 120.0)] { + assert!(found.iter().any(|&q| near(p, q)), "{p:?} in {found:?}"); + } + // In order around the band, not crossing itself: the area is the 100 by 40 rectangle's. + let area = found.iter().zip(found.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum::() / 2.0; + assert!((area.abs() - 4000.0).abs() < 1e-6, "area {area} of {found:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.node_count(), count); +} + +#[test] +fn connect_with_all_makes_one_shape_of_each_kind_and_a_point_makes_a_triangle() { + let mut s = session(); + let (ca, cb) = ((Point::new(100.0, 100.0), 20.0), (Point::new(220.0, 140.0), 40.0)); + let (a, b) = (circle(&mut s, ca.0.x, ca.0.y, ca.1), circle(&mut s, cb.0.x, cb.0.y, cb.1)); + let r = s.execute(C, &json!({"connect": true, "centerline": true, "ids": [a.0, b.0]})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(ids.len(), 3, "an external shape, an internal shape and the centerline"); + for &id in &ids[..2] { + let found = corners(&s, id); + assert_eq!(found.len(), 4); + let on = |(c, r): (Point, f64)| found.iter().filter(|p| ((**p - c).hypot() - r).abs() < 1e-6).count(); + assert_eq!((on(ca), on(cb)), (2, 2), "two corners where the tangents touch each circle: {found:?}"); + } + assert_ne!(corners(&s, ids[0]), corners(&s, ids[1])); + assert_eq!(r["centerline"], json!(ids[2].0)); + + let mut s = session(); + let (p, c) = (point(&mut s, 0.0, 100.0), circle(&mut s, 100.0, 100.0, 20.0)); + let r = s.execute(C, &json!({"connect": true, "ids": [p.0, c.0]})).unwrap(); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let found = corners(&s, NodeId(ids[0].as_u64().unwrap())); + assert_eq!(found.len(), 3, "the point and where its two lines touch the circle: {found:?}"); + assert!(found.iter().any(|&q| near(q, Point::new(0.0, 100.0)))); +} + +#[test] +fn curved_makes_the_bridge_the_smooth_bridge_command_makes() { + let build = || { + let mut s = session(); + let ids = [circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 150.0, 100.0, 20.0), circle(&mut s, 125.0, 140.0, 20.0)]; + select(&mut s, &ids); + s + }; + for (merged, old) in [ + (json!({"curved": true}), json!({})), + ( + json!({"tangents": "external", "connect": true, "curved": true, "gap": 5, "reach": 30, "keepOriginals": true}), + json!({"gap": 5, "reach": 30, "keepOriginals": true}), + ), + ] { + let (mut s, mut t) = (build(), build()); + let r = s.execute(C, &merged).unwrap(); + let q = t.execute("addon.pathtools.bridge", &old).unwrap(); + assert_eq!(r, q, "{merged}"); + let kinds = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.kind.clone()).collect::>(); + assert_eq!(kinds(&s), kinds(&t), "{merged}"); + } +} + +#[test] +fn options_of_the_other_mode_are_refused() { + let mut s = session(); + let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0)); + select(&mut s, &[a, b]); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + for (p, says) in [ + (json!({"connect": "yes"}), "connect"), + (json!({"curved": true, "tangents": "all"}), "external"), + (json!({"curved": true, "centerline": true}), "centerline"), + (json!({"curved": true, "connect": false}), "connected"), + (json!({"radius": 50}), "curved"), + (json!({"connect": true, "keepOriginals": true}), "curved"), + (json!({"curved": true, "radius": 50, "gap": 2}), "not both"), + (json!({"curved": true, "radius": 0}), "radius"), + ] { + assert!(err(&mut s, p.clone()).contains(says), "{p}: {}", err(&mut s, p.clone())); + } + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); +} diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 584f33dc36..1b16421c8d 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -237,6 +237,7 @@ fn add_points_splits_selected_segments_evenly() { let n = steps(&s); assert_eq!(s.execute("addon.pathtools.addPoints", &json!({"count": 3})).unwrap()["added"], json!(3)); let xs: Vec = path(&s, l).anchors().map(|(_, _, a)| a.p.x).collect(); + assert_eq!(xs.len(), 5, "{xs:?}"); assert!(xs.iter().zip([0.0, 25.0, 50.0, 75.0, 100.0]).all(|(x, w)| (x - w).abs() < 1e-3), "{xs:?}"); assert_eq!(steps(&s), n + 1); refuses(&mut s, "addon.pathtools.addPoints", &[json!({"count": 0}), json!({"count": 101}), json!({"count": 1.5})]); diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index 14a462d79f..ef010d7f32 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -7,6 +7,7 @@ //! (#5532). The reference app has no command for it, so it goes beyond parity and changes no //! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's. +pub mod numbers; #[cfg(test)] mod tests; @@ -65,6 +66,15 @@ pub fn specs() -> Vec { has_selection, release_path ), + cmd!( + "addon.type.numbers", + "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, 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 new file mode 100644 index 0000000000..f8064b9ded --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/numbers.rs @@ -0,0 +1,498 @@ +//! Make Numbers Sequence (`addon.type.numbers`): numbers the selected type objects from a start +//! value by a step, replacing each object's whole text, the numbers in it, or a `{%n}` placeholder. +//! The objects are taken in stacking order, by rows or by columns. Leading and trailing zeros pad +//! the numbers to one width. Based on Sergey Osokin's MIT-licensed MakeNumbersSequence script +//! (). + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_color::recolor::Rng; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject, TextRun}; +use vectorcraft_geom::Rect; +use vectorcraft_render::effects; +use vectorcraft_text::edit; +use vectorcraft_text::retype::is_combining_mark; + +use super::super::super::menucmds::whole_or; +use super::super::super::object::choice; +use super::super::super::textedit::text_mut; +use super::super::super::threads; +use super::super::super::typecmd::refresh_bounds; +use super::super::super::typemenu::text_ids; +use super::super::super::{bad, number_or, switch_or, targets}; +use crate::{EngineError, Result, Session}; + +/// The command id. +pub const COMMAND: &str = "addon.type.numbers"; +/// The orders the objects are numbered in. +pub const ORDERS: [&str; 3] = ["stacking", "rows", "columns"]; +/// What each object's number replaces. +pub const REPLACES: [&str; 3] = ["all", "numbers", "placeholder"]; +/// The placeholder `replace: "placeholder"` replaces, in any case. +pub const PLACEHOLDER: &str = "{%n}"; +/// The largest start, end or step. +const MAX_VALUE: f64 = 1e12; +/// The most decimal places a number keeps. +const MAX_DECIMALS: usize = 6; +/// The largest fixed number of digits. +pub const MAX_DIGITS: u64 = 30; +/// The most type objects one run numbers. +const MAX_TEXTS: usize = 100_000; +/// The most numbers or placeholders one run replaces. +pub(crate) const MAX_MATCHES: usize = 10_000; + +/// What one run does, read from its params. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct Options { + pub start: f64, + /// None: the numbers run to the last type object. + pub end: Option, + pub step: f64, + pub order: &'static str, + pub replace: &'static str, + /// Some(seed): the numbers go to the objects in random order. + pub shuffle: Option, + pub leading_zeros: bool, + /// The least number of whole digits with leading zeros; None: as many as the widest number. + pub digits: Option, + pub trailing_zeros: bool, + pub remove_unused: bool, +} + +impl Options { + pub(crate) fn parse(p: &Value) -> Result { + const C: &str = COMMAND; + let value = |key: &str, default: f64| -> Result { + let v = number_or(p, key, default, C)?; + if !v.is_finite() || v.abs() > MAX_VALUE { + return Err(bad(C, format!("`{key}` must be from -{MAX_VALUE} to {MAX_VALUE}"))); + } + Ok(v) + }; + let start = value("start", 1.0)?; + let step = value("step", 1.0)?; + let end = match p.get("end") { + None | Some(Value::Null) => None, + Some(_) => Some(value("end", 0.0)?), + }; + let order = pick(choice(p, C, "order", &ORDERS)?.unwrap_or("stacking"), &ORDERS); + let replace = pick(choice(p, C, "replace", &REPLACES)?.unwrap_or("all"), &REPLACES); + let seed = whole_or(p, "seed", 0, C)?; + let shuffle = if switch_or(p, "shuffle", false, C)? { Some(seed) } else { None }; + let digits = match p.get("digits") { + None | Some(Value::Null) => None, + Some(_) => { + let d = whole_or(p, "digits", 1, C)?; + if !(1..=MAX_DIGITS).contains(&d) { + return Err(bad(C, format!("`digits` must be from 1 to {MAX_DIGITS}"))); + } + Some(usize::try_from(d).unwrap_or(1)) + } + }; + let remove_unused = switch_or(p, "removeUnused", false, C)?; + if remove_unused && end.is_none() { + return Err(bad(C, "`removeUnused` needs an `end`")); + } + Ok(Self { + start, + end, + step, + order, + replace, + shuffle, + leading_zeros: switch_or(p, "leadingZeros", true, C)?, + digits, + trailing_zeros: switch_or(p, "trailingZeros", false, C)?, + remove_unused, + }) + } +} + +/// `v` as the static entry of `list` it equals. +fn pick(v: &str, list: &[&'static str]) -> &'static str { + list.iter().copied().find(|x| *x == v).unwrap_or(list[0]) +} + +/// The decimal places `v` is written with, at most [`MAX_DECIMALS`]. +fn decimals(v: f64) -> usize { + let s = format!("{v}"); + s.split_once('.').map_or(0, |(_, f)| f.len()).min(MAX_DECIMALS) +} + +/// Round the shortest decimal representation of `v` to fixed point at `places`. +fn scaled(v: f64, places: usize) -> i128 { + let s = format!("{v}"); + let magnitude = s.trim_start_matches('-'); + let (whole, fraction) = magnitude.split_once('.').unwrap_or((magnitude, "")); + let digits = whole.bytes().chain(fraction.bytes().chain(std::iter::repeat(b'0')).take(places)); + let mut value = digits.fold(0_i128, |n, digit| n * 10 + i128::from(digit - b'0')); + if fraction.as_bytes().get(places).is_some_and(|digit| *digit >= b'5') { + value += 1; + } + if v < 0.0 { -value } else { value } +} + +/// `v` scaled by `10^places`, without trailing zeros and with no minus sign on zero. +fn write(v: i128, places: usize) -> String { + let scale = 10_u128.pow(places as u32); + let magnitude = v.unsigned_abs(); + let sign = if v < 0 { "-" } else { "" }; + let whole = magnitude / scale; + if places == 0 { + return format!("{sign}{whole}"); + } + let fraction = magnitude % scale; + let s = format!("{sign}{whole}.{fraction:0places$}"); + s.trim_end_matches('0').trim_end_matches('.').to_string() +} + +/// The numbers for `count` objects as text: from `start` by `step` (its sign set to run toward +/// `end`), stopping past `end`, then padded with zeros as `o` says. +pub(crate) fn sequence(o: &Options, count: usize) -> Vec { + let places = [Some(o.start), Some(o.step), o.end].into_iter().flatten().map(decimals).max().unwrap_or(0); + let step = match o.end { + Some(end) if (o.start <= end) == (o.step < 0.0) => -o.step, + _ => o.step, + }; + // Count steps at the supported decimal precision so an inclusive end survives rounding. + let scaled = |v: f64| scaled(v, places); + let start_i = scaled(o.start); + let step_i = scaled(step); + let fit = match o.end { + Some(end) if step_i != 0 => usize::try_from((scaled(end) - start_i) / step_i + 1).unwrap_or(usize::MAX), + _ => count, + }; + let values: Vec = (0..count.min(fit)).map(|i| start_i + i as i128 * step_i).collect(); + let mut out: Vec = values.iter().map(|v| write(*v, places)).collect(); + if o.trailing_zeros { + let most = out.iter().map(|s| s.split_once('.').map_or(0, |(_, f)| f.len())).max().unwrap_or(0); + if most > 0 { + for s in &mut out { + let have = s.split_once('.').map_or(0, |(_, f)| f.len()); + if have == 0 { + s.push('.'); + } + s.extend(std::iter::repeat_n('0', most - have)); + } + } + } + if o.leading_zeros { + let last = o.end.map(scaled).unwrap_or_else(|| values.last().copied().unwrap_or(start_i)); + // Whole digits as written, after rounding to `places`. + let whole = |v: i128| { + let s = write(v, places); + let s = s.trim_start_matches('-'); + s.split_once('.').map_or(s.len(), |(w, _)| w.len()) + }; + let width = whole(start_i).max(whole(last)).max(o.digits.unwrap_or(1)); + for s in &mut out { + if s.starts_with('-') { + continue; + } + let have = s.split_once('.').map_or(s.len(), |(w, _)| w.len()); + if have < width { + s.insert_str(0, &"0".repeat(width - have)); + } + } + } + out +} + +/// The byte ranges of `text` a number replaces: each run of ASCII digits, with any `.` or `,` +/// followed by more digits inside it, and a `-` before it that does not follow a letter or digit. +pub(crate) fn number_spans(text: &str) -> Vec<(usize, usize)> { + let b = text.as_bytes(); + let mut out = vec![]; + let mut i = 0; + while i < b.len() { + if !b[i].is_ascii_digit() { + i += 1; + continue; + } + let signed = i > 0 && b[i - 1] == b'-' && !text[..i - 1].chars().rev().find(|c| !is_combining_mark(*c)).is_some_and(char::is_alphanumeric); + let start = if signed { i - 1 } else { i }; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + while i + 1 < b.len() && matches!(b[i], b'.' | b',') && b[i + 1].is_ascii_digit() { + i += 1; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + } + out.push((start, i)); + } + out +} + +/// The byte ranges of `text` that hold the placeholder, in any case. +pub(crate) fn placeholder_spans(text: &str) -> Vec<(usize, usize)> { + let lower = text.to_ascii_lowercase(); + lower.match_indices(PLACEHOLDER).map(|(i, m)| (i, i + m.len())).collect() +} + +/// `ids` in rows (top to bottom, each row left to right) or columns (left to right, each top to +/// bottom), by the centres of `bounds`. Objects whose centres are within half the median height +/// (width for columns) of a row's first object share its row. +fn by_position(ids: Vec<(NodeId, Rect)>, rows: bool) -> Vec { + let along = |r: &Rect| if rows { r.center().y } else { r.center().x }; + let across = |r: &Rect| if rows { r.center().x } else { r.center().y }; + let mut sizes: Vec = ids.iter().map(|(_, r)| if rows { r.height() } else { r.width() }).collect(); + sizes.sort_by(f64::total_cmp); + let n = sizes.len(); + let median = match n { + 0 | 1 => 0.0, + _ if n.is_multiple_of(2) => (sizes[n / 2 - 1] + sizes[n / 2]) / 2.0, + _ => sizes[n / 2], + }; + let tolerance = median / 2.0; + let mut ids = ids; + ids.sort_by(|a, b| along(&a.1).total_cmp(&along(&b.1))); + let mut out = Vec::with_capacity(ids.len()); + let mut row: Vec<(NodeId, Rect)> = vec![]; + for item in ids { + if row.first().is_some_and(|first| along(&item.1) - along(&first.1) > tolerance) { + row.sort_by(|a, b| across(&a.1).total_cmp(&across(&b.1))); + out.extend(row.drain(..).map(|(id, _)| id)); + } + row.push(item); + } + row.sort_by(|a, b| across(&a.1).total_cmp(&across(&b.1))); + out.extend(row.into_iter().map(|(id, _)| id)); + out +} + +/// One replacement in a text: its start and end bytes and the number that goes there. +type Edit = (usize, usize, String); + +/// Each span of `spans` in `text` replaced by `number`, as edits from the last to the first. A +/// span that already reads `number` is left out, so its formatting stays. +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)?; + let named = targets(s, p)?; + let d = &s.doc()?.doc; + if let Some(id) = named.iter().find(|id| d.node(**id).is_none()) { + return Err(EngineError::NoNode(*id)); + } + // Type objects, groups' included, in stacking order from the back; locked or hidden ones stay. + let mut texts = text_ids(d, &named); + { + let editable = d.editable(); + texts.retain(|id| editable(*id)); + } + let paths = d.index_paths(texts.iter().copied()); + texts.sort_by(|a, b| paths.get(a).cmp(&paths.get(b))); + if texts.len() > MAX_TEXTS { + return Err(bad(C, format!("too many type objects: at most {MAX_TEXTS}"))); + } + let plain = |id: NodeId| match d.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t.plain_text(), + _ => String::new(), + }; + 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() + .map(|(id, _)| (*id, effects::preview::bounds_of(d, &[*id], false).unwrap_or(Rect::new(f64::MAX, f64::MAX, f64::MAX, f64::MAX)))) + .collect(); + let mut by_id: std::collections::HashMap = texts.into_iter().collect(); + texts = by_position(placed, o.order == "rows").into_iter().filter_map(|id| by_id.remove(&id).map(|t| (id, t))).collect(); + } + // The objects are shuffled, not the numbers, so an end limit can number any of them. + if let Some(seed) = o.shuffle { + let mut rng = Rng::new(seed); + for i in (1..texts.len()).rev() { + let j = usize::try_from(rng.next_u64() % (i as u64 + 1)).unwrap_or(0); + texts.swap(i, j); + } + } + let numbers = sequence(&o, texts.len()); + let mut plans: Vec<(NodeId, Vec)> = vec![]; + let mut matches = 0; + for ((id, text), number) in texts.iter().zip(&numbers) { + let spans = match o.replace { + "numbers" => number_spans(text), + "placeholder" => placeholder_spans(text), + _ => vec![], + }; + // Checked before any replacement text is made. + matches += spans.iter().filter(|(a, b)| text.get(*a..*b) != Some(number.as_str())).count(); + if matches > MAX_MATCHES { + return Err(bad(C, format!("too many numbers or placeholders to replace: at most {MAX_MATCHES}"))); + } + let changes = match o.replace { + "numbers" | "placeholder" => edits(text, spans, number), + _ => vec![(0, text.len(), number.clone())], + }; + // The text it would have, to leave out objects that already read so. + if replaced(text, &changes) != *text { + plans.push((*id, changes)); + } + } + let numbered: Vec = texts.iter().take(numbers.len()).map(|(id, _)| id.0).collect(); + // A clipping group's or layer's mask is its first child; removing it would make the next child the mask. + let mask = |id: NodeId| { + d.parent_of(id).and_then(|g| d.node(g)).is_some_and(|g| g.clips() && g.children().and_then(|c| c.first()).is_some_and(|c| c.id == id)) + }; + let removed: Vec = + if o.remove_unused { texts.iter().skip(numbers.len()).map(|(id, _)| *id).filter(|id| !mask(*id)).collect() } else { vec![] }; + if plans.is_empty() && removed.is_empty() { + return Ok(json!({ "count": 0, "ids": numbered, "removed": [] })); + } + let count = plans.len(); + s.edit("Make Numbers Sequence", |d, sel| { + for (id, changes) in &plans { + let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; + apply(t, changes); + refresh_bounds(t); + } + d.remove_many(&removed)?; + if !removed.is_empty() { + sel.remove_all(removed.iter().copied()); + } + Ok(()) + })?; + Ok(json!({ "count": count, "ids": numbered, "removed": removed.iter().map(|id| id.0).collect::>() })) +} diff --git a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs new file mode 100644 index 0000000000..d472268049 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs @@ -0,0 +1,444 @@ +//! Make Numbers Sequence: the numbers a sequence gives, what each replace mode changes, the +//! orders, removed objects, one undo step, and bad params refused without a change. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind, TextObject, TextRun}; + +use super::{COMMAND as C, Options, apply, edits, number_spans, placeholder_spans, sequence, text_passes}; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn text_at(s: &mut Session, x: f64, y: f64, words: &str) -> NodeId { + NodeId(s.execute("text.create", &json!({"x": x, "y": y, "text": words, "size": 20})).unwrap()["id"].as_u64().unwrap()) +} + +fn plain(s: &Session, id: NodeId) -> String { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn seq(p: Value, count: usize) -> Vec { + sequence(&Options::parse(&p).unwrap(), count) +} + +#[test] +fn a_sequence_steps_toward_its_end_and_pads_with_zeros() { + assert_eq!(seq(json!({"start": 1, "step": 5, "end": 20}), 10), ["01", "06", "11", "16"], "stops past the end"); + assert_eq!(seq(json!({"start": 10, "step": 3, "end": 1, "leadingZeros": false}), 10), ["10", "7", "4", "1"], "the step turns to run down"); + assert_eq!(seq(json!({"start": 8, "digits": 3}), 3), ["008", "009", "010"]); + assert_eq!(seq(json!({"start": -1, "step": 1}), 3), ["-1", "0", "1"], "negative numbers get no zeros"); + assert_eq!(seq(json!({"start": 0.1, "step": 0.1, "leadingZeros": false}), 3), ["0.1", "0.2", "0.3"], "no rounding noise"); + assert_eq!(seq(json!({"start": 1, "step": 0.25, "trailingZeros": true}), 3), ["1.00", "1.25", "1.50"]); + assert_eq!(seq(json!({"start": 4, "step": 0}), 3), ["4", "4", "4"]); + assert_eq!( + seq(json!({"start": 1e9 + 0.1, "step": 0.1, "end": 1e9 + 0.3}), 5), + ["1000000000.1", "1000000000.2", "1000000000.3"], + "a value that rounds to the end counts" + ); + assert_eq!( + seq(json!({"start": 10000000000.1, "step": 0.1, "end": 10000000000.3}), 5), + ["10000000000.1", "10000000000.2", "10000000000.3"], + "large values keep the inclusive decimal end" + ); + assert_eq!(seq(json!({"start": 1e12, "step": 0.000001, "end": 1e12}), 3), ["1000000000000"], "an end equal to the start counts"); + assert_eq!( + seq(json!({"start": 999999999999.9_f64, "step": 0.000001}), 3), + ["999999999999.9", "999999999999.900001", "999999999999.900002"], + "large values keep their decimal digits when scaled for a small step" + ); + assert_eq!( + seq(json!({"start": 999999999999.9_f64, "step": 0.000001, "end": 999999999999.9_f64}), 3), + ["999999999999.9"], + "the end uses the same decimal scaling as the start" + ); + assert_eq!(seq(json!({"start": 0.1, "step": 3.3}), 4), ["00.1", "03.4", "06.7", "10"], "padded to the rounded last number"); + assert_eq!(seq(json!({"start": 1, "step": 1_000_000_000_000_u64}), 9009).last().map(String::as_str), Some("9008000000000001")); + assert_eq!(seq(json!({"start": -0.25, "step": 0.125}), 5), ["-0.25", "-0.125", "0", "0.125", "0.25"]); + assert_eq!(seq(json!({"start": -0.0000001, "step": 0}), 1), ["0"], "rounded zero has no minus sign"); + assert_eq!(seq(json!({"start": 9.9999999, "step": 0}), 1), ["10"], "width uses the rounded whole part"); + assert_eq!(seq(json!({"start": -0.0000005, "step": 0}), 1), ["-0.000001"], "decimal ties round away from zero"); +} + +#[test] +fn unthreaded_type_checks_the_threads_once() { + let mut s = session(); + let ids: Vec = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect(); + let scans = super::threads::thread_scans(); + super::make_numbers(&mut s, &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + assert_eq!(super::threads::thread_scans() - scans, 1, "selection size does not multiply thread scans"); + assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::>(), ["1", "2", "3"]); +} + +#[test] +fn threaded_type_is_refused() { + let mut s = session(); + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "1 2 3", "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 n = steps(&s); + assert!(s.execute(C, &json!({"ids": [a, b]})).is_err()); + 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)]); + assert!(number_spans("none").is_empty()); + assert_eq!(placeholder_spans("a{%N}b{%n}"), [(1, 5), (6, 10)]); +} + +#[test] +fn the_whole_text_gets_numbered_in_stacking_order_as_one_step() { + let mut s = session(); + let ids: Vec = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect(); + let n = steps(&s); + let out = s.execute(C, &json!({"ids": [ids[2].0, ids[0].0, ids[1].0], "start": 7})).unwrap(); + assert_eq!(out["count"], json!(3)); + assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::>(), ["7", "8", "9"], "from the back"); + assert_eq!(steps(&s), n + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(ids.iter().all(|id| plain(&s, *id) == "x"), "undone"); +} + +#[test] +fn numbers_and_placeholders_are_replaced_inside_the_text() { + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, "Seat 99, row 4"); + let b = text_at(&mut s, 40.0, 140.0, "no digits"); + let c = text_at(&mut s, 40.0, 180.0, "Seat 1"); + s.execute(C, &json!({"ids": [a.0, b.0, c.0], "replace": "numbers", "start": 5})).unwrap(); + assert_eq!([plain(&s, a), plain(&s, b), plain(&s, c)], ["Seat 5, row 5", "no digits", "Seat 6"], "text with no number is skipped"); + let d = text_at(&mut s, 40.0, 220.0, "Tag {%N} / {%n}"); + let e = text_at(&mut s, 40.0, 260.0, "Tag 3"); + s.execute(C, &json!({"ids": [d.0, e.0], "replace": "placeholder", "start": 2})).unwrap(); + assert_eq!([plain(&s, d), plain(&s, e)], ["Tag 2 / 2", "Tag 3"]); +} + +#[test] +fn ruby_follows_each_number_or_placeholder_replacement() { + let mut s = session(); + let word = "漢字"; + for (replace, words) in [("numbers", "1 2 漢字"), ("placeholder", "{%n} {%N} 漢字")] { + let id = text_at(&mut s, 40.0, 100.0, words); + let start = words.find(word).unwrap(); + s.execute("type.ruby", &json!({"ids": [id.0], "start": start, "end": start + word.len(), "text": "かんじ"})).unwrap(); + s.execute(C, &json!({"ids": [id.0], "replace": replace, "start": 123456})).unwrap(); + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not text") }; + let text = t.plain_text(); + assert_eq!(text, "123456 123456 漢字"); + assert_eq!(t.ruby.len(), 1); + let ruby = &t.ruby[0]; + assert_eq!(&text[ruby.start..ruby.end], word, "ruby follows both replacements in {replace} mode"); + assert_eq!(ruby.text, "かんじ"); + } +} + +#[test] +fn rows_and_columns_order_by_position() { + let mut s = session(); + // Created bottom-right first, so stacking order differs from both positions. + let br = text_at(&mut s, 300.0, 200.0, "x"); + let tl = text_at(&mut s, 40.0, 100.0, "x"); + let bl = text_at(&mut s, 40.0, 200.0, "x"); + let tr = text_at(&mut s, 300.0, 102.0, "x"); + let ids = json!([br.0, tl.0, bl.0, tr.0]); + s.execute(C, &json!({"ids": ids, "order": "rows"})).unwrap(); + assert_eq!([tl, tr, bl, br].map(|id| plain(&s, id)), ["1", "2", "3", "4"], "a small offset stays in its row"); + s.execute(C, &json!({"ids": ids, "order": "columns"})).unwrap(); + assert_eq!([tl, bl, tr, br].map(|id| plain(&s, id)), ["1", "2", "3", "4"]); +} + +#[test] +fn an_end_leaves_the_rest_or_removes_it() { + let mut s = session(); + let ids: Vec = (0..4).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect(); + let all = json!(ids.iter().map(|id| id.0).collect::>()); + s.execute(C, &json!({"ids": all, "end": 2})).unwrap(); + assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::>(), ["1", "2", "x", "x"]); + let out = s.execute(C, &json!({"ids": all, "start": 5, "end": 6, "removeUnused": true})).unwrap(); + assert_eq!(out["removed"], json!([ids[2].0, ids[3].0])); + assert!(s.doc().unwrap().doc.node(ids[3]).is_none()); +} + +#[test] +fn shuffle_gives_every_number_once() { + let mut s = session(); + let ids: Vec = (0..6).map(|i| text_at(&mut s, 40.0, 60.0 + 40.0 * f64::from(i), "x")).collect(); + let all = json!(ids.iter().map(|id| id.0).collect::>()); + s.execute(C, &json!({"ids": all, "shuffle": true, "seed": 3, "leadingZeros": false})).unwrap(); + let mut got: Vec = ids.iter().map(|id| plain(&s, *id)).collect(); + assert_ne!(got, ["1", "2", "3", "4", "5", "6"], "seed 3 moves them"); + got.sort(); + assert_eq!(got, ["1", "2", "3", "4", "5", "6"]); +} + +#[test] +fn shuffle_with_an_end_can_number_any_object() { + let mut numbered = [false; 6]; + for seed in 0..40 { + let mut s = session(); + let ids: Vec = (0..6).map(|i| text_at(&mut s, 40.0, 60.0 + 40.0 * f64::from(i), "x")).collect(); + let all = json!(ids.iter().map(|id| id.0).collect::>()); + let out = s.execute(C, &json!({"ids": all, "shuffle": true, "seed": seed, "end": 2, "removeUnused": true})).unwrap(); + assert_eq!(out["removed"].as_array().unwrap().len(), 4); + for (i, id) in ids.iter().enumerate() { + numbered[i] |= s.doc().unwrap().doc.node(*id).is_some(); + } + } + assert_eq!(numbered, [true; 6], "every object is numbered for some seed"); +} + +#[test] +fn the_same_seed_numbers_and_removes_the_same_objects() { + let run = || { + let mut s = session(); + let ids: Vec = (0..8).map(|i| text_at(&mut s, 40.0, 40.0 + 40.0 * f64::from(i), "x")).collect(); + let all = json!(ids.iter().map(|id| id.0).collect::>()); + let out = s.execute(C, &json!({"ids": all, "shuffle": true, "seed": 11, "end": 4, "removeUnused": true})).unwrap(); + let texts: Vec> = ids.iter().map(|id| s.doc().unwrap().doc.node(*id).map(|_| plain(&s, *id))).collect(); + let removed: Vec = + out["removed"].as_array().unwrap().iter().map(|r| ids.iter().position(|id| Some(id.0) == r.as_u64()).unwrap()).collect(); + (texts, removed) + }; + let (texts, removed) = run(); + assert_eq!(removed.len(), 4); + assert_eq!(run(), (texts, removed), "seed 11 gives each object the same number and removes the same ones"); +} + +fn group_of(s: &mut Session, ids: &[NodeId]) -> NodeId { + s.execute("select.set", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.doc().unwrap().doc.parent_of(ids[0]).unwrap() +} + +#[test] +fn a_negative_number_in_the_text_is_replaced_with_its_sign() { + assert_eq!(number_spans("Seat -4, A-4"), [(5, 7), (11, 12)], "a hyphen after a letter is not a sign"); + assert_eq!(number_spans("É-4"), [(3, 4)], "nor after a letter outside ASCII"); + assert_eq!(number_spans("E\u{301}-4"), [(4, 5)], "nor after a letter with a combining mark"); + assert_eq!(number_spans("क्-4"), [(7, 8)], "nor after a letter with a virama"); + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, "Seat -4"); + let b = text_at(&mut s, 40.0, 140.0, "Seat 9"); + s.execute(C, &json!({"ids": [a.0, b.0], "replace": "numbers", "start": 2, "step": -3})).unwrap(); + assert_eq!([plain(&s, a), plain(&s, b)], ["Seat 2", "Seat -1"]); +} + +#[test] +fn a_match_that_already_reads_the_number_is_not_edited() { + let text = "5 and 4"; + assert_eq!(super::edits(text, number_spans(text), "5"), [(6, 7, "5".to_string())]); +} + +#[test] +fn too_many_matches_in_one_run_are_refused() { + let mut unchanged = session(); + let text = vec!["1"; super::MAX_MATCHES + 1].join(" "); + let id = text_at(&mut unchanged, 40.0, 100.0, &text); + let before = steps(&unchanged); + let out = unchanged.execute(C, &json!({"ids": [id.0], "start": 1, "replace": "numbers"})).unwrap(); + assert_eq!(out["count"], 0); + assert_eq!(plain(&unchanged, id), text); + assert_eq!(steps(&unchanged), before); + + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, &"{%n}".repeat(super::MAX_MATCHES + 1)); + let n = steps(&s); + assert!(s.execute(C, &json!({"ids": [a.0], "replace": "placeholder"})).is_err()); + assert_eq!(steps(&s), n); + // Whole texts are not matches: the object limit covers them. + s.execute("edit.undo", &json!({})).unwrap(); + text_at(&mut s, 40.0, 140.0, "x"); + // Each duplicate of the whole selection doubles it: 2^14 objects in 14 steps. + for _ in 0..14 { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + let count = s.doc().unwrap().selection.objects.len(); + assert!(count > super::MAX_MATCHES, "{count} objects"); + let out = s.execute(C, &json!({"step": 0})); + assert!(out.is_ok()); + let out = out.unwrap(); + assert!(out["count"].as_u64().unwrap() > super::MAX_MATCHES as u64); +} + +#[test] +fn locked_and_hidden_type_in_a_group_is_left_alone() { + let mut s = session(); + let ids: Vec = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect(); + let group = group_of(&mut s, &ids); + s.execute("object.setProps", &json!({"ids": [ids[1].0], "locked": true})).unwrap(); + s.execute("object.setProps", &json!({"ids": [ids[2].0], "visible": false})).unwrap(); + let out = s.execute(C, &json!({"ids": [group.0], "end": 1, "removeUnused": true})).unwrap(); + assert_eq!(out["removed"], json!([])); + assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::>(), ["1", "x", "x"]); +} + +#[test] +fn removing_unused_type_keeps_a_clipping_mask_and_the_selection() { + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, "x"); + let b = text_at(&mut s, 40.0, 140.0, "x"); + // The top object becomes the mask; it sits lowest on the page, so rows number it last. + let mask = text_at(&mut s, 40.0, 300.0, "x"); + s.execute("select.set", &json!({"ids": [a.0, b.0, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let group = s.doc().unwrap().doc.parent_of(mask).unwrap(); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + let out = s.execute(C, &json!({"order": "rows", "end": 1, "removeUnused": true})).unwrap(); + assert_eq!(out["removed"], json!([b.0]), "the mask stays"); + assert!(s.doc().unwrap().doc.node(mask).is_some()); + assert_eq!(s.doc().unwrap().selection.objects, [group], "the group stays selected"); +} + +#[test] +fn rows_are_found_among_the_type_that_gets_numbers() { + let mut s = session(); + let upper = text_at(&mut s, 300.0, 100.0, "1"); + let lower = text_at(&mut s, 40.0, 135.0, "1"); + let h1 = NodeId(s.execute("text.create", &json!({"x": 40, "y": 400, "text": "Title", "size": 200})).unwrap()["id"].as_u64().unwrap()); + let h2 = NodeId(s.execute("text.create", &json!({"x": 40, "y": 700, "text": "Title", "size": 200})).unwrap()["id"].as_u64().unwrap()); + s.execute(C, &json!({"ids": [upper.0, lower.0, h1.0, h2.0], "replace": "numbers", "order": "rows", "start": 1, "leadingZeros": false})).unwrap(); + assert_eq!([plain(&s, upper), plain(&s, lower)], ["1", "2"], "headings without numbers do not merge the rows"); +} + +#[test] +fn a_run_that_changes_nothing_makes_no_step_and_bad_params_fail() { + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, "1"); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({"ids": [a.0]})).unwrap()["count"], json!(0)); + assert_eq!(steps(&s), n); + for p in [ + json!({"ids": [a.0], "start": "one"}), + json!({"ids": [a.0], "step": 1e13}), + json!({"ids": [a.0], "order": "diagonal"}), + json!({"ids": [a.0], "digits": 0}), + json!({"ids": [a.0], "removeUnused": true}), + json!({"ids": [a.0], "shuffle": "yes"}), + json!({"ids": [a.0], "seed": "x"}), + ] { + assert!(s.execute(C, &p).is_err(), "{p} fails"); + } + 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/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs index a8518719be..148ccd4b9a 100644 --- a/crates/engine/src/cmd/addons/typetools/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -69,7 +69,8 @@ fn a_straight_ramp_sizes_each_letter_and_skips_spaces() { assert_eq!(sizes, [('a', 10.0), ('b', 20.0), (' ', 20.0), ('c', 30.0), ('d', 40.0)], "the space keeps its size"); assert_eq!(obj(&s, id).plain_text(), "ab cd", "the text stays live"); s.execute("edit.undo", &json!({})).unwrap(); - assert!(styles(&s, id).iter().all(|(_, st)| st.size == 20.0), "undone"); + let undone: Vec<(char, f64)> = styles(&s, id).into_iter().map(|(c, st)| (c, st.size)).collect(); + assert_eq!(undone, [('a', 20.0), ('b', 20.0), (' ', 20.0), ('c', 20.0), ('d', 20.0)], "undone"); } #[test] diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 426f374a5c..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, }; @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Live Paint"], Some("Cmd+Alt+X"), - "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", + "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step). The command stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {id, faces, edges}", has_selection_or_ids, lp_make ), @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Merge", ["Object", "Live Paint"], None, - "{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", + "{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step). The command stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {id, faces, edges}", has_multi_or_ids, lp_merge ), @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Gap Options", [], None, - "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step) → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", + "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step). The command stops with an error and leaves the art unchanged when a group's paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. The paths include lines across the gaps when detect is on. → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", has_selection_or_ids, lp_gap_options ), @@ -740,12 +740,13 @@ fn build_children(d: &mut Document, sources: Vec>, max_gap: Option { - let (regs, edges, _) = po::live_paint_with_gaps(&shapes, gap); + let (regs, edges, _) = po::try_live_paint_with_gaps(&shapes, gap).map_err(too_many)?; (regs, edges) } - None => po::live_paint(&shapes), + None => po::try_live_paint(&shapes).map_err(too_many)?, }; if regs.is_empty() && edges.is_empty() { return Err(EngineError::Other("Live Paint: these paths are too degenerate to paint".into())); diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 693608574e..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(); @@ -1586,6 +1622,8 @@ mod trace_limit_tests { // anchors each. let strokes = |f: &tr::SeamFills| f.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); let outlined = seams_within(&res, ¶ms, (24, 16), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap(); + assert!(!outlined.strokes.is_empty(), "{res:?}"); + assert_eq!(outlined.strokes.len(), all.as_ref().unwrap().strokes.len(), "one outline for each seam fill: {outlined:?}"); assert!(outlined.strokes.iter().all(|tp| tp.stroke.is_none() && !tp.path.is_empty()), "{outlined:?}"); let n = strokes(all.as_ref().unwrap()); assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined)); diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 610498f56a..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 @@ -696,9 +687,13 @@ mod tests { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); assert_eq!(c, layer, "the scenario needs the id to be reused"); s.execute("edit.paste", &json!({})).unwrap(); - let d = &s.doc().unwrap().doc; + let st = s.doc().unwrap(); + let d = &st.doc; let compound = d.node(NodeId(c)).unwrap(); - assert!(compound.children().unwrap().iter().all(|ch| matches!(ch.kind, vectorcraft_doc::NodeKind::Path { .. }))); + assert_eq!(compound.children().unwrap().len(), 1, "the compound path holds only the rectangle it was made from"); + let pasted = st.selection.objects.clone(); + assert_eq!(pasted.len(), 1); + assert!(d.parent_of(pasted[0]).is_some_and(|p| d.node(p).unwrap().is_layer()), "the copy lands on a layer"); } #[test] 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/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index ef9cd71850..c1cb80c939 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -1722,7 +1722,7 @@ mod tests { let jags = polyline(&ring); let sp = SubPath::new(jags.clone(), true); assert!(subpath_len(&sp) < 24.0); - assert!(smooth_corners(&jags, true, 1e-6).iter().all(|c| *c), "each jag turns sharply at its anchor"); + assert_eq!(smooth_corners(&jags, true, 1e-6), vec![true; 16], "each jag turns sharply at its anchor"); assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]); assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]); } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index bac821ab90..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 (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (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 84b8bc1a4f..0a4cf89b18 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -1,5 +1,3 @@ -#[cfg(not(target_arch = "wasm32"))] -use super::write_atomic; use super::{EngineError, Result, Session, Value, bad, json}; // ---------- the file system (none on the web, where commands take and return bytes) ---------- @@ -267,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; @@ -274,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"))); @@ -325,8 +342,30 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { // Work that stops early for a cancel can leave a truncated result: none of it is written. vectorcraft_doc::cancel::check()?; may_write(path)?; - // Never a half-written file: see [`write_atomic`]. - write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e)) + // Never a half-written file: see [`vectorcraft_format::write_atomic`]. + write_checked(path, |f| std::io::Write::write_all(f, bytes)).map_err(|e| write_error(path, e)) +} + +/// [`vectorcraft_format::write_atomic_with`] for `path`, which [`may_write`] allowed. While writes +/// are checked ([`crate::file_access::writes_checked`]), the folder that receives the file is +/// checked again as it is opened, and the file goes into that open folder +/// ([`vectorcraft_format::write_atomic_checked`]): a folder on the path that is replaced after the +/// check does not redirect the write. +#[cfg(not(target_arch = "wasm32"))] +fn write_checked(path: &str, fill: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>) -> std::io::Result<()> { + let path = std::path::Path::new(path); + if !crate::file_access::writes_checked() { + return vectorcraft_format::write_atomic_with(path, fill); + } + vectorcraft_format::write_atomic_checked(path, fill, |opened| { + // On Unix `opened` is the open folder's real path with the file's name: compared as it is, + // without looking the folder up again. Elsewhere it is `path` itself. + #[cfg(unix)] + let checked = crate::file_access::check_write_real(opened); + #[cfg(not(unix))] + let checked = crate::file_access::check_write_unrecorded(&opened.to_string_lossy()); + checked.map_err(std::io::Error::other) + }) } /// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the @@ -344,7 +383,7 @@ fn write_error(path: &str, error: std::io::Error) -> EngineError { pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; - vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e)) + write_checked(path, |f| fill(f)).map_err(|e| write_error(path, e)) } /// The save commands' writer: preserves a filesystem location refusal as a typed error. Other @@ -358,7 +397,7 @@ pub fn write_save_file(path: &str, bytes: &[u8]) -> Result<()> { pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; - vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| save_write_error(path, e)) + write_checked(path, |f| fill(f)).map_err(|e| save_write_error(path, e)) } #[cfg(not(target_arch = "wasm32"))] @@ -751,4 +790,43 @@ mod tests { assert_eq!(naming_in_error(EngineError::Other(raw.clone()), &file).to_string(), raw); let _ = std::fs::remove_dir_all(base); } + + /// The second check of a checked write compares the open folder's real path as it is: a folder + /// on that path replaced afterwards by a link into the write root does not make a place outside + /// the root pass. + #[cfg(unix)] + #[test] + fn a_checked_write_compares_the_open_folder_without_looking_it_up_again() { + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-real-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (root, out) = (base.join("root"), base.join("out")); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(out.join("x")).unwrap(); + let real = out.join("x/doc.svg"); + std::fs::remove_dir(out.join("x")).unwrap(); + std::os::unix::fs::symlink(&root, out.join("x")).unwrap(); + let roots = AutomationRoots::new(&[], &[root.as_path()]).unwrap(); + assert!(confine(roots.as_ref(), || crate::file_access::check_write_unrecorded(&real.to_string_lossy())).is_ok(), "looked up, it passes"); + let checked = confine(roots.as_ref(), || crate::file_access::check_write_real(&real)); + assert!(checked.is_err_and(|e| e.contains("outside the write root"))); + let _ = std::fs::remove_dir_all(base); + } + + /// A checked write through a link to a folder whose name is not valid UTF-8, inside the write + /// root, is saved. + #[cfg(target_os = "linux")] + #[test] + fn a_checked_write_saves_into_a_folder_whose_name_is_not_text() { + use std::os::unix::ffi::OsStrExt; + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-bytes-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let bytes = base.join(std::ffi::OsStr::from_bytes(b"folder-\xff")); + std::fs::create_dir_all(&bytes).unwrap(); + std::os::unix::fs::symlink(&bytes, base.join("text")).unwrap(); + let roots = AutomationRoots::new(&[], &[base.as_path()]).unwrap(); + let path = base.join("text/doc.svg").to_string_lossy().into_owned(); + confine(roots.as_ref(), || write_file(&path, b"new")).unwrap(); + assert_eq!(std::fs::read(bytes.join("doc.svg")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(base); + } } 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 a48ac3e85b..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 ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are 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). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are 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). Never changes the document's path", has_doc, export::export ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,