Merge remote-tracking branch 'upstream/main' into feat/indic-digit-input

# Conflicts:
#	Cargo.toml
#	docs/localization-parity.md
This commit is contained in:
ruchirguitar committed 2026-12-05 10:27:49 +05:30
commit aeb9671069
774 files changed
+94930 -5500

No files matched your search

+2
View File
@@ -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
+16 -4
View File
@@ -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:
@@ -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):
+21 -3
View File
@@ -9,19 +9,23 @@ on:
branches: [main]
schedule:
- cron: "37 3 * * *"
# `labeled` so adding the `full-ci` label starts a run of all six shards.
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# A newer push to a PR branch cancels its older run; every push to main runs to the end.
# A newer push to a PR branch cancels its older run; every push to main runs to the end. Adding
# any label other than `full-ci` gets a group of its own, so it never cancels a real run.
concurrency:
group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
group: ci-${{ github.event_name == 'pull_request' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
gate:
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
@@ -47,10 +51,24 @@ 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 <k>/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
# The dependency cache also keeps the compiled workspace crates and test executables, so a
# The dependency cache also keeps the compiled workspace crates and their library and binary
# test executables (not the integration tests' executables), so a
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
# cache-prune.yml deletes the one it replaced after each attempt. The nightly run restores
+2 -2
View File
@@ -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 (<reach>)` or `partial (<reach>)` 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:<id>` 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 <crate> --all-targets`, `cargo xtask test` or `cargo nextest run -p <crate>`. 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`.
Generated
+271 -120
View File
File diff suppressed because it is too large. Load diff
+60 -51
View File
@@ -10,53 +10,59 @@ license = "MIT OR Apache-2.0"
rust-version = "1.95"
[workspace.dependencies]
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" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# Language packs: the Craft apps' shared font store installs them (#4936).
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["pcraft-pixels"] }
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["pcraft-pixels"] }
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# Digits typed in any script in numeric fields (`vectorcraft_doc::units`).
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified).
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# WMF, EMF and EMF+ reader (craft-libs#778).
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" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps.
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
# the members it imports.
craft = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# Nightly profile isolation, launch protocol, and security fence.
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -196,22 +202,25 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
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" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
# skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa).
# It stays at this rev until craft-libs#5222 merges.
skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
+6
View File
@@ -35,6 +35,12 @@ based in part on the work of the Independent JPEG Group.
WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmparser dependency is
under the Apache License 2.0 with the LLVM exception.
DWG drawings are read by the acadrust crate 0.6.6 (https://crates.io/crates/acadrust/0.6.6), through
craft-dwg from https://github.com/storytold/craft-libs. acadrust is used unmodified under the Mozilla
Public License 2.0; its source is available at that address. Its license text and its third-party
notices (code adapted from ACadSharp, Copyright (c) 2021 Albert Domenech, MIT License) are in
licenses/acadrust-0.6.6/.
The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification
coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) and its fork by Zach
Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part
+3 -1
View File
@@ -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.
@@ -316,6 +316,8 @@ RISC-V (riscv64) packages are `vectorcraft-<ver>-linux-riscv64.deb`,
### FreeBSD
Prebuilt FreeBSD release archives target FreeBSD 15.1 or newer; FreeBSD 14.x is not supported by these builds.
| Build | File |
|---|---|
| x86_64 | `vectorcraft-<ver>-freebsd-x86_64.tar.gz` |
+11 -2
View File
@@ -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,14 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
## Progress log
- 2026-12-04: Paste from CAD apps: on Windows, Paste reads the enhanced metafile CAD and office apps copy as vector art, and a `.dxf`, `.dwg` or HP-GL plot file copied in a file manager pastes as its drawing through the new command `clipboard.importCad` (#10819). Headline numbers unchanged.
- 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 that starts again where the path turns back on itself at a cusp, a straight segment included (#10659). Headline numbers unchanged.
- 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied.
- 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged.
- 2026-11-29: 3D and Materials › Materials › Properties: Roughness and Metallic for Extrude & Bevel, Revolve, Inflate and Rotate, shaded with glTF 2.0's metallic-roughness BRDF and written into glTF and USD exports ([three-d.md](docs/three-d.md#material-properties)); scores and estimates unchanged.
- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
@@ -172,6 +179,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 `<name>_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.
@@ -265,6 +273,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-26 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; the link watcher scans them in the background, so turning it on never waits on a file; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Scores and estimates unchanged. |
| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. |
| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. |
| 2026-11-15 | minor | Graphic Styles: 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). |
+5
View File
@@ -25,6 +25,8 @@ vectorcraft-render = { workspace = true }
vectorcraft-text = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# The agent settings and the desktop app to start for plain `mcp` (the shared `src/agent_settings.rs`).
craft = { workspace = true, features = ["automation-agents"] }
# `perf` on Windows (src/perf.rs) reads how busy the processors are (GetSystemTimes) and this
# process's working set (GetProcessMemoryInfo) through winsafe's safe wrappers over Win32 (MIT),
@@ -47,11 +49,14 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std"
[dev-dependencies]
tempfile = "3"
vectorcraft-testkit = { workspace = true }
# DWG files for the `info` test, written from DXF by craft-dwg.
craft-dwg = { workspace = true }
serde_json = { workspace = true }
# The files of other crates that this crate compiles or its tests read, for CI's test selection.
[package.metadata.craft]
reads = [
"apps/vectorcraft/src/agent_settings.rs",
"apps/vectorcraft/src/mac_fonts.rs",
"apps/vectorcraft/src/prefs_dir.rs",
"apps/vectorcraft/src/profile.rs",
+175 -48
View File
@@ -2,10 +2,10 @@
//!
//! ```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 mcp [--headless] [--when-closed launch|headless|error] [--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] [--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]
@@ -39,6 +39,10 @@ macro_rules! out {
}};
}
/// The desktop app's agent settings (Preferences › AI Integrations), shared: plain `mcp` reads the
/// closed-app choice and the agent folders the app saved.
#[path = "../../vectorcraft/src/agent_settings.rs"]
mod agent_settings;
/// The desktop app's CoreText font lister, shared: exports and MCP find the same fonts.
#[cfg(target_os = "macos")]
#[path = "../../vectorcraft/src/mac_fonts.rs"]
@@ -56,9 +60,11 @@ mod system_fonts;
#[path = "../../vectorcraft/src/windows_cores.rs"]
mod windows_cores;
use craft::automation::agents::WhenAppClosed;
use serde_json::{Value, json};
use vectorcraft_engine::file_access::{self, AutomationRoots};
use vectorcraft_mcp::{Backend, DEFAULT_ADDR, Headless, Remote, Server};
use vectorcraft_mcp::agents::{LiveBackend, LiveConfig};
use vectorcraft_mcp::{Backend, Headless, Remote, Server};
/// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly, as
/// ripgrep does; any other write error is reported.
@@ -79,9 +85,18 @@ USAGE:
Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and
does not take --connect.
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
(vectorcraft --control 7979), falling back to a headless in-process session.
vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
Run the MCP server on stdio. Every tool call goes to the open VectorCraft window while AI
agents may use it (ArtCraft Launcher › Settings › AI agents), found through the connection
file the window publishes in the settings folder: no port or token to configure, and an app
opened after the session started is found too. Otherwise the call runs in a session without
a window. While agents may use VectorCraft but it is closed, the choice in Preferences › AI
Integrations applies (open VectorCraft, a session without a window in the agent folders, or
an error); --when-closed overrides it. Files of the open window's agent requests stay in the
agent folders set there (Documents/ArtCraft/Agents/VectorCraft when none is set); the
agent_folders tool names them. --headless always runs without a window.
--connect ADDR (deprecated, removed in a later release) drives an app started with
vectorcraft --control PORT and its VECTORCRAFT_CONTROL_TOKEN.
--automation-read-root / --automation-write-root confine the files the agent's commands read
(open, place, relink, library loads…) and write (save, export, package, library saves…) to
DIR, links followed; each may be given more than once, a path inside any of its folders being
@@ -98,12 +113,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 +133,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).
@@ -202,6 +224,12 @@ fn help() -> Result<(), String> {
}
fn main() -> ExitCode {
// A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits.
if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() {
std::process::exit(code);
}
// DWG drawings open through that copy, so a damaged file can't end this process.
vectorcraft_engine::dwg::use_own_worker();
// Before the first render: the cores the process may run on.
#[cfg(windows)]
windows_cores::install();
@@ -273,6 +301,20 @@ fn with_stores(mut h: Headless) -> Headless {
h
}
/// Plain `mcp`'s window lookup: the agent settings in `dir`, the closed-app choice (`--when-closed`
/// overrides the saved one), the desktop app beside this CLI to start, and headless sessions with
/// the user's stores, or confined to the agent folders without them.
fn live_config(dir: std::path::PathBuf, when_closed: Option<WhenAppClosed>) -> LiveConfig {
let mut cfg = LiveConfig::new(dir, agent_settings::read_settings);
cfg.when_closed = when_closed;
cfg.launch = std::env::current_exe().ok().and_then(|cli| craft::automation::agents::launcher(&cli, vectorcraft_mcp::agents::APP_EXE));
cfg.headless = Box::new(|roots| match roots {
Some(roots) => Headless::with_document().with_automation_roots(Some(roots)),
None => with_stores(Headless::with_document()),
});
cfg
}
/// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`).
fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
if allow {
@@ -281,26 +323,34 @@ fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
h
}
/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own
/// plug-ins, so `--connect` is refused and the default does not connect.
/// The stderr line `mcp --connect` prints: the flag works for one more release.
const CONNECT_DEPRECATED: &str = "vectorcraft-cli: --connect is deprecated and will be removed in a later release; plain `vectorcraft-cli mcp` finds the open VectorCraft window while AI agents are on in ArtCraft Launcher › Settings › AI agents";
/// `mcp`: the open VectorCraft window while the person lets agents use it (the ArtCraft Launcher's
/// switch), found through its connection file on every tool call, otherwise a headless session
/// (`vectorcraft_mcp::agents`). `--headless`, the automation roots, `--allow-plugin-grants` and
/// `--safe-mode` (`safe_mode`: a running app loads its own plug-ins) always run headless.
/// `--connect ADDR` drives an app started with `vectorcraft --control PORT` (deprecated).
fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) {
if help_requested(args, &["--connect", "--when-closed", "--automation-read-root", "--automation-write-root"]) {
return help();
}
let mut connect: Option<String> = None;
let mut headless = false;
let mut when_closed: Option<String> = None;
let mut allow_grants = false;
let (mut read_roots, mut write_roots): (Vec<String>, Vec<String>) = (vec![], vec![]);
let mut it = args.iter();
while let Some(a) = it.next() {
// The roots also come as `--flag=DIR`, as the other Craft apps take them.
let (flag, inline) = match a.split_once('=') {
Some((f, v)) if f.starts_with("--automation-") => (f, Some(v.to_string())),
Some((f, v)) if f.starts_with("--automation-") || f == "--when-closed" => (f, Some(v.to_string())),
_ => (a.as_str(), None),
};
match flag {
"--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?),
"--headless" => headless = true,
"--when-closed" => when_closed = Some(inline.or_else(|| it.next().cloned()).ok_or("--when-closed needs launch, headless or error")?),
"--allow-plugin-grants" => allow_grants = true,
"--automation-read-root" | "--automation-write-root" => {
let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?;
@@ -321,6 +371,16 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
if safe_mode && connect.is_some() {
return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control <port>`".into());
}
let when_closed = match when_closed.as_deref() {
None => None,
Some(choice) => {
let parsed = WhenAppClosed::parse(choice).ok_or_else(|| format!("--when-closed must be launch, headless or error, not `{choice}`"))?;
if connect.is_some() || headless || safe_mode || allow_grants || !(read_roots.is_empty() && write_roots.is_empty()) {
return Err("--when-closed is for the open window of plain `mcp`; --connect, --headless, --safe-mode, --allow-plugin-grants and the automation roots never use it".into());
}
Some(parsed)
}
};
let read: Vec<&Path> = read_roots.iter().map(Path::new).collect();
let write: Vec<&Path> = write_roots.iter().map(Path::new).collect();
let roots = AutomationRoots::new(&read, &write)?;
@@ -336,13 +396,18 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
} else if headless || safe_mode || allow_grants {
Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants))
} else if let Some(addr) = connect {
eprintln!("{CONNECT_DEPRECATED}");
// Explicit address: fail loudly if the app isn't there.
let token = vectorcraft_mcp::control_token()?;
Box::new(Remote::connect(&addr, &token).map_err(|e| format!("cannot connect to {addr}: {e}"))?)
} else {
// No token or no app listening: the headless session answers instead.
match vectorcraft_mcp::control_token().ok().and_then(|token| Remote::connect(DEFAULT_ADDR, &token).ok()) {
Some(r) => Box::new(r),
match prefs_dir::prefs_dir() {
Some(dir) => Box::new(LiveBackend::new(live_config(dir, when_closed))),
// No settings folder (no home folder): no window can be found either, so `--when-closed error`
// refuses rather than answering from a session the agent didn't ask for.
None if when_closed == Some(WhenAppClosed::Error) => {
return Err("VectorCraft's settings folder can't be found (no home folder), so its window can't be either: open VectorCraft, or run `mcp` without `--when-closed error`".into());
}
None => Box::new(with_stores(Headless::with_document())),
}
};
@@ -367,6 +432,9 @@ fn convert(args: &[String]) -> Result<(), String> {
"--scale",
"-s",
"--ppi",
"--width",
"--height",
"--background",
"--artboard",
"-a",
"--range",
@@ -381,9 +449,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::<f64>, None::<u64>, None::<String>, false, false, false, false);
let mut ppi = None::<f64>;
let (mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) =
(None::<u64>, None::<String>, false, false, false, false);
let mut size = RasterSize::default();
let mut decimals = None::<u64>;
// 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 +462,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 +506,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 +562,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<f64>,
ppi: Option<f64>,
width: Option<f64>,
height: Option<f64>,
background: Option<String>,
}
/// A pixel size or resolution flag's value: a positive finite number.
fn positive(flag: &str, raw: Option<&String>) -> Result<f64, String> {
raw.and_then(|v| v.parse::<f64>().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<String, String> {
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<f64>, ppi: Option<f64>) -> 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
}
@@ -569,6 +674,8 @@ fn thumbnail(args: &[String]) -> Result<(), String> {
}
}
let [input, output] = <[&str; 2]>::try_from(files).map_err(|_| "thumbnail needs IN and OUT")?;
// A DWG worker ends by then too, so the exit below leaves no conversion running.
vectorcraft_engine::dwg::use_own_worker_for(THUMBNAIL_TIME);
// The process ends when the time is up, wherever the work is: OUT is written whole or not at all.
std::thread::spawn(|| {
std::thread::sleep(THUMBNAIL_TIME);
@@ -698,7 +805,23 @@ fn command_step(v: Value) -> Result<Step, String> {
}
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 +830,7 @@ fn run(args: &[String]) -> Result<(), String> {
// The step of the `--cmd` just given, which a `--params` sets.
let mut params_for: Option<usize> = None;
let mut stdin_read = false;
let mut scale = None::<f64>;
let mut ppi = None::<f64>;
let mut size = RasterSize::default();
let mut allow_grants = false;
let mut it = args.iter();
while let Some(a) = it.next() {
@@ -747,17 +869,22 @@ fn run(args: &[String]) -> Result<(), String> {
"--allow-plugin-grants" => allow_grants = true,
"--scale" | "-s" => {
let raw = val("a number")?;
scale = Some(raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?);
size.scale = Some(raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?);
}
"--ppi" => {
"--ppi" | "--width" | "--height" => {
let raw = val("a number")?;
ppi = Some(
raw.parse::<f64>()
.ok()
.filter(|n| n.is_finite() && *n > 0.0)
.ok_or_else(|| format!("--ppi {raw}: needs a positive finite number"))?,
);
let n = raw
.parse::<f64>()
.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 +928,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}))?;
+17
View File
@@ -836,3 +836,20 @@ fn runs_without_preferences_remember_nothing() {
let r = run_in(&config, &[("pdf.preset.list", json!({}))]);
assert!(r[0]["presets"].as_array().unwrap().iter().all(|p| p["builtIn"] == true));
}
/// Plain `mcp` takes `--when-closed` for the open window only, and `--connect` still works for one
/// release but says it is deprecated before it connects.
#[test]
fn mcp_when_closed_and_the_deprecated_connect() {
let fails = |args: &[&str], why: &str| {
let out = Command::new(crate::bin()).args(args).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success() && err.contains(why), "{args:?}: {err}");
err.into_owned()
};
fails(&["mcp", "--when-closed", "later"], "--when-closed must be launch, headless or error");
fails(&["mcp", "--when-closed", "launch", "--headless"], "--when-closed is for the open window");
fails(&["mcp", "--when-closed=error", "--connect", "127.0.0.1:1"], "--when-closed is for the open window");
let err = fails(&["mcp", "--connect", "127.0.0.1:1"], "--connect is deprecated");
assert!(err.contains("cannot connect") || err.contains("no control token"), "{err}");
}
+169
View File
@@ -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"]);
@@ -276,3 +378,70 @@ fn convert_and_run_write_ait_templates() {
assert!(!one.status.success());
assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr));
}
/// A DWG drawing opens through a worker copy of the program, so a damaged one ends in an error from
/// `info`, never in a crash. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on
/// aarch64.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
#[test]
fn info_reads_a_dwg_and_a_damaged_one_is_an_error_not_a_crash() {
let dxf = tmp("plan.dxf");
make(&dxf, 120, 80);
craft_dwg::allow_in_process();
let dwg = craft_dwg::dxf_to_dwg_as(&std::fs::read(&dxf).unwrap(), "AC1018").unwrap();
let good = tmp("plan.dwg");
std::fs::write(&good, &dwg).unwrap();
// The DWG comes in as the DXF it was written from.
let (v, from) = (info(&good), info(&dxf));
assert!(v["kinds"]["Path"].as_u64().is_some_and(|n| n > 0), "{v}");
assert_eq!((&v["kinds"], &v["artboards"][0]["rect"]), (&from["kinds"], &from["artboards"][0]["rect"]), "{v}\n{from}");
let n = dwg.len();
let mut damaged = vec![dwg[..n / 3].to_vec(), dwg[..2 * n / 3].to_vec(), dwg[..16].to_vec()];
let mut overwritten = dwg.clone();
overwritten[n / 2..(n / 2 + 64).min(n)].fill(0xFF);
damaged.push(overwritten);
let mut flipped = dwg.clone();
flipped.iter_mut().skip(32).step_by(97).for_each(|b| *b ^= 0xA5);
damaged.push(flipped);
for (i, bytes) in damaged.iter().enumerate() {
let path = tmp(&format!("damaged-{i}.dwg"));
std::fs::write(&path, bytes).unwrap();
let out = Command::new(crate::bin()).args(["info", &path]).output().unwrap();
// A process ended by a signal has no exit code.
assert!(out.status.code().is_some(), "damaged file {i}: {:?}", out.status);
// The file cut to a third and the one cut to its header can't be read; the reader may
// recover the others.
if i == 0 || i == 2 {
assert!(!out.status.success(), "damaged file {i} is refused: {}", String::from_utf8_lossy(&out.stdout));
}
if !out.status.success() {
assert!(String::from_utf8_lossy(&out.stderr).contains("DWG"), "damaged file {i}: {}", String::from_utf8_lossy(&out.stderr));
}
}
}
/// A DWG worker started with a deadline (as `thumbnail` starts one) exits with code 1 once the
/// deadline passes, even while it still waits for its drawing, and at once when it has already
/// passed, so `thumbnail`'s exit leaves no conversion running.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
#[test]
fn a_dwg_worker_with_a_time_limit_exits_when_the_time_is_up() {
let now = std::time::SystemTime::now();
for until in [now + std::time::Duration::from_secs(1), now - std::time::Duration::from_secs(1)] {
let millis = until.duration_since(std::time::UNIX_EPOCH).unwrap().as_millis().to_string();
let mut worker = Command::new(crate::bin())
.args(["--dwg-worker", "--dwg-worker-until", &millis])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap();
// Its input stays open, so the worker never gets the whole request.
let input = worker.stdin.take();
let out = worker.wait_with_output().unwrap();
drop(input);
assert_eq!(out.status.code(), Some(1), "{:?}", out.status);
// It stops without answering, so no partial drawing reaches the caller.
assert!(out.stdout.is_empty(), "{} bytes written", out.stdout.len());
}
}
+1 -1
View File
@@ -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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", version = "0.1.0" }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
+2 -1
View File
@@ -143,7 +143,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
let pen = host.pointers.borrow().pen();
let spec = InstallSpec::new(ShellInfo::current(), Arc::new(SystemWindows)).pen(pen);
// The interface faces the page serves are fetched by the stack as text needs them.
let fonts = vectorcraft_ui_egui::ui_fonts().fetcher(Arc::new(crate::fonts::BrowserFetcher));
let language = taken.borrow().as_ref().map_or_else(i18n::system_lang, VectorcraftApp::ui_language);
let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, language, Some(Arc::new(crate::fonts::BrowserFetcher)));
embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?;
egui_extras::install_image_loaders(ctx);
let files = {
+6 -1
View File
@@ -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"] }
+77
View File
@@ -0,0 +1,77 @@
//! The agent settings of Preferences › AI Integrations, in `agents.json` in the settings folder
//! (`prefs_dir.rs`). The desktop app writes them when they change (`prefs.agents`); `vectorcraft-cli`
//! (which shares this file) reads them on every tool call of plain `mcp`, for the closed-app choice
//! and the agent folders.
use std::io::Read as _;
use std::path::Path;
use craft::automation::agents::AgentSettings;
use serde_json::Value;
/// The file in the settings folder: `{"controlPort", "readRoot", "writeRoot", "whenAppClosed",
/// "allowAgentControl"}`, the framework's `AgentSettings`.
pub const SETTINGS_FILE: &str = "agents.json";
/// The largest settings file read; the settings are a few short strings.
const MAX_SETTINGS_FILE: u64 = 64 * 1024;
/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be read,
/// so neither the app nor the CLI fails over them. One bad value resets only itself.
pub fn read_settings(dir: &Path) -> AgentSettings {
let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() };
let mut text = String::new();
if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE {
return AgentSettings::default();
}
let Ok(Value::Object(saved)) = serde_json::from_str::<Value>(&text) else { return AgentSettings::default() };
let mut settings = AgentSettings::default();
for (key, value) in saved {
let Ok(Value::Object(mut one)) = serde_json::to_value(&settings) else { continue };
if one.contains_key(&key) {
one.insert(key, value);
if let Ok(next) = serde_json::from_value(Value::Object(one)) {
settings = next;
}
}
}
settings
}
/// Saves `settings` in `dir` (created when missing), replacing the file in one step, so a
/// `vectorcraft-cli mcp` reading it at the same time sees the old or the new settings, never half.
// The desktop writes the settings; `vectorcraft-cli` includes this file and only reads them.
#[allow(dead_code)]
pub fn write_settings(dir: &Path, settings: &AgentSettings) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?;
let partial = dir.join(format!("{SETTINGS_FILE}.{}.tmp", std::process::id()));
std::fs::write(&partial, text)?;
std::fs::rename(&partial, dir.join(SETTINGS_FILE)).inspect_err(|_| {
let _ = std::fs::remove_file(&partial);
})
}
#[cfg(test)]
mod tests {
use super::*;
use craft::automation::agents::WhenAppClosed;
// Settings saved by the app read back in the CLI, and a damaged file or value never fails it.
#[test]
fn saved_settings_read_back_and_bad_values_reset_alone() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(read_settings(dir.path()), AgentSettings::default());
let mut settings = AgentSettings::default();
settings.read_root = "/in".into();
settings.when_app_closed = WhenAppClosed::Headless;
write_settings(dir.path(), &settings).unwrap();
assert_eq!(read_settings(dir.path()), settings);
std::fs::write(dir.path().join(SETTINGS_FILE), "not json").unwrap();
assert_eq!(read_settings(dir.path()), AgentSettings::default());
std::fs::write(dir.path().join(SETTINGS_FILE), r#"{"whenAppClosed": "error", "readRoot": 5, "unknown": true}"#).unwrap();
let read = read_settings(dir.path());
assert_eq!(read.when_app_closed, WhenAppClosed::Error);
assert_eq!(read.read_root, "");
}
}
+1 -1
View File
@@ -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);
+85 -6
View File
@@ -2,8 +2,10 @@
//! (`Services::clipboard`).
//!
//! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go;
//! Paste reads each of them and EPS, a bitmap as PNG, else as the device-independent bitmap that
//! screenshots and most apps copy (`CF_DIBV5`, `CF_DIB`; the system makes them of a `CF_BITMAP`).
//! Paste reads each of them and EPS, the enhanced metafile that CAD and office apps copy as
//! vector art (`CF_ENHMETAFILE`; the system makes one of a `CF_METAFILEPICT`), a bitmap as PNG,
//! else as the device-independent bitmap that screenshots and most apps copy (`CF_DIBV5`,
//! `CF_DIB`; the system makes them of a `CF_BITMAP`).
//! - macOS: text, SVG, PDF and PNG in one go: arboard writes the text, else the PNG as TIFF, and
//! the other formats are added to the same pasteboard item ([`pasteboard_additions`]); Paste
//! reads text and bitmaps, the pasteboard's SVG, PDF and EPS as vector art (#1499) and its PNG
@@ -19,7 +21,8 @@
//! that copied to send its data (a bitmap 10 s), and until that app answers, later reads fail at
//! once; a paste then waits for that read's answer off the UI thread.
//! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS,
//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). A
//! a metafile, a DXF or DWG drawing, an HP-GL plot file or a bitmap), before the clipboard's
//! other formats (the files' paths as text). A
//! file of more than 64 MiB is skipped before it is read.
use std::io::{Cursor, Read};
@@ -303,6 +306,23 @@ fn copy_within(size: Option<usize>, limit: usize, copy: impl FnOnce() -> Option<
copy().filter(|data| data.len() <= limit)
}
/// The records of an enhanced metafile, which the Windows clipboard holds as a handle
/// (`CF_ENHMETAFILE`) whose records `GetEnhMetaFileBits` copies: `bits` called without a buffer
/// gives their size, and with a buffer copies them and gives how many bytes it copied (0 when it
/// failed). Nothing is copied when the size is 0 or more than `limit` bytes ([`copy_within`]).
#[cfg_attr(not(windows), allow(dead_code))]
fn enhmetafile_bits(mut bits: impl FnMut(Option<&mut [u8]>) -> u32, limit: usize) -> Option<Vec<u8>> {
let size = usize::try_from(bits(None)).ok();
copy_within(size, limit, || {
let mut data = vec![0; size?];
let copied = usize::try_from(bits(Some(&mut data))).ok()?;
(copied > 0 && copied <= data.len()).then(|| {
data.truncate(copied);
data
})
})
}
/// The most bytes of UTF-8 that `utf16` bytes of UTF-16 text come to: a code unit (2 bytes) is at
/// most 3 bytes of UTF-8, and a surrogate pair (4 bytes) is 4.
#[cfg_attr(not(windows), allow(dead_code))]
@@ -428,10 +448,12 @@ mod win {
use std::path::PathBuf;
use windows::Win32::Graphics::Gdi::{GetEnhMetaFileBits, HENHMETAFILE};
use super::{
BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Cursor, Flavor, Flavour, LaterFlavor, MAX_BYTES, MAX_URIS, PNG, SVG,
TEXT, copied_file, copy_within, decode_png, dib_image, drop_files_within, png_flavour, read_flavor, read_image_flavor, read_later_flavor,
utf8_most, windows_formats,
BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Cursor, EMF, Flavor, Flavour, LaterFlavor, MAX_BYTES, MAX_URIS, PNG,
SVG, TEXT, copied_file, copy_within, decode_png, dib_image, drop_files_within, enhmetafile_bits, png_flavour, read_flavor, read_image_flavor,
read_later_flavor, utf8_most, windows_formats,
};
/// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the
@@ -533,6 +555,7 @@ mod win {
|| mimes.iter().any(|m| match *m {
TEXT => raw::is_format_avail(formats::CF_UNICODETEXT),
BITMAP => DIBS.into_iter().chain(formats_of(PNG)).any(raw::is_format_avail),
EMF => raw::is_format_avail(formats::CF_ENHMETAFILE),
m => formats_of(m).any(raw::is_format_avail),
})
}
@@ -571,6 +594,19 @@ mod win {
formats_of(mime).filter(|id| raw::is_format_avail(*id)).find_map(|id| copy_registered(id, MAX_BYTES).filter(|data| !data.is_empty()))
}
/// The enhanced metafile the clipboard holds, while it is open, as the bytes of an EMF file; at
/// most [`MAX_BYTES`] of them ([`enhmetafile_bits`]).
#[allow(unsafe_code)]
fn read_enhmetafile() -> Option<Vec<u8>> {
if !raw::is_format_avail(formats::CF_ENHMETAFILE) {
return None;
}
let emf = HENHMETAFILE(raw::get_clipboard_data(formats::CF_ENHMETAFILE).ok()?.as_ptr());
// SAFETY: `emf` is the clipboard's metafile handle, which stays valid while the clipboard is
// open; the call writes at most the length of the buffer it is given.
enhmetafile_bits(|buffer| unsafe { GetEnhMetaFileBits(emf, buffer) }, MAX_BYTES)
}
/// A device-independent bitmap as a PNG flavour.
fn dib_png(dib: &[u8]) -> Option<Flavour> {
png_flavour(&dib_image(dib)?)
@@ -607,6 +643,7 @@ mod win {
})?;
(TEXT, text)
}
EMF => (EMF, read_enhmetafile()?),
m => (m, read_registered(m)?),
};
// Memory blocks can be longer than the data: SVG text ends at its first NUL.
@@ -3545,6 +3582,48 @@ mod tests {
assert!(copied_file(vec![eps], &[BITMAP, TEXT]).is_none());
}
/// A DXF drawing or an HP-GL plot file copied in a file manager pastes as vector art.
#[test]
fn a_copied_cad_file_pastes() {
use vectorcraft_engine::cmd::clipboard::{DXF, HPGL};
let d = dir("cad");
let (dxf, plot) = (d.path().join("plan.dxf"), d.path().join("part.plt"));
std::fs::write(&dxf, "0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n0\n0\nENDSEC\n0\nEOF\n").unwrap();
std::fs::write(&plot, "IN;SP1;PA0,0;PD1016,0;PU;").unwrap();
assert_eq!(copied_file(vec![dxf.clone()], &PASTE_ORDER).map(|f| f.mime), Some(DXF));
assert_eq!(copied_file(vec![plot.clone()], &PASTE_ORDER).map(|f| f.mime), Some(HPGL));
assert!(copied_file(vec![dxf, plot], &[BITMAP, TEXT]).is_none());
}
/// The enhanced metafile the Windows clipboard holds is copied whole, into a buffer of the size
/// it gives; one of no records or of more than the limit is not copied, and a failed copy gives
/// nothing.
#[test]
fn an_enhanced_metafile_is_copied_within_the_limit() {
let records: Vec<u8> = (0..40).collect();
let read = |records: &[u8], fails: bool, limit: usize| {
let mut copies = 0;
let got = enhmetafile_bits(
|buffer| match buffer {
None => records.len() as u32,
Some(_) if fails => 0,
Some(buffer) => {
copies += 1;
assert_eq!(buffer.len(), records.len());
buffer.copy_from_slice(records);
records.len() as u32
}
},
limit,
);
(got, copies)
};
assert_eq!(read(&records, false, 40), (Some(records.clone()), 1));
assert_eq!(read(&records, false, 39), (None, 0));
assert_eq!(read(&[], false, 40), (None, 0));
assert_eq!(read(&records, true, 40), (None, 0));
}
#[test]
fn a_crlf_left_by_the_uri_list_is_ignored() {
let d = dir("crlf");
+43 -4
View File
@@ -27,6 +27,7 @@
//! how the window's frames reach the display (`presentation`).
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
mod agent_settings;
mod automation_args;
#[cfg(test)]
mod build_channel;
@@ -516,6 +517,30 @@ fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec<Stri
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
}
/// Agents in the open window (`vectorcraft_ui_egui::agents`): while the ArtCraft Launcher's switch
/// names VectorCraft, the window serves agents on loopback and publishes the connection in its
/// settings folder, where `vectorcraft-cli mcp` finds it. A connection file a crashed run left is
/// removed first. With `--control` (`control_port`, served by `launched`) that channel serves the
/// whole run and the link stays off. A nightly and a run without preferences have no link.
fn agents_link(ctx: &egui::Context, control_port: Option<u16>, launched: Option<&Listening>) -> Option<vectorcraft_ui_egui::agents::Agents> {
use craft::automation::agents::{AgentSwitch, remove_stale_connection};
use vectorcraft_ui_egui::agents::{Agents, LAUNCHER_APP_ID, SaveFn};
let dir = prefs_dir::prefs_dir()?;
remove_stale_connection(&dir);
let switch = AgentSwitch::watch(LAUNCHER_APP_ID, {
let ctx = ctx.clone();
move || ctx.request_repaint()
});
let save_dir = dir.clone();
let save: SaveFn = Box::new(move |settings| {
agent_settings::write_settings(&save_dir, settings).map_err(|e| format!("couldn't save the agent settings in {}: {e}", save_dir.display()))
});
let version = format!("VectorCraft {}", env!("VECTORCRAFT_BUILT_VERSION"));
let agents = Agents::new(Some(dir.clone()), version, switch, agent_settings::read_settings(&dir), save);
// The port it listens on (the one the system picked for `--control 0`), none when it couldn't.
Some(if control_port.is_some() { agents.launched_with_control(launched.map(|l| l.addr.port())) } else { agents })
}
/// The control channel's port, and the token's notice with the token itself.
type ControlChannel = (Option<u16>, Option<(String, String)>);
@@ -573,10 +598,17 @@ fn finish_pending_update(nightly: bool) {
}
fn main() -> std::process::ExitCode {
// A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits,
// before the launch profile, the logger or any window.
if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() {
std::process::exit(code);
}
// The launch profile first: a nightly build self-isolates or uses the Launcher's profile here,
// before the update helper, the logger, fonts or any saved state, and `--version` is answered
// here too.
let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS };
// DWG drawings open through that copy, so a damaged file can't end this process.
vectorcraft_engine::dwg::use_own_worker();
let nightly = launch_profile::current().is_nightly();
#[cfg(windows)]
finish_pending_update(nightly);
@@ -857,8 +889,6 @@ fn main() -> std::process::ExitCode {
Some(pen) => spec.pen(pen),
None => spec,
};
embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?;
egui_extras::install_image_loaders(ctx);
let folders = settings.lock().get().ui.last_folders.clone();
let wake = {
let ctx = ctx.clone();
@@ -875,7 +905,6 @@ fn main() -> std::process::ExitCode {
.settings(Arc::new(settings.clone()))
.files(files.clone())
.build();
host.clone().install(ctx);
let mut session = Session::new();
// The profiles loaded before come back before the preferences name any of them.
prefs_dir::attach_profile_store(&mut session);
@@ -900,12 +929,16 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_proof_setups(&mut session);
prefs_dir::attach_script_data(&mut session);
let mut app = VectorcraftApp::new(session, services(winit_window.clone()));
load_prefs(&mut app, &settings);
let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, app.ui_language(), None);
embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?;
egui_extras::install_image_loaders(ctx);
host.clone().install(ctx);
app.host = Arc::new(host);
app.adopt_context(&cc.egui_ctx);
// A nightly is updated by the Launcher: it never checks for a stable release, which
// would install this program's own updater over the nightly build.
app.set_startup_update_check(!nightly);
load_prefs(&mut app, &settings);
safe_mode::after_start(&mut app, stopped);
// Loads started later (a preference change, the end of Safe Mode) are waited for,
// after the launch's own.
@@ -1048,6 +1081,12 @@ fn main() -> std::process::ExitCode {
}
}
}
if !nightly
&& prefs_enabled()
&& let Some(agents) = agents_link(&cc.egui_ctx, control_port, control_server.as_ref())
{
app = app.with_agents(agents);
}
#[cfg(target_os = "macos")]
{
open_documents::set_ui(&cc.egui_ctx);
+549 -34
View File
@@ -19,9 +19,15 @@ impl PrintService for SystemPrint {
let note = system::print(job)?;
Ok(sent(job.title, job.printer, &note))
}
fn shared_printers(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintersFn> {
Some(std::sync::Arc::new(system::queues))
}
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, &note))))
}
fn applies_paper(&self) -> bool {
!cfg!(windows)
}
fn turns_landscape(&self) -> bool {
// macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright
// paper. craft-print turns each sheet to its own orientation on Windows.
@@ -37,32 +43,88 @@ impl PrintService for SystemPrint {
true
}
fn papers(&mut self, printer: &str, fresh: bool) -> Papers {
self.papers.poll(printer, fresh, |printer| installed_papers(&printer))
self.papers.poll(printer, fresh, std::time::Instant::now(), |printer| installed_papers(&printer))
}
}
/// The paper-size lookup in flight: the printer it reads and its worker's channel.
/// A paper-size read that waits for the worker before it.
type PaperRead = Box<dyn FnOnce(String) -> Vec<Paper> + Send>;
/// How long the newest still-running worker runs before a waiting read may start beside it, and how long a read waits
/// when no worker may start before its printer is given no paper sizes.
const PAPER_WAIT: std::time::Duration = std::time::Duration::from_secs(15);
/// The most paper-size workers alive at once, stalled ones included.
const PAPER_WORKERS: usize = 4;
/// The paper-size lookup: the printer it reads with its worker's channel, the read waiting to start with the time it
/// began waiting, and the start times and completion flags of its workers. A read starts when no worker runs, or when
/// the newest still-running worker has run [`PAPER_WAIT`] and fewer than [`PAPER_WORKERS`] are alive.
#[derive(Default)]
struct PaperLookup(Option<(String, std::sync::mpsc::Receiver<Vec<Paper>>)>);
struct PaperLookup {
current: Option<(String, std::sync::mpsc::Receiver<Vec<Paper>>)>,
waiting: Option<(String, PaperRead, std::time::Instant)>,
started: Vec<(std::time::Instant, std::sync::Arc<std::sync::atomic::AtomicBool>)>,
workers: std::sync::Arc<std::sync::atomic::AtomicUsize>,
}
/// Marks a worker finished and counts it down when it ends, including when it panics.
struct WorkerDone(std::sync::Arc<std::sync::atomic::AtomicUsize>, std::sync::Arc<std::sync::atomic::AtomicBool>);
impl Drop for WorkerDone {
fn drop(&mut self) {
self.1.store(false, std::sync::atomic::Ordering::SeqCst);
self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
}
}
impl PaperLookup {
/// Poll the lookup of `printer`. A new lookup runs `read` on a worker when `fresh` is set, when the one in flight
/// reads another printer, or when none is in flight; the earlier one's answer is dropped.
fn poll(&mut self, printer: &str, fresh: bool, read: impl FnOnce(String) -> Vec<Paper> + Send + 'static) -> Papers {
if fresh || self.0.as_ref().is_none_or(|(p, _)| p != printer) {
let (send, receive) = std::sync::mpsc::channel();
let name = printer.to_string();
let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || {
let _ = send.send(read(name));
});
self.0 = Some((printer.to_string(), receive));
/// Poll the lookup of `printer`. A new lookup of `read` is wanted when `fresh` is set, when the one in flight or
/// waiting reads another printer, or when none is in flight; the earlier one's answer is dropped. Only the newest
/// waiting read starts, when the workers allow it at `now`. Each new or replacement read begins waiting at `now`.
/// Finished workers do not delay a waiting read. A read that has waited [`PAPER_WAIT`] while
/// [`PAPER_WORKERS`] workers stall is dropped, and the printer gets no paper sizes.
fn poll(&mut self, printer: &str, fresh: bool, now: std::time::Instant, read: impl FnOnce(String) -> Vec<Paper> + Send + 'static) -> Papers {
let wanted = self.waiting.as_ref().map(|(p, ..)| p).or(self.current.as_ref().map(|(p, _)| p));
if fresh || wanted.is_none_or(|p| p != printer) {
self.current = None;
self.waiting = Some((printer.to_string(), Box::new(read), now));
}
let result = match self.0.as_ref().map(|(_, receive)| receive.try_recv()) {
self.started.retain(|(_, running)| running.load(std::sync::atomic::Ordering::SeqCst));
let alive = self.workers.load(std::sync::atomic::Ordering::SeqCst);
let may_start = alive == 0
|| (alive < PAPER_WORKERS && self.started.last().is_none_or(|(started, _)| now.saturating_duration_since(*started) >= PAPER_WAIT));
if may_start && let Some((name, read, _)) = self.waiting.take() {
let (send, receive) = std::sync::mpsc::channel();
self.workers.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let running = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
let done = WorkerDone(self.workers.clone(), running.clone());
let printer = name.clone();
let spawned = std::thread::Builder::new().name("printer-papers".into()).spawn(move || {
let worker = done;
let papers = read(printer);
worker.1.store(false, std::sync::atomic::Ordering::SeqCst);
let _ = send.send(papers);
});
if spawned.is_err() {
return Papers::Ready(Vec::new());
}
self.started.push((now, running));
self.current = Some((name, receive));
}
if let Some((.., since)) = &self.waiting {
if now.saturating_duration_since(*since) < PAPER_WAIT {
return Papers::Pending;
}
self.waiting = None;
return Papers::Ready(Vec::new());
}
let result = match self.current.as_ref().map(|(_, receive)| receive.try_recv()) {
Some(Ok(papers)) => Papers::Ready(papers),
Some(Err(std::sync::mpsc::TryRecvError::Empty)) => return Papers::Pending,
Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) | None => Papers::Ready(Vec::new()),
};
self.0 = None;
self.current = None;
result
}
}
@@ -89,6 +151,10 @@ mod system {
pub fn printers() -> Vec<Printer> {
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<Printer> {
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<Paper> {
#[cfg(windows)]
@@ -110,17 +176,208 @@ mod system {
if printer.contains(['/', '\\']) || printer.starts_with('.') {
return Vec::new();
}
const PPD_CAP: u64 = 16 << 20;
let mut bytes = Vec::new();
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
if read.is_err() {
return Vec::new();
let named = cups_server();
let sockets = local_sockets();
// A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue,
// so its sizes come from the server.
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
if named_scheduler_is_local(named.as_deref(), port, |s| std::path::Path::new(s).exists(), &sockets, real_path) {
const PPD_CAP: u64 = 16 << 20;
let mut bytes = Vec::new();
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() };
if !papers.is_empty() {
return papers;
}
}
vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes))
// A driverless or remote queue has no PPD here: `lpoptions` asks the queue's server for its sizes.
let mut command = Command::new("lpoptions");
command.args(["-p", printer, "-l"]);
let papers = paper_output(&mut command)
.map(|out| vectorcraft_ui_egui::print::lpoptions_papers(&String::from_utf8_lossy(&out)))
.unwrap_or_default();
if !papers.is_empty() {
return papers;
}
// A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses.
let 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<String> {
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<String> {
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<String> {
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<str>], resolve: impl Fn(&str) -> Option<String>) -> 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<String>, exists: impl Fn(&str) -> bool, resolve: impl Fn(&str) -> Option<String>) -> Option<String> {
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` when none is named, where CUPS uses its domain socket when one exists and
/// `localhost` on `IPP_PORT` otherwise ([`named_scheduler_is_local`] resolves that case). macOS does not read `ServerName`
/// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts.
/// A server named without a port gets the one `IPP_PORT` sets, so `localhost` with `IPP_PORT=8631` is a second
/// scheduler rather than the local one.
#[cfg(not(windows))]
fn cups_server() -> Option<String> {
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
named_cups_server().map(|server| vectorcraft_ui_egui::print::server_with_ipp_port(&server, port))
}
/// The scheduler `cups_server` names, as written.
#[cfg(not(windows))]
fn named_cups_server() -> Option<String> {
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 the scheduler CUPS uses runs on this machine, given the server `cups_server` names, the `IPP_PORT`
/// port, whether a path exists, the local scheduler's domain `sockets` and a socket path's real path. With no
/// server named, CUPS uses its domain socket when one exists, which is local, and otherwise `localhost` on the
/// `IPP_PORT` port, which is local only on port 631.
#[cfg(not(windows))]
pub(super) fn named_scheduler_is_local(
named: Option<&str>,
port: Option<u16>,
exists: impl Fn(&str) -> bool,
sockets: &[String],
resolve: impl Fn(&str) -> Option<String>,
) -> bool {
match named {
Some(server) => scheduler_is_local(Some(server), sockets, resolve),
None if CUPS_SOCKETS.iter().any(|s| exists(s)) => true,
None => scheduler_is_local(Some(&vectorcraft_ui_egui::print::server_with_ipp_port("localhost", port)), sockets, resolve),
}
}
/// 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<String>) -> 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 if let Some((host, port)) = server.rsplit_once(':').filter(|(_, port)| port.starts_with(|c: char| c.is_ascii_digit())) {
// CUPS (`cupsSetServer`) reads the digits after the last `:` of an unbracketed name as its port, so `::1` is
// host `:` on port 1.
(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<String> {
text.lines().rev().find_map(|line| {
let kept = cups_conf_line(line);
let (key, value) = kept.trim().split_once(char::is_whitespace)?;
(key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string())
})
}
/// Drain output while polling the child, and stop discovery after ten seconds.
#[cfg(windows)]
fn paper_output(command: &mut Command) -> Option<Vec<u8>> {
use std::io::Read as _;
use std::process::Stdio;
@@ -163,10 +420,14 @@ mod system {
if job.direct_pdf {
return super::direct_pdf::print(job);
}
// Copies, layout, marks and colour management are already in the PDF. Preserve its
// physical sheet size and the queue's duplex default without printing copies twice.
let settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
craft::print::submit(job.pdf, &settings).map_err(|e| e.to_string())
craft::print::submit(job.pdf, &settings(job)).map_err(|e| e.to_string())
}
/// The spooler's settings for `job`. Copies, layout, marks and colour management are already in the PDF. Preserve
/// its physical sheet size and the queue's duplex default without printing copies twice. The driver's paper
/// keyword goes to CUPS as `media`, so the queue feeds the paper the job was laid out for.
pub(crate) fn settings(job: &PrintJob) -> craft::print::Job {
let options = job.paper.map(|paper| ("media".to_string(), paper.to_string())).into_iter().collect();
craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), options, ..Default::default() }
}
#[cfg(windows)]
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
@@ -254,15 +515,27 @@ mod paper_lookup_tests {
vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }]
}
/// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers.
fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec<Paper> {
let mut polled = lookup.poll(printer, true, move |_| paper(key));
/// The test clock: `secs` seconds after a fixed start.
fn at(secs: u64) -> std::time::Instant {
static START: std::sync::OnceLock<std::time::Instant> = 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<Paper> {
loop {
match polled {
match lookup.poll(printer, false, now, |_| panic!("polling starts no lookup")) {
Papers::Ready(papers) => return papers,
Papers::Pending => std::thread::yield_now(),
}
polled = lookup.poll(printer, false, |_| panic!("polling starts no lookup"));
}
}
/// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers.
fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec<Paper> {
match lookup.poll(printer, true, at(0), move |_| paper(key)) {
Papers::Ready(papers) => papers,
Papers::Pending => settle(lookup, printer, at(0)),
}
}
@@ -279,19 +552,110 @@ mod paper_lookup_tests {
fn a_fresh_lookup_drops_the_answer_of_an_earlier_one() {
let mut lookup = PaperLookup::default();
let (open, read) = gated("Old");
assert!(matches!(lookup.poll("Card", true, read), Papers::Pending));
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
let (other, read) = gated("Office");
assert!(matches!(lookup.poll("Office", true, read), Papers::Pending));
assert!(matches!(lookup.poll("Office", true, at(0), read), Papers::Pending));
let _ = open.send(());
let _ = other.send(());
// Back on the card printer.
assert_eq!(answer(&mut lookup, "Card", "New"), paper("New"));
// The dialog opens again on the card printer while a lookup of it is still running.
let (open, read) = gated("Stale");
assert!(matches!(lookup.poll("Card", true, read), Papers::Pending));
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
let _ = open.send(());
assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer"));
}
#[test]
fn a_stalled_lookup_holds_the_only_worker_while_the_printer_changes() {
use std::sync::atomic::{AtomicUsize, Ordering};
let mut lookup = PaperLookup::default();
let (open, read) = gated("Stalled");
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
let started = std::sync::Arc::new(AtomicUsize::new(0));
for (i, printer) in ["Office", "Card", "Office", "Plotter"].into_iter().cycle().take(40).enumerate() {
let count = started.clone();
let polled = lookup.poll(printer, i % 3 == 0, at(1), move |_| {
count.fetch_add(1, Ordering::SeqCst);
paper("Changed")
});
assert!(matches!(polled, Papers::Pending), "{printer}");
assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "only the stalled worker runs");
}
let _ = open.send(());
// Only the newest choice is read, once the stalled worker ends.
assert_eq!(settle(&mut lookup, "Plotter", at(2)), paper("Changed"));
assert_eq!(started.load(Ordering::SeqCst), 1);
}
#[test]
fn a_waiting_read_starts_beside_a_worker_stalled_for_the_wait() {
use std::sync::atomic::Ordering;
let mut lookup = PaperLookup::default();
let (card, read) = gated("Stalled");
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
let (office, read) = gated("Office");
assert!(matches!(lookup.poll("Office", false, at(1), read), Papers::Pending));
assert!(matches!(lookup.poll("Office", false, at(14), |_| panic!("polling starts no lookup")), Papers::Pending));
assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "the read waits while the worker is new");
// The worker has stalled for the whole wait: the waiting read starts beside it.
assert!(matches!(lookup.poll("Office", false, at(15), |_| panic!("polling starts no lookup")), Papers::Pending));
assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the waiting read starts beside the stalled worker");
let _ = office.send(());
assert_eq!(settle(&mut lookup, "Office", at(15)), paper("Office"));
// The worker that answered counts itself down once its thread ends.
while lookup.workers.load(Ordering::SeqCst) > 1 {
std::thread::yield_now();
}
// The older worker has stalled long enough for another read to start immediately.
let (next, began) = std::sync::mpsc::channel();
let (open, read) = gated("Next");
assert!(matches!(
lookup.poll("Next", false, at(16), move |printer| {
let _ = next.send(());
read(printer)
}),
Papers::Pending
));
assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the next read starts without another wait");
began.recv().expect("the next read started");
let _ = open.send(());
assert_eq!(settle(&mut lookup, "Next", at(16)), paper("Next"));
drop(card);
}
#[test]
fn a_printer_waiting_on_stalled_workers_gets_no_sizes_after_the_wait() {
use std::sync::atomic::Ordering;
let mut lookup = PaperLookup::default();
let (card, read) = gated("Stalled");
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
// More stalls fill the workers up to the limit, one wait apart.
let mut stalls = vec![card];
for (i, printer) in ["Plotter", "Scanner", "Fax"].into_iter().enumerate() {
let (gate, read) = gated("Stalled");
stalls.push(gate);
assert!(matches!(lookup.poll(printer, true, at(30 + 15 * i as u64), read), Papers::Pending), "{printer}");
}
assert!(matches!(lookup.poll("Label", true, at(61), |_| panic!("no worker may start")), Papers::Pending));
assert!(matches!(lookup.poll("Label", false, at(75), |_| panic!("polling starts no lookup")), Papers::Pending));
// Reopening the same printer and choosing another printer each starts a new wait.
assert!(matches!(lookup.poll("Label", true, at(76), |_| panic!("no worker may start")), Papers::Pending));
assert!(matches!(lookup.poll("Photo", false, at(91), |_| panic!("no worker may start")), Papers::Pending));
assert!(matches!(lookup.poll("Photo", false, at(105), |_| panic!("polling starts no lookup")), Papers::Pending));
match lookup.poll("Photo", false, at(106), |_| panic!("polling starts no lookup")) {
Papers::Ready(papers) => assert_eq!(papers, []),
Papers::Pending => panic!("the wait for the stalled workers did not end"),
}
assert!(lookup.workers.load(Ordering::SeqCst) <= super::PAPER_WORKERS);
// Once the stalled workers end, the next choice is read again.
drop(stalls);
let papers = match lookup.poll("Photo", true, at(107), |_| paper("Ready")) {
Papers::Ready(papers) => papers,
Papers::Pending => settle(&mut lookup, "Photo", at(107)),
};
assert_eq!(papers, paper("Ready"));
}
}
#[cfg(test)]
@@ -310,3 +674,154 @@ mod turn_tests {
);
}
}
#[cfg(all(test, not(windows)))]
mod client_conf_tests {
use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, named_scheduler_is_local, scheduler_is_local};
#[test]
fn with_no_server_named_the_implicit_scheduler_decides_locality() {
let none = |_: &str| false;
let socket = |s: &str| s == "/run/cups/cups.sock";
let real = |_: &str| None;
let own = cupsd_listen_sockets("");
assert!(!named_scheduler_is_local(None, Some(8631), none, &own, real), "localhost:8631 is a second scheduler");
assert!(named_scheduler_is_local(None, Some(631), none, &own, real));
assert!(named_scheduler_is_local(None, None, none, &own, real));
assert!(named_scheduler_is_local(None, Some(8631), socket, &own, real), "CUPS's socket is the local scheduler");
assert!(!named_scheduler_is_local(Some("print.example.com"), None, socket, &own, real));
assert!(named_scheduler_is_local(Some("localhost:631"), Some(8631), none, &own, real));
}
#[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<String> {
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]: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",
"::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 a_loopback_server_on_another_ipp_port_is_not_local() {
use vectorcraft_ui_egui::print::server_with_ipp_port;
let own = cupsd_listen_sockets("");
let real = |_: &str| None;
for named in ["localhost", "127.0.0.1", "[::1]", "localhost/version=1.1"] {
assert!(!scheduler_is_local(Some(&server_with_ipp_port(named, Some(8631))), &own, real), "{named}");
assert!(scheduler_is_local(Some(&server_with_ipp_port(named, Some(631))), &own, real), "{named}");
}
// CUPS reads an unbracketed `::1` as host `:` on port 1, so it is not the local scheduler on any `IPP_PORT`.
for port in [None, Some(631), Some(8631)] {
assert!(!scheduler_is_local(Some(&server_with_ipp_port("::1", port)), &own, real), "::1 with {port:?}");
}
assert!(scheduler_is_local(Some(&server_with_ipp_port("localhost:631", Some(8631))), &own, real), "a port in the server name wins");
assert!(scheduler_is_local(Some(&server_with_ipp_port("/run/cups/cups.sock", Some(8631))), &own, real));
}
#[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:?}");
}
}
+185 -64
View File
@@ -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
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input>). 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<AltCodes> = 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<Event>) {
/// 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<Event>) -> 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<Event>) {
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();
+5 -1
View File
@@ -1 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M15 20L18 14L21 20" stroke="#fff" stroke-width="3"/><path d="M15 20L18 14L21 20" stroke="#000" stroke-width="1.2" fill="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
<path d="M15 20L18 14L21 20" stroke="#000" stroke-width="1.2" fill="none"/>
</svg>

Before

Width:  |  Height:  |  Size: 585 B

After

Width:  |  Height:  |  Size: 465 B

+5 -1
View File
@@ -1 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M16 21A6 6 0 0 1 22 15" stroke="#fff" stroke-width="3"/><path d="M16 21A6 6 0 0 1 22 15" stroke="#000" stroke-width="1.2" fill="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
<path d="M16 21A6 6 0 0 1 22 15" stroke="#000" stroke-width="1.2" fill="none"/>
</svg>

Before

Width:  |  Height:  |  Size: 593 B

After

Width:  |  Height:  |  Size: 469 B

+6 -1
View File
@@ -1 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M15 20L18.5 16.5" stroke="#fff" stroke-width="3"/><path d="M15 20L18.5 16.5" stroke="#000" stroke-width="1.2" fill="none"/><path d="M18 13h4v4h-4Z" stroke="#fff" stroke-width="3"/><path d="M18 13h4v4h-4Z" fill="#000" stroke="#000" stroke-width="1"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
<path d="M15 20L18.5 16.5" stroke="#000" stroke-width="1.2" fill="none"/>
<path d="M18 13h4v4h-4Z" fill="#000" stroke="#000" stroke-width="1"/>
</svg>

Before

Width:  |  Height:  |  Size: 707 B

After

Width:  |  Height:  |  Size: 535 B

+8 -1
View File
@@ -1 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M15.6 14.6L20.4 19.4" stroke="#fff" stroke-width="3"/><path d="M20.4 14.6L15.6 19.4" stroke="#fff" stroke-width="3"/><path d="M18 14V20" stroke="#fff" stroke-width="3"/><path d="M15 17H21" stroke="#fff" stroke-width="3"/><path d="M15.6 14.6L20.4 19.4" stroke="#000" stroke-width="1.2" fill="none"/><path d="M20.4 14.6L15.6 19.4" stroke="#000" stroke-width="1.2" fill="none"/><path d="M18 14V20" stroke="#000" stroke-width="1.2" fill="none"/><path d="M15 17H21" stroke="#000" stroke-width="1.2" fill="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
<path d="M15.6 14.6L20.4 19.4" stroke="#000" stroke-width="1.2" fill="none"/>
<path d="M20.4 14.6L15.6 19.4" stroke="#000" stroke-width="1.2" fill="none"/>
<path d="M18 14V20" stroke="#000" stroke-width="1.2" fill="none"/>
<path d="M15 17H21" stroke="#000" stroke-width="1.2" fill="none"/>
</svg>

Before

Width:  |  Height:  |  Size: 965 B

After

Width:  |  Height:  |  Size: 685 B

+1
View File
@@ -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::*;
+1
View File
@@ -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;
+1
View File
@@ -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;
+3 -1
View File
@@ -3,13 +3,14 @@ name = "vectorcraft-cad"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer"
description = "VectorCraft CAD interchange: DXF export through craft-dxf, DXF and DWG import, and an HP-GL/2 plot file reader and writer"
[lints]
workspace = true
[dependencies]
craft-dxf = { workspace = true }
craft-dwg = { workspace = true }
craft-plotter = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
@@ -21,6 +22,7 @@ vectorcraft-text = { workspace = true }
kurbo = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
web-time = "1"
[dev-dependencies]
serde_json = { workspace = true }
+115
View File
@@ -0,0 +1,115 @@
//! Block definitions and INSERT entities for the DXF writer.
//!
//! Temporary: `craft_dxf::drawing` at the pinned craft-libs revision writes only the model and
//! paper space blocks. storytold/craft-libs#5381 adds `Block`, `Drawing::blocks` and
//! `Codes::insert`; once it merges and the pin moves past it, this module is removed and
//! `scene.rs` uses those instead. Until then [`write`] adds the user blocks to the file that
//! `Drawing::write` returns, with the same group codes #5381 writes.
use craft_dxf::drawing::{Codes, Drawing, Handle, fixed};
/// A block definition: entities written once, which INSERT entities place ([`insert`]). Its base
/// point is the origin.
#[derive(Clone, Debug)]
pub struct Block {
pub name: String,
/// The handle of its BLOCK_RECORD (from R13), which owns its entities.
pub record: Handle,
/// The handles of its BLOCK and ENDBLK records.
pub begin: Handle,
pub end: Handle,
/// The entities' group codes, written with `record` as their owner.
pub entities: String,
}
/// The start of an object: its type, and from R13 its handle, owner and first subclass.
fn object(c: &mut Codes, kind: &str, h: Handle, owner: Handle, subclass: &str) {
c.raw(0, kind);
if c.v.handles() {
c.handle(5, h);
c.handle(330, owner);
c.raw(100, subclass);
}
}
/// An INSERT entity owned by `owner` on `layer` that places block `block` at the origin, unscaled
/// and unrotated. It has no color of its own (ByLayer).
pub fn insert(c: &mut Codes, h: Handle, owner: Handle, layer: &str, block: &str) {
object(c, "INSERT", h, owner, "AcDbEntity");
c.str(8, layer);
if c.v.handles() {
c.raw(100, "AcDbBlockReference");
}
c.str(2, block);
c.xyz(10, 0.0, 0.0);
}
/// The whole file of `d` with `blocks` written after the model and paper space blocks.
pub fn write(d: Drawing, blocks: &[Block]) -> String {
let v = d.version;
let out = d.write();
if blocks.is_empty() {
return out;
}
let mut defs = Codes::new(v);
for b in blocks {
object(&mut defs, "BLOCK", b.begin, b.record, "AcDbEntity");
defs.raw(8, "0");
if v.handles() {
defs.raw(100, "AcDbBlockBegin");
}
defs.str(2, &b.name);
defs.int(70, 0);
defs.xyz(10, 0.0, 0.0);
defs.str(3, &b.name);
defs.raw(1, "");
defs.append(&b.entities);
object(&mut defs, "ENDBLK", b.end, b.record, "AcDbEntity");
defs.raw(8, "0");
if v.handles() {
defs.raw(100, "AcDbBlockEnd");
}
}
let defs = defs.into_string();
if !v.handles() {
// R12 has no model and paper space blocks: its BLOCKS section holds the user blocks only.
let at = " 0\nSECTION\n 2\nENTITIES\n";
return match out.find(at) {
Some(i) => format!("{} 0\nSECTION\n 2\nBLOCKS\n{defs} 0\nENDSEC\n{}", &out[..i], &out[i..]),
None => out,
};
}
let mut records = Codes::new(v);
for b in blocks {
object(&mut records, "BLOCK_RECORD", b.record, fixed::BLOCK_RECORD_TABLE, "AcDbSymbolTableRecord");
records.raw(100, "AcDbBlockTableRecord");
records.str(2, &b.name);
if v.r2000() {
records.handle(340, Handle(0));
records.int(70, 0);
records.int(280, 1);
records.int(281, 0);
}
}
let records = records.into_string();
let (Some(table), Some(blocks_at)) = (out.find(" 0\nTABLE\n 2\nBLOCK_RECORD\n"), out.find(" 0\nSECTION\n 2\nBLOCKS\n")) else {
return out;
};
let count = " 70\n2\n";
let (Some(c), Some(t_end), Some(b_end)) = (
out[table..].find(count).map(|i| table + i),
out[table..].find(" 0\nENDTAB\n").map(|i| table + i),
out[blocks_at..].find(" 0\nENDSEC\n").map(|i| blocks_at + i),
) else {
return out;
};
let mut s = String::with_capacity(out.len() + records.len() + defs.len());
s.push_str(&out[..c]);
s.push_str(&format!(" 70\n{}\n", 2 + blocks.len()));
s.push_str(&out[c + count.len()..t_end]);
s.push_str(&records);
s.push_str(&out[t_end..b_end]);
s.push_str(&defs);
s.push_str(&out[b_end..]);
s
}
+278
View File
@@ -0,0 +1,278 @@
//! DWG drawings, read as DXF: `craft_dwg` converts the bytes and the DXF reader reads the result.
//!
//! The conversion runs in a child process once the program has called [`use_own_worker`] (and
//! [`serve_if_asked`] first thing in `main`), so a damaged file that makes the DWG reader abort
//! ends that process, not VectorCraft. Without a worker the conversion is refused, unless
//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read there.
use std::hash::BuildHasher;
use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak};
use std::time::Duration;
use web_time::Instant;
pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker};
/// The worker argument after [`WORKER_ARG`] that gives its deadline in milliseconds since the UNIX epoch
/// ([`use_own_worker_for`]).
const WORKER_UNTIL_ARG: &str = "--dwg-worker-until";
/// Serve one conversion and return the exit code if this process was started as a worker. A
/// worker started by [`use_own_worker_for`] exits with code 1 once its time is up, wherever the
/// conversion is.
pub fn serve_if_asked() -> Option<i32> {
let mut args = std::env::args_os().skip(1);
if args.next()? != WORKER_ARG {
return None;
}
if args.next().is_some_and(|a| a == WORKER_UNTIL_ARG)
&& let Some(millis) = args.next().and_then(|s| s.to_str()?.parse::<u64>().ok())
&& let Some(until) = std::time::UNIX_EPOCH.checked_add(std::time::Duration::from_millis(millis))
{
if until <= std::time::SystemTime::now() {
return Some(1);
}
std::thread::spawn(move || {
std::thread::sleep(until.duration_since(std::time::SystemTime::now()).unwrap_or_default());
std::process::exit(1);
});
}
craft_dwg::serve_if_asked()
}
/// [`use_own_worker`], each worker exiting once `limit` from this call is up (a deadline passed to it
/// in milliseconds since the UNIX epoch), however late it starts, so a program that ends after
/// `limit` leaves no conversion running. If this program's path can't be found, or the deadline
/// can't be written, the worker setting does not change. Web builds have no worker.
pub fn use_own_worker_for(limit: std::time::Duration) {
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
if let Ok(program) = std::env::current_exe()
&& let Some(until) = std::time::SystemTime::now().checked_add(limit).and_then(|until| until.duration_since(std::time::UNIX_EPOCH).ok())
&& let Ok(millis) = u64::try_from(until.as_millis())
{
craft_dwg::worker::use_worker(program, vec![WORKER_ARG.into(), WORKER_UNTIL_ARG.into(), millis.to_string().into()]);
}
#[cfg(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))]
let _ = limit;
}
/// The largest DXF rendition kept for the next read of the same drawing (128 MiB).
const MAX_KEPT: usize = 128 << 20;
/// Is `bytes` a DWG drawing (an `AC10nn` version code first)?
pub fn is_dwg(bytes: &[u8]) -> bool {
craft_dwg::is_dwg(bytes)
}
/// A DWG drawing as DXF bytes, and what the conversion left out.
#[derive(Debug, PartialEq)]
pub(crate) struct Converted {
pub dxf: Vec<u8>,
pub notes: Vec<String>,
}
type Outcome = Result<Arc<Converted>, String>;
/// The outcome of the last drawing converted, by a hash of its bytes and its length, and the
/// conversions a [`Held`] keeps. Open reads a drawing's layouts, draws a preview of each in its
/// dialog and then opens it, and each of those reads the same file; a file the conversion refused
/// (or whose worker stopped) is refused again without another conversion for [`FAILURE_KEPT`],
/// after which the next read converts it again.
#[derive(Default)]
struct Kept {
hasher: std::collections::hash_map::RandomState,
/// The last outcome, by key, and when it was kept.
last: Option<((u64, usize), Outcome, Instant)>,
/// The conversions handed out by [`hold`], while a [`Held`] for each exists.
held: Vec<((u64, usize), Weak<Converted>)>,
}
impl Kept {
fn key(&self, bytes: &[u8]) -> (u64, usize) {
(self.hasher.hash_one(bytes), bytes.len())
}
fn get(&self, key: (u64, usize), now: Instant) -> Option<Outcome> {
let fresh = |outcome: &Outcome, at: &Instant| outcome.is_ok() || now.saturating_duration_since(*at) < FAILURE_KEPT;
if let Some((_, outcome, _)) = self.last.as_ref().filter(|(k, outcome, at)| *k == key && fresh(outcome, at)) {
return Some(outcome.clone());
}
self.held.iter().filter(|(k, _)| *k == key).find_map(|(_, c)| c.upgrade()).map(Ok)
}
fn hold(&mut self, key: (u64, usize), converted: &Arc<Converted>) {
self.held.retain(|(_, c)| c.strong_count() > 0);
self.held.push((key, Arc::downgrade(converted)));
}
fn keep(&mut self, key: (u64, usize), outcome: &Outcome, now: Instant) {
if outcome.as_ref().is_ok_and(|c| c.dxf.len() > MAX_KEPT) {
self.last = None;
} else {
self.last = Some((key, outcome.clone(), now));
}
}
}
/// How long a failed conversion is returned again for the same bytes. A worker can fail for a
/// passing cause (memory, its deadline, a failed start), so a later read converts the drawing again.
const FAILURE_KEPT: Duration = Duration::from_secs(10);
/// The conversion of `bytes` that `kept` holds, else `convert`'s, which `kept` then holds. The
/// lock is not held while `convert` runs, so another drawing can be converted at the same time.
fn through(kept: &Mutex<Kept>, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Outcome {
through_at(kept, bytes, &Instant::now, convert)
}
/// [`through`] with the time read from `now`; an outcome is kept from when `convert` returned.
fn through_at(kept: &Mutex<Kept>, bytes: &[u8], now: &dyn Fn() -> Instant, convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Outcome {
let key = {
let kept = kept.lock().unwrap_or_else(PoisonError::into_inner);
let key = kept.key(bytes);
if let Some(outcome) = kept.get(key, now()) {
return outcome;
}
key
};
let outcome = convert(bytes).map(Arc::new);
kept.lock().unwrap_or_else(PoisonError::into_inner).keep(key, &outcome, now());
outcome
}
/// [`through`], and the conversion stays where `kept` finds it while the [`Held`] lasts.
fn hold_in(kept: &Mutex<Kept>, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Result<Held, String> {
let converted = through(kept, bytes, convert)?;
let mut kept = kept.lock().unwrap_or_else(PoisonError::into_inner);
let key = kept.key(bytes);
kept.hold(key, &converted);
Ok(Held { _converted: converted })
}
static KEPT: LazyLock<Mutex<Kept>> = LazyLock::new(Mutex::default);
/// `bytes` (a DWG drawing) as DXF, within craft-dwg's default limits (512 MiB of DWG, 1 GiB of DXF).
pub(crate) fn to_dxf(bytes: &[u8]) -> Outcome {
through(&KEPT, bytes, convert)
}
/// A DWG drawing's conversion, kept for every read of the same bytes ([`crate::info`],
/// [`crate::import`]) while this value exists, whatever other drawings are converted meanwhile and
/// however large its DXF is.
#[derive(Debug, Clone)]
pub struct Held {
_converted: Arc<Converted>,
}
/// Convert `bytes` (a DWG drawing), or take the conversion already kept, and keep it while the
/// returned [`Held`] exists → the conversion's error when it fails.
pub fn hold(bytes: &[u8]) -> Result<Held, String> {
hold_in(&KEPT, bytes, convert)
}
fn convert(bytes: &[u8]) -> Result<Converted, String> {
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(|e| worded(&e))?;
Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() })
}
/// craft-dwg's message or note in VectorCraft's words: VectorCraft opens a DWG and never saves one.
fn worded(message: &str) -> String {
message
.replace("accepted by this bridge", "VectorCraft opens")
.replace("types this bridge can't preserve", "types VectorCraft can't read")
.replace("; saving over the original file would lose them", "")
}
#[cfg(test)]
mod tests {
use super::*;
fn counting<'a>(calls: &'a std::cell::Cell<usize>, dxf: &'a [u8]) -> impl FnOnce(&[u8]) -> Result<Converted, String> + 'a {
move |_| {
calls.set(calls.get() + 1);
Ok(Converted { dxf: dxf.to_vec(), notes: vec![] })
}
}
#[test]
fn the_same_drawing_is_converted_once_and_another_drawing_again() {
let kept = Mutex::new(Kept::default());
let calls = std::cell::Cell::new(0);
let a = through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
let again = through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap();
assert_eq!(calls.get(), 1);
assert_eq!(again.dxf, a.dxf);
through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap();
assert_eq!(calls.get(), 2);
// The first drawing is no longer held.
through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
assert_eq!(calls.get(), 3);
}
#[test]
fn a_refused_file_is_refused_again_without_converting_and_an_oversized_rendition_is_not_kept() {
let kept = Mutex::new(Kept::default());
let calls = std::cell::Cell::new(0);
let start = Instant::now();
let at_start = move || start;
assert_eq!(through_at(&kept, b"AC1015 bad", &at_start, |_| Err("DWG: no".to_string())).unwrap_err(), "DWG: no");
let again = through_at(&kept, b"AC1015 bad", &at_start, counting(&calls, b"0\nEOF\n"));
assert_eq!((again.unwrap_err().as_str(), calls.get()), ("DWG: no", 0));
let big = vec![b' '; MAX_KEPT + 1];
through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
assert_eq!(calls.get(), 2, "a rendition over MAX_KEPT is converted again");
}
#[test]
fn a_failed_conversion_is_tried_again_once_its_time_is_up() {
let kept = Mutex::new(Kept::default());
let calls = std::cell::Cell::new(0);
let clock = std::cell::Cell::new(Instant::now());
let now = || clock.get();
// The worker fails after running for longer than FAILURE_KEPT: the failure is kept from then.
let slow_failure = |_: &[u8]| {
clock.set(clock.get() + FAILURE_KEPT * 2);
Err("DWG: stopped".to_string())
};
assert!(through_at(&kept, b"AC1015 bad", &now, slow_failure).is_err());
clock.set(clock.get() + FAILURE_KEPT / 2);
let within = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n"));
assert_eq!((within.unwrap_err().as_str(), calls.get()), ("DWG: stopped", 0));
clock.set(clock.get() + FAILURE_KEPT / 2);
let later = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n"));
assert_eq!((later.unwrap().dxf.as_slice(), calls.get()), (b"0\nEOF\n".as_slice(), 1));
// A conversion that worked is kept whatever the time.
clock.set(clock.get() + FAILURE_KEPT * 100);
through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"other")).unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn a_held_drawing_is_not_converted_again_until_its_hold_is_dropped() {
let kept = Mutex::new(Kept::default());
let calls = std::cell::Cell::new(0);
let big = vec![b' '; MAX_KEPT + 1];
let one = hold_in(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
let large = hold_in(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap();
assert_eq!(calls.get(), 3);
// Another drawing converted since, and a rendition over MAX_KEPT, are still found.
through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap();
assert_eq!(through(&kept, b"AC1015 big", counting(&calls, b"other")).unwrap().dxf.len(), big.len());
assert_eq!(calls.get(), 3);
drop((one, large));
through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
assert_eq!(calls.get(), 5, "a dropped hold no longer keeps its conversion");
let refused = hold_in(&kept, b"AC1015 bad", |_| Err("DWG: no".to_string()));
assert_eq!(refused.unwrap_err(), "DWG: no");
}
#[test]
fn messages_name_what_vectorcraft_does() {
let m = worded("DWG: the file is 9.9 MB, larger than the 1.0 MB accepted by this bridge");
assert_eq!(m, "DWG: the file is 9.9 MB, larger than the 1.0 MB VectorCraft opens");
let n = worded("DWG: 2 objects of types this bridge can't preserve were left out (X × 2); saving over the original file would lose them");
assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)");
}
}
+6
View File
@@ -76,6 +76,12 @@ pub fn is_hpgl(bytes: &[u8]) -> bool {
holds_instructions(bytes, true)
}
/// Does `bytes` start like a file named as an HP-GL plot file ([`import`] reads it)? As
/// [`is_hpgl`] checks, but any instruction may come first.
pub fn is_named_hpgl(bytes: &[u8]) -> bool {
holds_instructions(bytes, false)
}
/// Does `bytes` hold HP-GL instructions as [`is_hpgl`] checks? When `strict` is false, any of them
/// may come first: a file picked by its extension may start with one a plot file seldom starts
/// with (`SI`, `DI`). Either way, at least one of the instructions checked must be one the reader
+25 -9
View File
@@ -1,4 +1,5 @@
//! DXF import: a DXF drawing (ASCII or binary) of any version as a document.
//! DXF import: a DXF drawing (ASCII or binary) of any version as a document. A DWG drawing comes
//! in the same way, converted to DXF first ([`crate::dwg`]).
//!
//! The drawing's model space (or a paper layout) comes in at a ratio (1 unit of the art = N
//! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred
@@ -102,11 +103,24 @@ pub fn is_dxf(bytes: &[u8]) -> bool {
false
}
/// The tags of a DXF file and where it is damaged (DWG files are refused).
fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Option<String>), String> {
if bytes.starts_with(b"AC10") || bytes.starts_with(b"AC1.") {
return Err("this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that".into());
/// The tags of a DXF file, or of a DWG file converted to DXF ([`crate::dwg`]), and what the read
/// left out: where the file is damaged, and what the DWG conversion couldn't read.
fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Vec<String>), String> {
if crate::dwg::is_dwg(bytes) {
let converted = crate::dwg::to_dxf(bytes)?;
let (tags, mut notes) = dxf_tags(&converted.dxf)?;
notes.extend(converted.notes.iter().cloned());
return Ok((tags, notes));
}
// R1.x and R2.x drawings (MC0.0, AC1.2 to AC2.10), and an AC10 header with no version number.
if [&b"AC10"[..], b"AC1.", b"AC2.", b"MC0."].iter().any(|magic| bytes.starts_with(magic)) {
return Err("this DWG drawing's version can't be read: save it from the CAD app as a DXF and open that".into());
}
dxf_tags(bytes)
}
/// The tags of a DXF file and where it is damaged.
fn dxf_tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Vec<String>), String> {
let (tags, damaged) = craft_dxf::parse_recovering(bytes).map_err(|e| match e {
craft_dxf::DxfError::TooLarge { .. } => "the drawing is too large to open".to_string(),
_ if bytes.starts_with(reader::BINARY_SENTINEL) => "this binary DXF file is damaged or cut short".to_string(),
@@ -115,7 +129,7 @@ fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Option<String>), String> {
if tags.is_empty() {
return Err("not a DXF drawing".into());
}
Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out"))))
Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out")).into_iter().collect()))
}
/// The unit of `$INSUNITS` code `code` and the scale that shows the drawing 1:1 in it.
@@ -182,7 +196,7 @@ pub fn info(bytes: &[u8]) -> Result<DxfInfo, String> {
})
}
/// Import a DXF drawing with `o`.
/// Import a DXF or DWG drawing with `o`.
pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
let (w, h) = o.fit_to;
if !(w > 0.0 && h > 0.0 && w.max(h) <= build::MAX_EXTENT) {
@@ -193,7 +207,7 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
{
return Err(format!("scale must be a number from {} to {}, not {s}", SCALE_RANGE.start(), SCALE_RANGE.end()));
}
let (tags, damaged) = tags(bytes)?;
let (tags, notes) = tags(bytes)?;
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
if d.sections == 0 {
return Err("not a DXF drawing".into());
@@ -214,10 +228,12 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
};
let (mut document, mut warnings) = build::Build::new(&d, o).run(layout, natural, ratio)?;
document.units = if o.fit { unit } else { o.unit.unwrap_or(unit) };
warnings.extend(damaged);
warnings.extend(notes);
document.limit_depth_noting(&mut warnings);
Ok(Imported { document, warnings })
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_dwg;
+108 -7
View File
@@ -178,7 +178,7 @@ pub(crate) struct Converter {
const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries";
const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour";
const MESHES: &str = "3D polygon meshes and polyface meshes are left out";
const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out";
const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each";
const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all";
const FAR_AWAY: &str = "entities with coordinates out of range are left out";
@@ -233,14 +233,20 @@ impl Converter {
path(ellipse(m.common.extrusion, *center, *major, *ratio, *start, *end)?)
}
model::EntityKind::LwPolyline(p) => lwpolyline(p, ocs),
model::EntityKind::Polyline(p) => self.polyline(p, ocs),
model::EntityKind::Polyline(p) => self.polyline(p, &g, ocs),
model::EntityKind::Spline(s) => path(spline(s)?),
model::EntityKind::Solid { corners } | model::EntityKind::Trace { corners } => {
let [a, b, c, d] = corners.map(point);
// The corners zigzag: the outline runs 1, 2, 4, 3.
Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs), fill: true, width: 0.0 })
}
model::EntityKind::Face3d { corners, .. } => path(polygon(&corners.map(point))),
model::EntityKind::Face3d { corners, hidden_edges } => {
// Bit n of group 70 hides the edge from corner n.
let corners: Vec<(Point, bool)> = corners.iter().enumerate().map(|(i, c)| (point(*c), hidden_edges & (1 << i) == 0)).collect();
let mut bp = BezPath::new();
face(&mut bp, &corners);
(!bp.elements().is_empty()).then_some(bp).and_then(path)
}
model::EntityKind::Hatch(h) => self.hatch(h, ocs),
model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text),
model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text),
@@ -253,10 +259,11 @@ impl Converter {
}
}
fn polyline(&mut self, p: &model::Polyline, ocs: Affine) -> Option<Geom> {
if p.is_mesh() || p.is_polyface() {
self.warn(MESHES);
return None;
fn polyline(&mut self, p: &model::Polyline, g: &Groups<'_>, ocs: Affine) -> Option<Geom> {
// Meshes are in world coordinates, seen from above.
if p.is_polyface() || p.is_mesh() {
let bp = if p.is_polyface() { self.polyface(p) } else { self.mesh(p, g) }?;
return Some(Geom::Path { bp, fill: false, width: 0.0 });
}
// Spline frame control points and polyface faces aren't on the line.
let verts: Vec<Vertex> =
@@ -267,6 +274,60 @@ impl Converter {
Some(Geom::Path { bp, fill: false, width: p.start_width.max(0.0) })
}
/// A polyface mesh's faces: each one's visible edges, closed when all of them are.
fn polyface(&mut self, p: &model::Polyline) -> Option<BezPath> {
let points: Vec<Point> = p.vertices.iter().filter(|v| !v.is_face()).map(|v| point(v.location)).collect();
let mut bp = BezPath::new();
for f in p.vertices.iter().filter(|v| v.is_face()) {
// Vertex numbers count from 1, negative when the edge from that vertex is hidden;
// 0 ends a triangle's list.
let corners: Option<Vec<(Point, bool)>> = f
.face
.iter()
.take_while(|n| **n != 0)
.map(|n| {
let i = usize::try_from(n.unsigned_abs()).ok()?.checked_sub(1)?;
Some((*points.get(i)?, *n > 0))
})
.collect();
match corners {
Some(corners) => face(&mut bp, &corners),
None => self.warn(MESH_VERTICES),
}
}
(!bp.elements().is_empty()).then_some(bp)
}
/// A polygon mesh as its M lines and N lines. Its vertices go row by row (N to a row); a
/// smoothed mesh holds its surface's vertices (groups 73 and 74 count them) after the frame.
fn mesh(&mut self, p: &model::Polyline, g: &Groups<'_>) -> Option<BezPath> {
let points: Vec<Point> = p.vertices.iter().filter(|v| !v.is_spline_frame()).map(|v| point(v.location)).collect();
let size = |m: i64, n: i64| {
let (m, n) = (usize::try_from(m).ok()?, usize::try_from(n).ok()?);
(m > 0 && n > 0 && m.checked_mul(n) == Some(points.len())).then_some((m, n))
};
let (frame, surface) = ((p.m, p.n), (g.i_or(73, 0), g.i_or(74, 0)));
// Without the frame's vertices only the surface's counts describe the grid.
let dims = if p.vertices.iter().any(model::Vertex::is_spline_frame) {
size(surface.0, surface.1)
} else {
size(frame.0, frame.1).or_else(|| size(surface.0, surface.1))
};
let Some((m, n)) = dims else {
self.warn(MESH_VERTICES);
return None;
};
let mut bp = BezPath::new();
for row in points.chunks(n) {
line(&mut bp, row, p.flags & 32 != 0);
}
for col in 0..n {
let pts: Vec<Point> = (0..m).map(|r| points[r * n + col]).collect();
line(&mut bp, &pts, p.closed());
}
(!bp.elements().is_empty()).then_some(bp)
}
fn insert(&mut self, ins: &model::Insert, followers: &[model::Record<'_>], ocs: Affine) -> Option<Geom> {
let block = Some(ins.block.trim()).filter(|b| !b.is_empty())?.to_uppercase();
let [sx, sy, _] = ins.scale;
@@ -398,6 +459,46 @@ fn polygon(pts: &[Point]) -> BezPath {
bp
}
/// Adds the line through `pts` to `bp`, closed if `closed` (nothing for fewer than two points).
fn line(bp: &mut BezPath, pts: &[Point], closed: bool) {
if pts.len() < 2 {
return;
}
for (i, p) in pts.iter().enumerate() {
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
}
if closed {
bp.close_path();
}
}
/// Adds a face's outline to `bp`: its corners with whether the edge from each to the next is
/// visible. All visible, the outline is closed; otherwise each run of visible edges is an open
/// line.
fn face(bp: &mut BezPath, corners: &[(Point, bool)]) {
let pts: Vec<Point> = corners.iter().map(|c| c.0).collect();
let Some(hidden) = corners.iter().position(|c| !c.1) else {
line(bp, &pts, true);
return;
};
// Start after a hidden edge, so that no run is split where the list wraps.
let n = corners.len();
let mut run: Vec<Point> = Vec::new();
for k in 1..=n {
let i = (hidden + k) % n;
if corners[i].1 {
if run.is_empty() {
run.push(pts[i]);
}
run.push(pts[(i + 1) % n]);
} else {
line(bp, &run, false);
run.clear();
}
}
line(bp, &run, false);
}
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
+125
View File
@@ -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();
@@ -242,6 +248,125 @@ fn polyline_bulges_are_exact_arcs() {
assert!((b.y1 - height(&doc)).abs() < 1e-4, "the arc's chord is at y 0: {b:?}");
}
/// The straight segments of the paths of the one object a drawing brings in, in drawing
/// coordinates (y up), each with its ends in order, sorted.
fn drawn_edges(r: &Imported) -> Vec<[(i64, i64); 2]> {
let doc = &r.document;
assert_eq!(doc.layers[0].children().map_or(0, Vec::len), 1, "one object: {:?}", r.warnings);
let h = height(doc);
let at = |p: Point| (p.x.round() as i64, (h - p.y).round() as i64);
let mut edges = vec![];
for n in leaves(doc) {
let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path: {:?}", n.kind) };
for s in path.to_bezpath().segments() {
let kurbo::PathSeg::Line(l) = s else { panic!("not a line: {s:?}") };
edges.push([at(l.p0), at(l.p1)]);
}
}
sorted(edges)
}
/// Edges with their ends in order, sorted.
fn sorted(mut e: Vec<[(i64, i64); 2]>) -> Vec<[(i64, i64); 2]> {
for x in &mut e {
x.sort_unstable();
}
e.sort_unstable();
e
}
fn vertex(flags: &'static str, x: &'static str, y: &'static str, z: &'static str) -> [(i32, &'static str); 5] {
[(0, "VERTEX"), (70, flags), (10, x), (20, y), (30, z)]
}
#[test]
fn polyface_meshes_draw_their_faces_visible_edges_from_above() {
// A square at two heights as two triangles sharing a hidden diagonal, and a face naming a
// vertex the mesh doesn't have.
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "64"), (71, "4"), (72, "3")];
for (x, y, z) in [("0", "0", "5"), ("10", "0", "5"), ("10", "10", "0"), ("0", "10", "0")] {
e.extend(vertex("192", x, y, z));
}
for f in [["1", "2", "-3"], ["3", "4", "-1"], ["1", "2", "9"]] {
e.extend(vertex("128", "0", "0", "0"));
e.extend([(71, f[0]), (72, f[1]), (73, f[2])]);
}
e.push((0, "SEQEND"));
let r = open(&entities(&e), &points());
let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]);
assert_eq!(drawn_edges(&r), square, "the outline without the diagonal");
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
// With every edge visible, each face is a closed outline.
let e: Vec<(i32, &str)> = e.iter().map(|&(c, v)| (c, v.trim_start_matches('-'))).collect();
let r = open(&entities(&e), &points());
let diagonal = drawn_edges(&r).iter().filter(|e| **e == [(0, 0), (10, 10)]).count();
assert_eq!(diagonal, 2, "the diagonal, once per face");
let faces = leaves(&r.document);
assert_eq!(faces.len(), 2);
assert!(faces.iter().all(|f| f.path_data().is_some_and(|p| p.subpaths.iter().all(|s| s.closed))));
}
#[test]
fn polygon_meshes_draw_their_m_and_n_lines_from_above() {
// Rows of 3 vertices: N runs along x, M along y.
let grid = |flags: &'static str, m: &'static str, n: &'static str, rows: &[&'static str]| {
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, flags), (71, m), (72, n)];
for y in rows {
for x in ["0", "10", "20"] {
e.extend(vertex("64", x, y, "7"));
}
}
e.push((0, "SEQEND"));
e
};
let edges = |e: &[(i32, &str)]| drawn_edges(&open(&entities(e), &points()));
let rows = vec![[(0, 0), (10, 0)], [(10, 0), (20, 0)], [(0, 10), (10, 10)], [(10, 10), (20, 10)]];
let cols = vec![[(0, 0), (0, 10)], [(10, 0), (10, 10)], [(20, 0), (20, 10)]];
let open_grid = sorted([rows.clone(), cols.clone()].concat());
assert_eq!(edges(&grid("16", "2", "3", &["0", "10"])), open_grid);
// Closed in N (32): each row joins its last vertex to its first.
let wrap = vec![[(20, 0), (0, 0)], [(20, 10), (0, 10)]];
assert_eq!(edges(&grid("48", "2", "3", &["0", "10"])), sorted([rows, cols, wrap].concat()));
// Closed in M (1): each column joins its last vertex to its first.
let tall = edges(&grid("17", "3", "3", &["0", "10", "20"]));
for e in [[(0, 0), (0, 20)], [(10, 0), (10, 20)], [(20, 0), (20, 20)]] {
assert_eq!(tall.iter().filter(|x| **x == e).count(), 1, "{e:?} in {tall:?}");
}
// A smoothed mesh draws its surface (73 by 74 vertices), not the frame before it, even when
// the frame (3 by 2) has as many vertices.
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "20"), (71, "3"), (72, "2"), (73, "2"), (74, "3"), (75, "6")];
for (x, y) in [("-50", "-50"), ("50", "-50"), ("-50", "0"), ("50", "0"), ("-50", "50"), ("50", "50")] {
e.extend(vertex("80", x, y, "0"));
}
e.extend_from_slice(&grid("16", "2", "3", &["0", "10"])[5..]);
assert_eq!(edges(&e), open_grid);
// When the surface counts (2 by 4) don't fit, the frame's (3 by 2) don't describe the surface
// vertices either: the mesh is left out with a warning.
let i = e.iter().position(|t| *t == (74, "3")).unwrap_or_else(|| panic!("no group 74 in {e:?}"));
e[i] = (74, "4");
let r = open(&entities(&e), &points());
assert!(leaves(&r.document).is_empty());
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
// Vertices that don't fill the grid: the mesh is left out with a warning.
let r = open(&entities(&grid("16", "2", "4", &["0", "10"])), &points());
assert!(leaves(&r.document).is_empty());
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
}
#[test]
fn three_d_faces_leave_out_their_hidden_edges() {
let edges = |hidden: &'static str| {
let mut e: Vec<(i32, &str)> = vec![(0, "3DFACE"), (70, hidden)];
e.extend([(10, "0"), (20, "0"), (11, "10"), (21, "0"), (12, "10"), (22, "10"), (13, "0"), (23, "10")]);
drawn_edges(&open(&entities(&e), &points()))
};
let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]);
assert_eq!(edges("0"), square);
// Bit 0 hides the edge from the first corner, bit 2 the one from the third.
assert_eq!(edges("1"), sorted(vec![[(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]));
assert_eq!(edges("5"), sorted(vec![[(10, 0), (10, 10)], [(0, 10), (0, 0)]]));
}
#[test]
fn nurbs_splines_stay_within_a_hundredth() {
// A rational quadratic circle of radius 100: nine weighted control points.
+85
View File
@@ -0,0 +1,85 @@
//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer, come in as the DXF
//! does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD
//! on aarch64.
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, Unit};
use vectorcraft_geom::{Rect, shapes};
use super::*;
use crate::{DxfOptions, DxfVersion};
/// A drawing in millimetres on a layer named `Walls`: a red rectangle and a blue ellipse.
fn dxf() -> Vec<u8> {
let mut d = Document::new(200.0, 100.0);
let layer = d.add_layer(Some("Walls"));
let stroke = |c| Appearance::basic(Paint::None, Paint::solid(c), 1.0);
let rect = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), stroke(Color::rgb(1.0, 0.0, 0.0)));
let oval = Node::path(d.alloc_id(), shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), stroke(Color::rgb(0.0, 0.0, 1.0)));
for n in [rect, oval] {
d.insert(Some(layer), usize::MAX, n).unwrap();
}
let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() };
crate::export(&d, &o).unwrap().bytes
}
fn dwg() -> Vec<u8> {
crate::dwg::allow_in_process();
craft_dwg::dxf_to_dwg_as(&dxf(), "AC1018").unwrap()
}
/// A layer's name, and each of its objects' bounds (to 0.01 pt) and stroke color.
type LayerArt = (Option<String>, Vec<([i64; 4], Option<[u8; 4]>)>);
/// Each layer holding art.
fn art(doc: &Document) -> Vec<LayerArt> {
let r = |v: f64| (v * 100.0).round() as i64;
doc.layers
.iter()
.filter_map(|layer| {
let objects: Vec<_> = layer
.children()?
.iter()
.map(|n| {
let b = n.geometric_bounds().unwrap();
let stroke = match n.appearance.stroke().map(|s| &s.paint) {
Some(Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)),
_ => None,
};
([r(b.x0), r(b.y0), r(b.x1), r(b.y1)], stroke)
})
.collect();
(!objects.is_empty()).then(|| (layer.name.clone(), objects))
})
.collect()
}
#[test]
fn a_dwg_drawing_comes_in_as_its_dxf_does() {
let (dxf, dwg) = (dxf(), dwg());
assert!(crate::is_dwg(&dwg) && !crate::is_dwg(&dxf));
let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() };
let want = art(&import(&dxf, &o).unwrap().document);
assert_eq!(want.len(), 1, "{want:?}");
assert_eq!(want[0].0.as_deref(), Some("Walls"));
assert_eq!(want[0].1.len(), 2, "{want:?}");
assert_eq!(art(&import(&dwg, &o).unwrap().document), want);
let i = info(&dwg).unwrap();
assert_eq!((i.units.as_str(), i.unit, i.layouts.first().map(String::as_str)), ("Millimeters", Unit::Millimeters, Some("Model")));
assert!(i.layers.iter().any(|l| l == "Walls"), "{i:?}");
}
#[test]
fn a_damaged_dwg_is_an_error_that_names_dwg() {
let mut cut = dwg();
cut.truncate(cut.len() / 3);
let e = import(&cut, &ImportOptions::default()).unwrap_err();
assert!(e.contains("DWG"), "{e}");
assert!(info(&cut).is_err());
// An R1.x or R2.x drawing is refused without reading it.
for old in [&b"AC1.50\x00\x00\x00\x00"[..], b"AC2.10\x00\x00\x00\x00", b"MC0.0\x00\x00\x00\x00"] {
let e = import(old, &ImportOptions::default()).unwrap_err();
assert!(e.contains("version can't be read") && e.contains("DXF"), "{e}");
}
}
+14 -1
View File
@@ -5,7 +5,8 @@
//! layer (hidden ones switched off, locked ones locked, non-printing ones not plotted), paths
//! become polylines (straight segments) or cubic splines (curves), fills their outlines and solid
//! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG
//! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per
//! or JPEG files the caller writes next to the drawing; with [`DxfOptions::group_blocks`] groups
//! become blocks placed by INSERT entities. Coordinates are y-up, in drawing units: `scale` units per
//! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`].
//! [`export_drawings`] writes one such drawing for each of several regions, applying the live
//! effects once for all of them.
@@ -14,15 +15,21 @@
//! clipping) is approximated or left out, and each such loss comes back as a warning.
//!
//! [`import()`] reads a DXF drawing (ASCII or binary, any version) into a document: see [`import`].
//! It reads a DWG drawing too, converted to DXF by [`dwg`].
//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`].
//!
//! - `aci`: the 256-colour index palette and the nearest index of a colour.
//! - The ASCII file around those entities is written by `craft_dxf::drawing`.
//! - `scene`: the document walk that turns objects into entities.
//! - `import`: the reader, entities to art, blocks to symbols.
//! - `dwg`: DWG drawings converted to DXF by craft-dwg, in a child process on desktop builds.
//! - `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;
// Temporary until storytold/craft-libs#5381 merges and the craft-libs pin moves past it.
mod blocks_compat;
pub mod dwg;
#[cfg(test)]
mod expansion_test;
pub mod hpgl;
@@ -33,6 +40,7 @@ use vectorcraft_doc::{Document, Unit};
use vectorcraft_geom::Rect;
pub use aci::{aci_rgb, nearest_aci};
pub use dwg::is_dwg;
pub use import::{DxfInfo, ImportOptions, Imported, import, info, is_dxf};
/// How deep symbols, blocks and brush art may nest in one another (deeper art is left out).
@@ -311,6 +319,10 @@ pub struct DxfOptions {
pub alter_paths: bool,
/// Type is written as glyph outlines (always with [`Preserve::Appearance`]).
pub outline_text: bool,
/// Always Export Group as Block Reference: each group is written as a block definition of its
/// contents, placed by an INSERT entity on the group's layer (groups inside it are blocks
/// placed inside that block). Off: a group's contents are written as plain entities.
pub group_blocks: bool,
/// The drawing's origin is this region's bottom-left corner (document space).
pub region: Rect,
/// Leave out objects entirely outside `region` (one drawing per artboard).
@@ -331,6 +343,7 @@ impl Default for DxfOptions {
preserve: Preserve::default(),
alter_paths: false,
outline_text: false,
group_blocks: false,
region: Rect::ZERO,
crop: false,
}
+51 -13
View File
@@ -2,7 +2,8 @@
//! order. Fills are their outlines then solid hatches (the outlines alone in R12 or with
//! hatches left out), placed images are linked image files unless left out, strokes
//! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or
//! filled outlines where the look needs them.
//! filled outlines where the look needs them. With [`DxfOptions::group_blocks`] each group is a
//! block, placed by an INSERT.
use std::collections::HashMap;
@@ -14,6 +15,8 @@ use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2};
use crate::aci::nearest_aci;
use crate::{CAP_HEIGHT, ColorDepth, DxfImage, DxfOptions, DxfOutput, MAX_NEST, Preserve, RasterFormat};
// Block and the INSERT writer come from craft-libs#5381 once it merges; see `blocks_compat`.
use crate::blocks_compat::Block;
use craft_dxf::drawing::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, STANDARD_STYLE, fixed};
/// Curves are flattened to within this distance (points) where DXF needs straight segments
@@ -503,8 +506,13 @@ pub(crate) struct Scene<'a> {
to_dxf: Affine,
/// Drawing units per point.
k: f64,
/// The entities written so far.
/// The entities written so far: those of model space, or of the group block being written.
e: Codes,
/// The owner of the entities in `e`: model space, or the group block's record.
owner: Handle,
/// Group blocks written so far ([`DxfOptions::group_blocks`]), each after the blocks it inserts.
blocks: Vec<Block>,
block_names: Names,
next: u32,
layers: Vec<Layer>,
layer_names: Names,
@@ -544,6 +552,9 @@ impl<'a> Scene<'a> {
to_dxf: Affine::new([k, 0.0, 0.0, -k, -r.x0 * k, r.y1 * k]),
k,
e: Codes::new(o.version.into()),
owner: fixed::MODEL_RECORD,
blocks: vec![],
block_names: Names::with(&["*Model_Space", "*Paper_Space"]),
next: fixed::FIRST_FREE,
layers: vec![],
layer_names: Names::with(&["0", "Defpoints"]),
@@ -593,7 +604,12 @@ impl<'a> Scene<'a> {
metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters),
next: self.next,
};
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings, setting_notes: self.setting_notes }
DxfOutput {
bytes: crate::blocks_compat::write(drawing, &self.blocks).into_bytes(),
images: self.files,
warnings: self.warnings,
setting_notes: self.setting_notes,
}
}
/// Note `w`, once, about something of the document that the drawing leaves out or that reaches
@@ -660,6 +676,7 @@ impl<'a> Scene<'a> {
self.children(children, *clip);
(self.layer, self.flags) = outer;
}
NodeKind::Group { children, clip } if self.o.group_blocks => self.group_block(n, children, *clip),
NodeKind::Group { children, clip } => self.children(children, *clip),
NodeKind::Path { path, rule, guide, .. } => {
if !*guide {
@@ -754,6 +771,27 @@ impl<'a> Scene<'a> {
}
}
/// Group `n` as a block of its children's entities and an INSERT that places it on the current
/// layer ([`DxfOptions::group_blocks`]). The block's base point is the drawing's origin, so its
/// entities keep their coordinates. A group that writes no entity writes no block.
fn group_block(&mut self, n: &Node, children: &[std::sync::Arc<Node>], clip: bool) {
let (record, begin, end, insert) = (self.handle(), self.handle(), self.handle(), self.handle());
let outer = std::mem::replace(&mut self.e, Codes::new(self.o.version.into()));
let owner = std::mem::replace(&mut self.owner, record);
self.children(children, clip);
let entities = std::mem::replace(&mut self.e, outer).into_string();
self.owner = owner;
if entities.is_empty() {
return;
}
let long = self.o.version.r2000();
let base = symbol_name(n.name.as_deref().unwrap_or_default(), long);
let base = if base.is_empty() { symbol_name("Group", long) } else { base };
let name = self.block_names.unique(&base, if long { 255 } else { 31 });
crate::blocks_compat::insert(&mut self.e, insert, self.owner, &self.layer, &name);
self.blocks.push(Block { name, record, begin, end, entities });
}
/// Warn about what DXF can't hold in `n`'s look.
fn note_losses(&mut self, n: &Node) {
if n.blend != vectorcraft_color::BlendMode::Normal {
@@ -959,7 +997,7 @@ impl<'a> Scene<'a> {
}
let h = self.handle();
let layer = self.layer.clone();
self.e.entity("HATCH", h, fixed::MODEL_RECORD, &layer, style, "AcDbHatch");
self.e.entity("HATCH", h, self.owner, &layer, style, "AcDbHatch");
self.e.xyz(10, 0.0, 0.0);
self.e.normal();
self.e.raw(2, "SOLID");
@@ -1040,7 +1078,7 @@ impl<'a> Scene<'a> {
let (a, b) = (self.pt(a), self.pt(b));
let layer = self.layer.clone();
let h = self.handle();
self.e.entity("LINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbLine");
self.e.entity("LINE", h, self.owner, &layer, style, "AcDbLine");
self.e.xyz(10, a.x, a.y);
self.e.xyz(11, b.x, b.y);
}
@@ -1058,7 +1096,7 @@ impl<'a> Scene<'a> {
// Bit 128: a linetype runs on through the vertices instead of restarting at each one.
let flags = i64::from(closed) | if style.linetype.is_some() { 128 } else { 0 };
if self.o.version.lwpolyline() {
self.e.entity("LWPOLYLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbPolyline");
self.e.entity("LWPOLYLINE", h, self.owner, &layer, style, "AcDbPolyline");
self.e.int(90, pts.len() as i64);
self.e.int(70, flags);
if let Some(w) = width {
@@ -1072,7 +1110,7 @@ impl<'a> Scene<'a> {
}
return;
}
self.e.entity("POLYLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDb2dPolyline");
self.e.entity("POLYLINE", h, self.owner, &layer, style, "AcDb2dPolyline");
self.e.int(66, 1);
self.e.xyz(10, 0.0, 0.0);
self.e.int(70, flags);
@@ -1134,7 +1172,7 @@ impl<'a> Scene<'a> {
let layer = self.layer.clone();
let h = self.handle();
if sub.closed {
self.e.entity("CIRCLE", h, fixed::MODEL_RECORD, &layer, style, "AcDbCircle");
self.e.entity("CIRCLE", h, self.owner, &layer, style, "AcDbCircle");
self.e.xyz(10, centre.x, centre.y);
self.e.num(40, radius);
self.e.normal();
@@ -1150,7 +1188,7 @@ impl<'a> Scene<'a> {
if !on_ccw_arc(a0, a1, am) {
std::mem::swap(&mut a0, &mut a1);
}
self.e.entity("ARC", h, fixed::MODEL_RECORD, &layer, style, "AcDbCircle");
self.e.entity("ARC", h, self.owner, &layer, style, "AcDbCircle");
self.e.xyz(10, centre.x, centre.y);
self.e.num(40, radius);
self.e.normal();
@@ -1197,7 +1235,7 @@ impl<'a> Scene<'a> {
let layer = self.layer.clone();
let h = self.handle();
self.e.entity("ELLIPSE", h, fixed::MODEL_RECORD, &layer, style, "AcDbEllipse");
self.e.entity("ELLIPSE", h, self.owner, &layer, style, "AcDbEllipse");
self.e.xyz(10, centre.x, centre.y);
self.e.xyz(11, axis.x, axis.y);
self.e.normal();
@@ -1232,7 +1270,7 @@ impl<'a> Scene<'a> {
let ctrl: Vec<Point> = ctrl.iter().map(|p| self.pt(*p)).collect();
let layer = self.layer.clone();
let h = self.handle();
self.e.entity("SPLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbSpline");
self.e.entity("SPLINE", h, self.owner, &layer, style, "AcDbSpline");
self.e.normal();
// Planar (bit 3) and, if the subpath is closed, also closed (bit 0). A geometrically
// closed cut needs the closed flag set so CAM/CAM tools (e.g. VCarve) treat it as a
@@ -1308,7 +1346,7 @@ impl<'a> Scene<'a> {
let p = self.pt(t.xf * origin);
let layer = self.layer.clone();
let h = self.handle();
self.e.entity("TEXT", h, fixed::MODEL_RECORD, &layer, &style, "AcDbText");
self.e.entity("TEXT", h, self.owner, &layer, &style, "AcDbText");
self.e.xyz(10, p.x, p.y);
self.e.num(40, height);
let s: String = s.chars().take(MAX_TEXT).collect();
@@ -1368,7 +1406,7 @@ impl<'a> Scene<'a> {
let def = def.handle;
let layer = self.layer.clone();
let style = EntityStyle { aci: 7, ..EntityStyle::default() };
self.e.entity("IMAGE", handle, fixed::MODEL_RECORD, &layer, &style, "AcDbRasterImage");
self.e.entity("IMAGE", handle, self.owner, &layer, &style, "AcDbRasterImage");
self.e.int(90, 0);
self.e.xyz(10, at.x, at.y);
self.e.xyz(11, u.x, u.y);
+2
View File
@@ -8,6 +8,8 @@ use vectorcraft_geom::{Affine, ParamCurve, PathData, Point, Rect, Shape, shapes}
use crate::*;
mod blocks;
type Pairs = Vec<(i32, String)>;
/// The `(code, value)` pairs of a DXF file.
+125
View File
@@ -0,0 +1,125 @@
//! Always Export Group as Block Reference: groups written as blocks placed by INSERT entities.
use super::*;
/// The user blocks of a drawing (not model or paper space): each its name and the entities
/// between its BLOCK and its ENDBLK.
fn blocks(out: &DxfOutput) -> Vec<(String, Vec<Pairs>)> {
let mut found: Vec<(String, Vec<Pairs>)> = vec![];
let mut open = false;
for o in section(&pairs(&out.bytes), "BLOCKS") {
match kind(&o) {
"BLOCK" => {
found.push((get(&o, 2).unwrap_or_default().to_string(), vec![]));
open = true;
}
"ENDBLK" => open = false,
_ if open => found.last_mut().expect("a block").1.push(o),
_ => {}
}
}
found.retain(|(name, _)| !name.starts_with('*'));
found
}
/// A filled square outside any group; the group `Frame` holding a stroked rectangle and the group
/// `Ring` holding a circle, on a second layer `Parts`.
fn grouped_doc() -> Document {
let mut d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(150.0, 10.0, 170.0, 30.0)), Paint::solid(Color::BLACK), Paint::None, 0.0)]);
let parts = d.add_layer(Some("Parts"));
let rect = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0);
let circle = path(&mut d, shapes::ellipse(Rect::new(40.0, 20.0, 70.0, 50.0)), Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
let mut ring = Node::group(d.alloc_id(), vec![Arc::new(circle)]);
ring.name = Some("Ring".into());
let mut frame = Node::group(d.alloc_id(), vec![Arc::new(rect), Arc::new(ring)]);
frame.name = Some("Frame".into());
d.insert(Some(parts), usize::MAX, frame).unwrap();
d
}
#[test]
fn groups_are_blocks_placed_by_inserts_in_every_version() {
let d = grouped_doc();
for v in DxfVersion::ALL {
let out = export(&d, &DxfOptions { version: v, group_blocks: true, ..opts(&d) }).unwrap();
let top = entities(&out);
let inserts: Vec<&Pairs> = top.iter().filter(|e| kind(e) == "INSERT").collect();
assert_eq!(inserts.len(), 1, "{v:?}: the outer group alone is placed in model space");
// Before 2000, names are capitals, letters, digits and $-_ only.
let long = v >= DxfVersion::R2000;
let (frame, ring, parts, first) = if long { ("Frame", "Ring", "Parts", "Layer 1") } else { ("FRAME", "RING", "PARTS", "LAYER_1") };
assert_eq!((get(inserts[0], 2), get(inserts[0], 8)), (Some(frame), Some(parts)), "{v:?}");
assert!(top.iter().any(|e| kind(e) != "INSERT" && get(e, 8) == Some(first)), "{v:?}: the loose square stays in model space");
let found = blocks(&out);
let names: Vec<&str> = found.iter().map(|b| b.0.as_str()).collect();
assert_eq!(names, [ring, frame], "{v:?}: the inner block comes first");
let (ring_entities, frame_entities) = (&found[0].1, &found[1].1);
assert!(!ring_entities.is_empty() && ring_entities.iter().all(|e| kind(e) != "INSERT"), "{v:?}: the circle is in its group's block");
let nested: Vec<&Pairs> = frame_entities.iter().filter(|e| kind(e) == "INSERT").collect();
assert_eq!(nested.len(), 1, "{v:?}: the inner group is placed inside the outer block");
assert_eq!(get(nested[0], 2), Some(ring), "{v:?}");
assert!(frame_entities.iter().any(|e| kind(e) != "INSERT"), "{v:?}: the rectangle is in the outer block");
if v >= DxfVersion::R13 {
// Each block's entities are owned by its BLOCK_RECORD, and the INSERTs by what holds them.
let records = table(&out, "BLOCK_RECORD");
let record = |name: &str| records.iter().find(|r| get(r, 2) == Some(name)).and_then(|r| get(r, 5).map(str::to_string));
for (name, ents) in &found {
let owner = record(name).unwrap_or_else(|| panic!("{v:?}: no BLOCK_RECORD for {name}"));
// A polyline's vertices and its SEQEND are owned by the polyline.
let owned: Vec<&Pairs> = ents.iter().filter(|e| !matches!(kind(e), "VERTEX" | "SEQEND")).collect();
assert!(!owned.is_empty() && owned.iter().all(|e| get(e, 330) == Some(owner.as_str())), "{v:?}: {name}");
}
assert_eq!(get(inserts[0], 330).map(str::to_string), record("*Model_Space"), "{v:?}: the outer INSERT is in model space");
assert_eq!(get(nested[0], 330).map(str::to_string), record(frame), "{v:?}: the inner INSERT is in the outer block");
}
}
}
#[test]
fn without_the_option_groups_are_written_as_their_contents() {
let d = grouped_doc();
let out = export(&d, &opts(&d)).unwrap();
assert!(blocks(&out).is_empty());
assert!(!kinds(&out).iter().any(|k| k == "INSERT"));
let with = export(&d, &DxfOptions { group_blocks: true, ..opts(&d) }).unwrap();
// The same entities are written, moved into blocks.
let count = |o: &DxfOutput| {
let drawn = |ents: &[Pairs]| ents.iter().filter(|e| kind(e) != "INSERT").count();
drawn(&entities(o)) + blocks(o).iter().map(|b| drawn(&b.1)).sum::<usize>()
};
assert_eq!(count(&out), count(&with));
assert_eq!(header(&pairs(&out.bytes), "$EXTMIN"), header(&pairs(&with.bytes), "$EXTMIN"));
assert_eq!(header(&pairs(&out.bytes), "$EXTMAX"), header(&pairs(&with.bytes), "$EXTMAX"));
}
#[test]
fn blocks_read_back_at_the_place_their_group_was() {
let d = grouped_doc();
let o = ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() };
let plain = import(&export(&d, &opts(&d)).unwrap().bytes, &o).unwrap().document;
let blocked = import(&export(&d, &DxfOptions { group_blocks: true, ..opts(&d) }).unwrap().bytes, &o).unwrap().document;
let names: Vec<&str> = blocked.symbols.iter().map(|s| s.name.as_str()).collect();
assert!(names.contains(&"Frame") && names.contains(&"Ring"), "{names:?}");
let (a, b) = (plain.art_bounds().unwrap(), blocked.art_bounds().unwrap());
assert!(close_to(&[a.x0, a.y0, a.x1, a.y1], &[b.x0, b.y0, b.x1, b.y1], 1e-6), "{a:?} against {b:?}");
}
#[test]
fn a_group_with_nothing_written_is_no_block_and_names_stay_unique() {
let mut d = Document::new(200.0, 100.0);
let layer = d.layers[0].id;
let mut hidden = path(&mut d, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Paint::solid(Color::BLACK), Paint::None, 0.0);
hidden.visible = false;
let empty = Node::group(d.alloc_id(), vec![Arc::new(hidden)]);
d.insert(Some(layer), usize::MAX, empty).unwrap();
for name in [Some("Part"), Some("part"), None, Some("*Model_Space")] {
let p = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), Paint::solid(Color::BLACK), Paint::None, 0.0);
let mut g = Node::group(d.alloc_id(), vec![Arc::new(p)]);
g.name = name.map(str::to_string);
d.insert(Some(layer), usize::MAX, g).unwrap();
}
let out = export(&d, &DxfOptions { group_blocks: true, ..opts(&d) }).unwrap();
let names: Vec<String> = blocks(&out).into_iter().map(|b| b.0).collect();
assert_eq!(names, ["Part", "part_2", "Group", "_Model_Space"], "the hidden-only group writes no block");
assert_eq!(kinds(&out).iter().filter(|k| *k == "INSERT").count(), 4);
}
+5
View File
@@ -197,6 +197,11 @@ mod tests {
assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary");
assert_eq!(Harmony::HighContrast3.id(), "highContrast3");
assert_eq!(parse("square"), None);
// The labels are written here and the ids come from the framework: a few shown labels read
// back as their rules.
for h in [Harmony::LeftComplement, Harmony::Monochromatic, Harmony::Compound2, Harmony::Pentagram] {
assert_eq!(parse(label(h)), Some(h), "{}", label(h));
}
}
#[test]
+1
View File
@@ -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;
+174 -1
View File
@@ -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<usize>, Vec<usize>)> },
/// 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<LiveRectParts> {
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() {
+151 -17
View File
@@ -28,40 +28,48 @@ pub fn resolve_stored_radii(base: &PathData, stored: &[f64], relative: bool) ->
out
}
fn dormant_radius_scale(base: &PathData) -> f64 {
base.length().max(1e-12)
}
/// Turn stored absolute radii into fractions of each corner's maximum, or the other way.
/// Anchors without a cuttable corner use the outline's length (at least 1e-12 document units).
/// Their fractions are not capped at 1.
/// When an anchor edit straightens or bends a corner, [`edit_corner_anchors`] converts its
/// radius between these reference lengths, preserving its document length at that edit.
pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) {
if live.radii_relative() == relative {
return;
}
let was_relative = live.radii_relative();
let base = match live {
LiveShape::Rectangle { w, h, .. } => shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)),
LiveShape::Polygon { .. } => live.polygon_outline(),
LiveShape::Polygon { .. } | LiveShape::Star { .. } => live.polygon_outline(),
LiveShape::Path { base, .. } => base.clone(),
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return,
};
let corners = path_corners(&base);
let dormant_scale = dormant_radius_scale(&base);
let radii: &mut [f64] = match live {
LiveShape::Rectangle { radii, .. } => radii,
LiveShape::Polygon { radii, .. } => radii,
LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } => radii,
LiveShape::Path { radii, .. } => radii,
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return,
};
for c in corners {
if let Some(r) = radii.get(c.index) {
let max = c.max_radius();
radii[c.index] = if relative {
if max > 1e-12 && !was_relative { (*r / max).clamp(0.0, 1.0) } else { *r }
} else if was_relative {
(*r).clamp(0.0, 1.0) * max
} else {
*r
};
for (index, r) in radii.iter_mut().enumerate() {
let corner = corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &corners[i]);
let max = corner.map_or(dormant_scale, Corner::max_radius);
if relative {
if max > 0.0 {
*r = if corner.is_some() { (*r / max).clamp(0.0, 1.0) } else { (*r / max).max(0.0) };
}
} else {
*r = if corner.is_some() { (*r).clamp(0.0, 1.0) } else { (*r).max(0.0) } * max;
}
}
match live {
LiveShape::Rectangle { radii_relative: rel, .. }
| LiveShape::Polygon { radii_relative: rel, .. }
| LiveShape::Star { radii_relative: rel, .. }
| LiveShape::Path { radii_relative: rel, .. } => {
*rel = relative;
}
@@ -99,7 +107,7 @@ impl<'a> LiveCorners<'a> {
let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = l.folded() else { return None };
(Cow::Owned(shapes::rectangle(Rect::new(0.0, 0.0, w, h))), xf, radii.to_vec(), kinds.to_vec(), radii_relative)
}
Some(l @ LiveShape::Polygon { radii, kinds, radii_relative, .. }) => {
Some(l @ (LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. })) => {
(Cow::Owned(l.polygon_outline()), Affine::IDENTITY, radii.clone(), kinds.clone(), *radii_relative)
}
Some(LiveShape::Path { base, radii, kinds, radii_relative }) => {
@@ -142,7 +150,8 @@ impl<'a> LiveCorners<'a> {
}
/// The radius corner `index` is stored at: document lengths, or a fraction in 0..1 when
/// [`LiveCorners::radii_relative`].
/// [`LiveCorners::radii_relative`]. Dormant anchors use the reference length documented in
/// [`convert_radii_relative`], and their fractions can exceed 1.
pub fn radius(&self, index: usize) -> f64 {
self.radii.get(index).copied().unwrap_or(0.0)
}
@@ -205,8 +214,8 @@ impl<'a> LiveCorners<'a> {
/// Set `radius` (document units; negative: 0) and/or `kind` on the `corners` (anchor indices of
/// the uncut outline, see [`LiveCorners`]) of a path and its live shape, then cut the path again.
/// A path that isn't a live shape keeps its uncut outline as a [`LiveShape::Path`], which is a
/// plain path again once no corner is cut. Ellipses and lines have no corners: they stay as they
/// are.
/// plain path again once no radius or nondefault corner kind is stored. A straight anchor keeps
/// its stored radius. Ellipses and lines have no corners: they stay as they are.
pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corners: &BTreeSet<usize>, radius: Option<f64>, kind: Option<CornerKind>) {
fn edit(
base: &PathData,
@@ -258,6 +267,14 @@ pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corne
edit(&outline, relative, radii, kinds, corners, radius, kind);
trim_vec_radii(radii, kinds);
}
LiveShape::Star { r1, r2, points, xf, radii, kinds, .. } => {
let outline = shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf);
let n = 2 * *points as usize;
radii.resize(n, 0.0);
kinds.resize(n, CornerKind::Round);
edit(&outline, relative, radii, kinds, corners, radius, kind);
trim_vec_radii(radii, kinds);
}
LiveShape::Path { base, radii, kinds, .. } => {
let n = base.anchor_count();
radii.resize(n, 0.0);
@@ -277,6 +294,81 @@ pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corne
}
}
/// Convert relative `radii` (fractions, one per anchor of the outline) after the outline changed
/// from `before` to `after`: a corner that straightened keeps its document length as a fraction of
/// `after`'s length, and a corner that bent again takes that length back as a fraction of its new
/// maximum. Other radii are left as they are.
pub fn rebase_relative_radii(before: &PathData, after: &PathData, radii: &mut [f64]) {
let (old_corners, new_corners) = (path_corners(before), path_corners(after));
let (old_dormant_scale, new_dormant_scale) = (dormant_radius_scale(before), dormant_radius_scale(after));
for (index, r) in radii.iter_mut().enumerate() {
let old = old_corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &old_corners[i]);
let new = new_corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &new_corners[i]);
match (old, new) {
(Some(c), None) => *r = (*r).clamp(0.0, 1.0) * c.max_radius() / new_dormant_scale,
(None, Some(c)) => *r = (*r * old_dormant_scale / c.max_radius()).clamp(0.0, 1.0),
_ => {}
}
}
}
/// Edit the anchors of the uncut outline that `anchors` (of the path as drawn) come from, while the
/// path keeps its Live Corners: `edit` gets the outline in document space and those of its anchors,
/// and the path is cut again with the same radii and kinds. A live rectangle or polygon becomes a
/// [`LiveShape::Path`] with that outline. [`LiveCorners::sources`] before and after the edit map
/// the anchors as drawn to the corners they come from.
/// Returns `None`, leaving the path unchanged, when the path has no live shape or
/// no corner with a radius, or is a rectangle sheared or scaled unevenly.
pub fn edit_corner_anchors(
path: &mut PathData,
live: &mut Option<Box<LiveShape>>,
anchors: &BTreeSet<AnchorRef>,
edit: impl FnOnce(&mut PathData, &BTreeSet<AnchorRef>),
) -> Option<()> {
live.as_ref()?;
if let Some(LiveShape::Rectangle { xf, .. }) = live.as_deref() {
let [a, b, c, d, _, _] = xf.as_coeffs();
let scale = (a * a + b * b).max(c * c + d * d).max(1e-12);
if ((a * a + b * b) - (c * c + d * d)).abs() > 1e-9 * scale || (a * c + b * d).abs() > 1e-9 * scale {
return None;
}
}
let (mut base, moved, mut radii, kinds, relative) = {
let lc = LiveCorners::new(path, live.as_deref())?;
// The stored radii decide, not the drawn ones: a corner the edit straightened draws no
// arc but keeps its radius, and rounds again when a later edit bends it.
if !lc.radii.iter().any(|r| *r > 0.0) {
return None;
}
let moved: BTreeSet<usize> = anchors.iter().filter_map(|(si, ai)| lc.sources.get(*si)?.get(*ai).copied()).collect();
if moved.is_empty() {
return None;
}
let mut radii = lc.radii.clone();
radii.resize(lc.base.anchor_count(), 0.0);
(lc.base.transformed(lc.xf), moved, radii, lc.kinds.clone(), lc.relative)
};
let mut on_base = BTreeSet::new();
let mut k = 0;
for (si, sp) in base.subpaths.iter().enumerate() {
for ai in 0..sp.anchors.len() {
if moved.contains(&k) {
on_base.insert((si, ai));
}
k += 1;
}
}
let before = relative.then(|| base.clone());
edit(&mut base, &on_base);
if let Some(before) = before {
rebase_relative_radii(&before, &base, &mut radii);
}
let l = LiveShape::Path { base, radii, kinds, radii_relative: relative };
*path = l.to_path();
*live = Some(Box::new(l));
Some(())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -363,6 +455,48 @@ mod tests {
assert!(!p.transform(Affine::translate((5.0, 0.0))), "a move needs no new cuts");
}
/// Moving the anchor of the only rounded corner into a straight line and back keeps its
/// stored radius, so the corner is rounded again.
#[test]
fn a_straightened_corner_rounds_again_when_it_bends_back() {
let pen = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], false));
let (mut path, mut live) = (pen.clone(), None);
set_corners(&mut path, &mut live, &set(&[1]), Some(10.0), None);
let corner = LiveCorners::new(&path, live.as_deref()).unwrap().anchors_of(&set(&[1]));
let move_corner = |path: &mut PathData, live: &mut Option<Box<LiveShape>>, to: Point| {
let sel = LiveCorners::new(path, live.as_deref()).unwrap().anchors_of(&set(&[1]));
let sel = if sel.is_empty() { anchors(&[1]) } else { sel };
edit_corner_anchors(path, live, &sel, |base, on_base| {
for &(si, ai) in on_base {
if let Some(a) = base.anchor_mut(si, ai) {
(a.p, a.h_in, a.h_out) = (to, to, to);
}
}
})
};
assert_eq!(corner.len(), 2, "the corner is cut");
// Straight: the corner has nothing to cut.
assert!(move_corner(&mut path, &mut live, Point::new(50.0, 40.0)).is_some());
assert!(matches!(live.as_deref(), Some(LiveShape::Path { radii, .. }) if radii.get(1) == Some(&10.0)));
assert_eq!(LiveCorners::new(&path, live.as_deref()).unwrap().drawn_radius(1), 0.0, "the straight corner draws no arc");
// Bent again: the stored radius cuts it again.
assert!(move_corner(&mut path, &mut live, Point::new(100.0, 0.0)).is_some(), "the straightened corner stays live");
let c = LiveCorners::new(&path, live.as_deref()).unwrap();
assert!((c.drawn_radius(1) - 10.0).abs() < 1e-6, "the corner keeps its radius: {live:?}");
for relative in [true, false] {
assert!(move_corner(&mut path, &mut live, Point::new(50.0, 40.0)).is_some());
assert_eq!(LiveCorners::new(&path, live.as_deref()).unwrap().drawn_radius(1), 0.0);
let l = live.as_deref_mut().unwrap();
convert_radii_relative(l, relative);
assert_eq!(l.radii_relative(), relative);
path = l.to_path();
assert!(move_corner(&mut path, &mut live, Point::new(100.0, 0.0)).is_some());
let c = LiveCorners::new(&path, live.as_deref()).unwrap();
assert!((c.drawn_radius(1) - 10.0).abs() < 1e-6, "the corner keeps its radius after changing modes: {live:?}");
}
}
#[test]
fn relative_radii_scale_with_rectangle_size() {
let l = LiveShape::Rectangle {
+12
View File
@@ -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<u64> = 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<Vec<u8>>);
@@ -10,6 +21,7 @@ pub type DecodedImage = (image::DynamicImage, Option<Vec<u8>>);
/// 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<DecodedImage, craft_image_codecs::CodecError> {
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,
+55 -14
View File
@@ -318,7 +318,7 @@ impl Document {
/// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as
/// [`Document::index_path`] finds it.
pub fn node(&self, id: NodeId) -> Option<&Node> {
if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) {
if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id).or_else(|| cached.added_node_in(&self.layers, id))) {
crate::id_index::note_path_lookup();
return Some(n);
}
@@ -365,10 +365,21 @@ impl Document {
Some(None) => return self.walk_index_path(id),
_ => {}
}
let stale = cached.contains_key(&id);
// An id the table doesn't have, at the path an earlier walk found for it, while the node
// there still has the id.
if !stale
&& let Some(p) = cached.added(&id)
&& self.node_at(&p).is_some_and(|n| n.id == id)
{
return Some(p);
}
// A stale path (the tree changed) or an id the cache doesn't have (deleted or added
// since): walk, and rebuild now and then.
let found = self.walk_index_path(id);
let stale = cached.contains_key(&id);
if !stale && let Some(p) = &found {
cached.note_added(id, p);
}
if (stale || found.is_some()) && self.index.missed() {
self.index.rebuild(&self.layers);
}
@@ -425,23 +436,37 @@ impl Document {
// Cached paths that still check out ([`id_index`]); the rest take one walk. For a good
// share of the document, one walk is quicker than checking each cached path.
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
want.retain(|id| match cache.get(id) {
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
want.retain(|id| match self.cached_path(&cache, *id) {
Some(p) => {
out.insert(*id, p);
false
}
_ => true,
None => true,
});
}
if !want.is_empty() {
crate::id_index::note_tree_walk();
let mut rest = HashMap::with_capacity(want.len());
walk(&self.layers, &want, &mut Vec::new(), &mut rest);
// The cache keeps the paths of found ids it doesn't have, for the next lookup.
if let Some(cache) = self.index.get().filter(|_| rest.len() <= crate::id_index::ADDED_PATHS) {
rest.iter().for_each(|(id, p)| cache.note_added(*id, p));
}
out.extend(rest);
}
out
}
/// The path the lookup cache `cache` has for `id`, while the node there has the id: the table's
/// path, or for an id the table doesn't have, the path an earlier walk found ([`id_index`]).
fn cached_path(&self, cache: &crate::id_index::Paths, id: NodeId) -> Option<Vec<usize>> {
let p = match cache.get(&id) {
Some(p) => p?,
None => cache.added(&id)?,
};
self.node_at(&p).is_some_and(|n| n.id == id).then_some(p)
}
/// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike
/// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every
/// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still
@@ -452,7 +477,8 @@ impl Document {
let want: std::collections::HashSet<NodeId, std::hash::BuildHasherDefault<crate::id_index::IdHasher>> = ids.into_iter().collect();
// As in `index_paths`, one walk is quicker than checking the cached paths of a good share
// of the document.
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
let cache = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len());
if let Some(cache) = &cache {
let mut paths = Vec::with_capacity(want.len());
let cached = want.iter().all(|id| match cache.get(id) {
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
@@ -476,6 +502,10 @@ impl Document {
out.push(n);
}
});
// Found ids the table doesn't have count toward a rebuild for later ordered lookups.
if cache.is_some_and(|cache| out.iter().any(|n| !cache.contains_key(&n.id))) && self.index.missed() {
self.index.rebuild(&self.layers);
}
}
out
}
@@ -584,10 +614,14 @@ impl Document {
/// Remove a node and return it.
pub fn remove(&mut self, id: NodeId) -> Result<Arc<Node>, DocError> {
let parent = self.parent_of(id);
let path = self.index_path(id).ok_or(DocError::NoNode(id))?;
let idx = *path.last().ok_or(DocError::NoNode(id))?;
let ch = self.children_mut(parent)?;
self.remove_at(id, &path)
}
/// Remove the node at `path`, the index path [`Document::index_path`] gave for `id`, and return it.
fn remove_at(&mut self, id: NodeId, path: &[usize]) -> Result<Arc<Node>, DocError> {
let (&idx, up) = path.split_last().ok_or(DocError::NoNode(id))?;
let ch = self.children_at(up).ok_or(DocError::NoNode(id))?;
if idx >= ch.len() {
return Err(DocError::NoNode(id));
}
@@ -602,10 +636,11 @@ impl Document {
{
return Err(DocError::Invalid("cannot move an object into itself".into()));
}
if let Some(n) = self.node(id) {
let path = self.index_path(id).ok_or(DocError::NoNode(id))?;
if let Some(n) = self.node_at(&path) {
self.check_ruler_guide_place(n, parent)?;
}
let n = self.remove(id)?;
let n = self.remove_at(id, &path)?;
let ch = self.children_mut(parent)?;
let i = Node::insert_index(ch, index, &n);
ch.insert(i, n);
@@ -623,9 +658,15 @@ impl Document {
/// Position of `id` within its parent: (parent, index, sibling count).
pub fn position(&self, id: NodeId) -> Option<(Option<NodeId>, usize, usize)> {
let parent = self.parent_of(id);
let idx = *self.index_path(id)?.last()?;
let n = self.children(parent)?.len();
let path = self.index_path(id)?;
let (&idx, up) = path.split_last()?;
let (parent, n) = match up {
[] => (None, self.layers.len()),
_ => {
let parent = self.node_at(up)?;
(Some(parent.id), parent.children()?.len())
}
};
Some((parent, idx, n))
}
+46
View File
@@ -239,6 +239,52 @@ impl Document {
round_json_paths(brushes, &round);
}
}
/// Make every live star a plain path of the outline it draws, for a save that versions before
/// live stars read: in the art of the layers, symbols, graph designs, pattern swatches and the
/// pattern definition that pattern editing's Cancel puts back (opacity-mask art included), and
/// in the brush definitions.
pub fn live_stars_to_paths(&mut self) {
let is_star = |n: &Node| matches!(n.live_shape(), Some(LiveShape::Star { .. }));
let mut plain = |n: &mut Node| {
if let NodeKind::Path { live, .. } = &mut n.kind
&& matches!(live.as_deref(), Some(LiveShape::Star { .. }))
{
*live = None;
}
};
let roots = self
.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
for root in roots {
edit_branches_where(root, &is_star, &mut plain);
}
if let Some(brushes) = self.unknown.get_mut("brushes") {
json_stars_to_paths(brushes);
}
}
}
/// Take `live` off every serialized path object (`type: "path"`) in `v` whose live shape is a
/// star.
fn json_stars_to_paths(v: &mut serde_json::Value) {
use serde_json::Value;
match v {
Value::Object(o) => {
if o.get("type").and_then(Value::as_str) == Some("path")
&& o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star")
{
o.remove("live");
}
o.values_mut().for_each(json_stars_to_paths);
}
Value::Array(a) => a.iter_mut().for_each(json_stars_to_paths),
_ => {}
}
}
/// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds,
+10
View File
@@ -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
}
}
+15 -3
View File
@@ -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<HitOptions> {
#[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<Hi
Some(if outline { HitOptions { outline: true, ..opt } } else { opt })
}
#[cfg(test)]
thread_local! {
/// How many objects' ancestries [`path_options`] went down on this thread.
static PATHS_CHECKED: std::cell::Cell<usize> = 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<NodeId>) -> Vec<NodeId> {
+57
View File
@@ -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<usize>| {
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::<Vec<_>>()
};
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]
+48 -4
View File
@@ -4,10 +4,15 @@
//! The tree is edited in many places through public fields, so the cache can't be kept in step
//! with it. It is checked instead: a cached path is used only while the node at that path still
//! has the id (a check as deep as the tree). A path that no longer checks out rebuilds the cache,
//! and an id the cache doesn't have (added since, or removed) is looked up by walking, as before.
//! and an id the cache doesn't have (added since, or removed) is looked up by walking.
//! An id that appears more than once (a damaged file) is never cached, so lookups keep returning
//! its first place in tree order.
//!
//! The path a walk finds for an id the table doesn't have is kept beside the table, shared by every
//! document that reads it, and checked the same way before it is used. Documents that each start
//! from the same copy and add the same object (every preview of a drag starts from the document as
//! it was at the press) then find that object without walking the tree.
//!
//! [`crate::Document::remove_many`] keeps the cache and notes the nodes it removes, so the cache
//! places each node after a removed sibling one lower and finds no path for a removed node or one
//! inside it. Once the removed nodes are half the cache's entries, the cache is let go. The first
@@ -16,8 +21,10 @@
//! The one case a cached lookup can answer differently from a walk: a second node with an
//! existing id put in the tree *after* the cache was built, earlier in tree order than the first.
//! The lookup then returns the original node (also one with that id) instead of the new one. The
//! app never makes such a node (paste and duplicate give new ids, undo restores whole trees);
//! duplicated ids come from damaged files, which are cached afresh when opened.
//! same holds for an id the table doesn't have: once a walk in one document has found it, a copy
//! that holds a second node with that id earlier in tree order gets the node at the path the walk
//! found. The app never makes such a node (paste and duplicate give new ids, undo restores whole
//! trees); duplicated ids come from damaged files, which are cached afresh when opened.
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
@@ -65,8 +72,15 @@ type Gaps = HashMap<u32, Vec<u32>>;
pub(crate) struct Paths {
table: Arc<Table>,
gaps: Arc<Gaps>,
/// The index paths that walks found for ids the table doesn't have, at most [`ADDED_PATHS`] of
/// them. Every document that reads the table reads them too, and checks a path against its own
/// tree before using it.
added: Arc<RwLock<IdMap<Vec<usize>>>>,
}
/// The most paths [`Paths`] keeps for ids its table doesn't have; one more lets the kept ones go.
pub(crate) const ADDED_PATHS: usize = 4096;
/// Where each node was when the cache was built: its parent's entry (`u32::MAX` for a top-level
/// layer) and its index among its siblings. One flat table, so building it allocates nothing per
/// node.
@@ -152,6 +166,36 @@ impl Paths {
Err(k) => Some(i - k as u32),
}
}
/// The index path a walk found for `id`, an id the table doesn't have ([`Paths::note_added`]);
/// the caller checks that the node there has the id.
pub(crate) fn added(&self, id: &NodeId) -> Option<Vec<usize>> {
let path = self.added.read().ok()?.get(id)?.clone();
note_path_copy();
Some(path)
}
/// The node with `id` in `layers` at the path [`Paths::added`] has for it, found without copying
/// the path: `None` when there is none or the node there does not have the id.
pub(crate) fn added_node_in<'a>(&self, layers: &'a [Arc<Node>], id: NodeId) -> Option<&'a Node> {
let added = self.added.read().ok()?;
let (first, rest) = added.get(&id)?.split_first()?;
let mut node: &Node = layers.get(*first)?;
for &i in rest {
node = node.children()?.get(i)?;
}
(node.id == id).then_some(node)
}
/// Keep `path`, which a walk found for `id`, when the table doesn't have `id`. Past
/// [`ADDED_PATHS`] ids, the kept paths are let go first.
pub(crate) fn note_added(&self, id: NodeId, path: &[usize]) {
if self.table.ids.contains_key(&id) {
return;
}
let Ok(mut added) = self.added.write() else { return };
if added.len() >= ADDED_PATHS && !added.contains_key(&id) {
added.clear();
}
added.insert(id, path.to_vec());
}
}
/// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out)
@@ -297,7 +341,7 @@ impl IdIndex {
note_tree_walk();
let mut table = Table::default();
walk(layers, u32::MAX, &mut table);
let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default() });
let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default(), added: Arc::default() });
if let Ok(mut g) = self.0.write() {
*g = Some(out.clone());
}
+3 -2
View File
@@ -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;
@@ -102,7 +103,7 @@ pub use appearance::{
};
pub use assets::ExportAsset;
pub use compound_shape::ShapeMode;
pub use corners::LiveCorners;
pub use corners::{LiveCorners, edit_corner_anchors, rebase_relative_radii};
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
pub use graph::{
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows,
@@ -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;
+90 -19
View File
@@ -46,11 +46,32 @@ pub enum LiveShape {
#[serde(default, skip_serializing_if = "is_false")]
radii_relative: bool,
},
/// A star drawn with the Star tool or `shape.star`: its point count and radii stay editable.
Star {
/// Outer radius: centre to each tip.
r1: f64,
/// Inner radius: centre to each point between two tips.
r2: f64,
/// 2–1000, as [`LiveShape::set_points`] gives it; a file's count is clamped when read.
#[serde(deserialize_with = "de_points")]
points: u32,
/// Maps the star (centred on the origin, first tip straight up) into the document.
xf: Affine,
/// Corner radii in document units, by vertex from the first tip clockwise, tips and inner
/// points alternating (none: sharp).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
radii: Vec<f64>,
/// Corner kinds, in the same order (none: round).
#[serde(default, skip_serializing_if = "all_round")]
kinds: Vec<CornerKind>,
#[serde(default, skip_serializing_if = "is_false")]
radii_relative: bool,
},
Line {
a: Point,
b: Point,
},
/// Any other path whose corners Live Corners cut (a star, a pen path): it keeps its uncut
/// Any other path whose corners Live Corners cut (a pen path, a star saved as a path): it keeps its uncut
/// outline so the corners stay editable. Without a cut corner it is a plain path again.
Path {
/// The path with its corners uncut, in the document.
@@ -74,9 +95,10 @@ fn is_false(b: &bool) -> bool {
impl LiveShape {
pub fn radii_relative(&self) -> bool {
match self {
LiveShape::Rectangle { radii_relative, .. } | LiveShape::Polygon { radii_relative, .. } | LiveShape::Path { radii_relative, .. } => {
*radii_relative
}
LiveShape::Rectangle { radii_relative, .. }
| LiveShape::Polygon { radii_relative, .. }
| LiveShape::Star { radii_relative, .. }
| LiveShape::Path { radii_relative, .. } => *radii_relative,
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => false,
}
}
@@ -86,6 +108,7 @@ impl LiveShape {
LiveShape::Rectangle { .. } => "Rectangle",
LiveShape::Ellipse { .. } => "Ellipse",
LiveShape::Polygon { .. } => "Polygon",
LiveShape::Star { .. } => "Star",
LiveShape::Line { .. } => "Line",
LiveShape::Path { .. } => "Path",
}
@@ -100,7 +123,7 @@ impl LiveShape {
shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), radii, *kinds).transformed(*xf)
}
LiveShape::Ellipse { w, h, pie, xf } => shapes::ellipse_pie(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1).transformed(*xf),
LiveShape::Polygon { radii, kinds, radii_relative, .. } => {
LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. } => {
let outline = self.polygon_outline();
let radii = crate::corners::resolve_stored_radii(&outline, radii, *radii_relative);
cut_corners(&outline, &radii, kinds).0
@@ -112,10 +135,12 @@ impl LiveShape {
}
}
}
/// A polygon's outline with its corners uncut, in the document (empty for other shapes).
/// A polygon's or star's outline with its corners uncut, in the document (empty for other
/// shapes).
pub fn polygon_outline(&self) -> PathData {
match self {
LiveShape::Polygon { radius, sides, xf, .. } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf),
LiveShape::Star { r1, r2, points, xf, .. } => shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf),
_ => PathData::default(),
}
}
@@ -123,16 +148,38 @@ impl LiveShape {
/// the corners past the old last one are sharp.
pub fn set_sides(&mut self, n: u64) {
let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return };
let old = *sides as usize;
*sides = n.clamp(3, 1000) as u32;
fn spread<T: Copy + PartialEq + Default>(v: &mut Vec<T>, n: usize) {
match v.first().copied() {
Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n],
Some(_) => v.resize(n, T::default()),
None => {}
}
spread(radii, old, *sides as usize);
spread(kinds, old, *sides as usize);
}
/// A star's point count. None for other shapes.
pub fn star_points(&self) -> Option<u32> {
let LiveShape::Star { points, .. } = self else { return None };
Some(*points)
}
/// Give a star `n` points (2–1000). Its corners keep the radius and kind they shared; else the
/// corners past the old last one are sharp.
pub fn set_points(&mut self, n: u64) {
let LiveShape::Star { points, radii, kinds, .. } = self else { return };
let old = 2 * *points as usize;
*points = n.clamp(2, 1000) as u32;
spread(radii, old, 2 * *points as usize);
spread(kinds, old, 2 * *points as usize);
}
/// A star's ratio: its inner radius over its outer radius (0 when the outer radius is 0). None
/// for other shapes.
pub fn star_ratio(&self) -> Option<f64> {
let LiveShape::Star { r1, r2, .. } = self else { return None };
Some(if *r1 > 0.0 { *r2 / *r1 } else { 0.0 })
}
/// Give a star the ratio `ratio` (0 to 1, see [`LiveShape::star_ratio`]), keeping its outer
/// radius. Nothing changes for other shapes or a ratio outside 0 to 1.
pub fn set_star_ratio(&mut self, ratio: f64) {
let LiveShape::Star { r1, r2, .. } = self else { return };
if ratio.is_finite() && (0.0..=1.0).contains(&ratio) {
*r2 = *r1 * ratio;
}
spread(radii, *sides as usize);
spread(kinds, *sides as usize);
}
/// A polygon's radius in the document, centre to vertex: its own radius by the mean scale of
/// `xf` (exact while its sides are equal). None for other shapes.
@@ -151,7 +198,9 @@ impl LiveShape {
/// ellipse drawn level reads 0°, as does a polygon drawn with its first vertex straight up. None for
/// other shapes.
pub fn shape_angle(&self) -> Option<f64> {
let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. }) = self else { return None };
let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. }) = self else {
return None;
};
// No −0° or 360° from rounding: a shape drawn level reads 0°.
let a = (-self.angle_deg()).rem_euclid(360.0);
Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 })
@@ -168,7 +217,7 @@ impl LiveShape {
let angle = angle.rem_euclid(360.0);
let (xf, local) = match self {
LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)),
LiveShape::Polygon { xf, .. } => (xf, Point::ZERO),
LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => (xf, Point::ZERO),
LiveShape::Line { .. } | LiveShape::Path { .. } => return,
};
let center = *xf * local;
@@ -274,7 +323,7 @@ impl LiveShape {
*xf = a * *xf;
false
}
LiveShape::Polygon { xf, radii, radii_relative, .. } => {
LiveShape::Polygon { xf, radii, radii_relative, .. } | LiveShape::Star { xf, radii, radii_relative, .. } => {
*xf = a * *xf;
scale_radii(radii, a, *radii_relative)
}
@@ -326,7 +375,7 @@ impl LiveShape {
let relative = self.radii_relative();
let radii: &mut [f64] = match self {
LiveShape::Rectangle { radii, .. } => radii,
LiveShape::Polygon { radii, .. } | LiveShape::Path { radii, .. } => radii,
LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } | LiveShape::Path { radii, .. } => radii,
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return false,
};
if relative || !radii.iter().any(|r| *r > 0.0) || k <= 1e-12 {
@@ -338,7 +387,7 @@ impl LiveShape {
/// Rotation angle of the live shape in degrees, clockwise on the page (y points down).
pub fn angle_deg(&self) -> f64 {
match self {
LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => {
LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => {
let c = xf.as_coeffs();
c[1].atan2(c[0]).to_degrees()
}
@@ -358,6 +407,28 @@ fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
u32::deserialize(d).map(|n| n.clamp(3, 1000))
}
/// A star's point count read from a file, clamped as the commands clamp it (see [`de_sides`]).
fn de_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
u32::deserialize(d).map(|n| n.clamp(2, 1000))
}
/// Give a corner list for `old` corners `n` entries: one value all `old` corners shared fills it;
/// otherwise entries past its end are the default (sharp, round) and entries past `n` go. A list
/// shorter than `old` holds the default for its missing corners, so it is shared only when that
/// default is; entries of a longer list past `old` name no corner and go first. An empty list
/// stays empty.
fn spread<T: Copy + PartialEq + Default>(v: &mut Vec<T>, old: usize, n: usize) {
v.truncate(old);
if !v.is_empty() && v.len() < old {
v.resize(old, T::default());
}
match v.first().copied() {
Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n],
Some(_) => v.resize(n, T::default()),
None => {}
}
}
/// Whether `a` only moves (no rotation, scale, shear or reflection).
pub(super) fn moves_only(a: Affine) -> bool {
let [a0, a1, a2, a3, _, _] = a.as_coeffs();
+71
View File
@@ -158,6 +158,77 @@ fn a_polygon_from_a_file_has_3_to_1000_sides() {
assert_eq!(huge.polygon_outline().anchor_count(), 1000);
}
/// A live star saves and reads back as it was, and one read from a file has 2 to 1000 points.
#[test]
fn a_star_round_trips_and_its_file_count_is_clamped() {
let star = LiveShape::Star {
r1: 40.0,
r2: 20.0,
points: 7,
xf: Affine::translate((10.0, 20.0)),
radii: vec![2.0; 14],
kinds: vec![],
radii_relative: false,
};
let text = serde_json::to_string(&star).unwrap();
assert_eq!(serde_json::from_str::<LiveShape>(&text).unwrap(), star);
assert_eq!(star.label(), "Star");
let read = |points: u64| {
let json = serde_json::json!({"shape": "star", "r1": 10.0, "r2": 5.0, "points": points, "xf": [1, 0, 0, 1, 0, 0]});
serde_json::from_value::<LiveShape>(json).unwrap().star_points().unwrap()
};
assert_eq!([0, 2, 5, 1000, 4_000_000_000].map(read), [2, 2, 5, 1000, 1000]);
// Points and ratio change; the outer radius stays.
let mut s = star.clone();
s.set_points(9);
s.set_star_ratio(0.25);
assert!(matches!(&s, LiveShape::Star { r1, r2, points: 9, radii, .. } if *r1 == 40.0 && *r2 == 10.0 && *radii == vec![2.0; 18]));
assert_eq!(s.polygon_outline().anchor_count(), 18);
}
/// A corner list shorter than the corners holds sharp corners past its end, so a new point or
/// side count does not give those corners the first corner's radius.
#[test]
fn a_short_corner_list_keeps_its_missing_corners_sharp() {
let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false };
star.set_points(6);
let mut want = vec![0.0; 12];
want[0] = 2.0;
assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want), "{star:?}");
let mut polygon = LiveShape::Polygon { radius: 40.0, sides: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false };
polygon.set_sides(6);
let mut want = vec![0.0; 6];
want[0] = 2.0;
assert!(matches!(&polygon, LiveShape::Polygon { radii, .. } if *radii == want), "{polygon:?}");
}
/// A corner list longer than the corners drops its entries past the old last corner, so the
/// corners a new point count adds are sharp and keep the default kind.
#[test]
fn a_long_corner_list_drops_its_entries_past_the_corners() {
let mut radii = vec![0.0; 12];
radii[0] = 2.0;
radii[10] = 7.0;
radii[11] = 7.0;
let mut kinds = vec![CornerKind::Round; 12];
kinds[0] = CornerKind::Chamfer;
kinds[10] = CornerKind::Chamfer;
kinds[11] = CornerKind::Chamfer;
let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii, kinds, radii_relative: false };
star.set_points(6);
let mut want_radii = vec![0.0; 12];
want_radii[0] = 2.0;
let mut want_kinds = vec![CornerKind::Round; 12];
want_kinds[0] = CornerKind::Chamfer;
assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want_radii), "{star:?}");
assert!(matches!(&star, LiveShape::Star { kinds, .. } if *kinds == want_kinds), "{star:?}");
// A complete list that all corners share still fills the new corners.
let mut star =
LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![3.0; 10], kinds: vec![], radii_relative: false };
star.set_points(6);
assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == vec![3.0; 12]), "{star:?}");
}
#[test]
fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() {
let close = |a: f64, b: f64| (a - b).abs() < 1e-9;
+1 -1
View File
@@ -78,7 +78,7 @@ pub struct Selection {
}
/// See [`Selection::symbol_part`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SymbolPart {
/// The symbol instance.
pub instance: NodeId,
+22
View File
@@ -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]
+86
View File
@@ -608,3 +608,89 @@ fn node_lookups_copy_no_index_path() {
agree(&d, &ids[..200], "after remove_many");
agree(&d, &nested, "nested");
}
/// Copies of one document that each add the same object, as the previews of a drag do from the document at the press,
/// find that object where a walk finds it. The first copy walks the tree once for it and the later copies do not walk,
/// and [`Document::node`] finds it without copying an index path.
/// A copy that adds the object elsewhere, adds an object below it, groups it or deletes it, and the document they
/// were copied from, still find what a walk finds. A copy that adds it twice finds one node with its id, and
/// [`Document::nodes_in_order`] finds both.
#[test]
fn copies_that_add_an_object_find_it_without_walking_again() {
let (mut base, ids) = squares(2_000);
let layer = base.layers[0].id;
let added = base.alloc_id();
let new = || Node::path(added, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art());
base.drop_lookup_cache();
base.node(layer);
let walks = tree_walks();
let mut node_copies = 0;
for copy in 0..20 {
let mut d = base.clone();
d.insert(Some(layer), usize::MAX, new()).unwrap();
let copies = path_copies();
assert!(d.node(added).is_some_and(|n| n.id == added), "copy {copy}");
node_copies += path_copies() - copies;
assert_eq!(d.index_path(added), Some(vec![0, ids.len()]), "copy {copy}");
assert_eq!(d.index_paths([added, ids[5]]).get(&added), Some(&vec![0, ids.len()]), "copy {copy}");
assert_eq!(d.ancestry(added), Some(vec![layer, added]), "copy {copy}");
}
assert_eq!(tree_walks() - walks, 1, "walks of the tree for 20 copies");
assert_eq!(node_copies, 0, "index paths copied by node for 20 copies");
// A copy that adds the object twice: lookups give one node with its id, and nodes_in_order,
// which reads only the table's paths, gives both.
let mut d = base.clone();
d.insert(Some(layer), usize::MAX, new()).unwrap();
d.insert(Some(layer), 3, new()).unwrap();
agree_except(&d, &[added, ids[3], ids[0]], Some(added), "added twice");
assert_eq!(d.nodes_in_order([ids[7], added]).iter().map(|n| n.id).collect::<Vec<_>>(), [added, ids[7], added], "added twice");
let gone = d.index_path(added).unwrap();
assert_eq!(d.remove(added).unwrap().id, added);
assert_eq!(d.walk_index_path(added).filter(|p| *p != gone).map(|_| ()), Some(()), "the other one stays");
assert_eq!(d.layers[0].children().unwrap().len(), ids.len() + 1, "removed one node");
// The object lower in the layer, with another object below it, and the next copy back at the top.
let mut d = base.clone();
d.insert(Some(layer), 10, new()).unwrap();
agree(&d, &[added, ids[9], ids[10]], "added at 10");
let below = square(&mut d);
let below = d.insert(Some(layer), 0, below).unwrap();
agree(&d, &[added, below, ids[9]], "an object below it");
let mut d = base.clone();
d.insert(Some(layer), usize::MAX, new()).unwrap();
agree(&d, &[added], "back at the top");
// Grouped with the object below it, then deleted.
let gid = d.alloc_id();
let members = vec![d.remove(ids[ids.len() - 1]).unwrap(), d.remove(added).unwrap()];
d.insert(Some(layer), usize::MAX, Node::group(gid, members)).unwrap();
assert_eq!(d.index_path(added), Some(vec![0, ids.len() - 1, 1]));
agree(&d, &[added, gid, ids[ids.len() - 1]], "grouped");
d.remove(gid).unwrap();
assert!(d.node(added).is_none() && d.index_path(added).is_none(), "deleted with its group");
agree(&d, &[added, gid], "deleted");
// The document the copies came from has no such object, and a copy that adds it again finds it.
assert!(base.node(added).is_none() && base.index_path(added).is_none() && base.index_paths([added]).is_empty());
let mut d = base.clone();
d.insert(Some(layer), usize::MAX, new()).unwrap();
agree(&d, &[added, ids[0]], "added again");
}
/// Repeated ordered lookups of an added object rebuild the table and then use its cached path.
#[test]
fn ordered_lookups_of_an_added_object_stop_walking() {
let (mut d, _) = squares(2_000);
let layer = d.layers[0].id;
d.drop_lookup_cache();
d.node(layer);
let new = square(&mut d);
let added = d.insert(Some(layer), usize::MAX, new).unwrap();
assert!(d.node(added).is_some_and(|n| n.id == added));
let walks = tree_walks();
for lookup in 0..20 {
assert_eq!(d.nodes_in_order([added]).iter().map(|n| n.id).collect::<Vec<_>>(), [added], "lookup {lookup}");
}
assert!(tree_walks() - walks <= 5, "walks of the tree for 20 ordered lookups");
}
+103 -2
View File
@@ -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<Item = NodeId>) -> Self {
let mut ids: Vec<u64> = 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<Self> {
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<TraceMade> {
self.extras().trace.as_deref().and_then(|t| t.get(TRACE_MADE)).and_then(TraceMade::from_json)
}
/// Records `made` as the objects the trace of this Image Trace object made, when its `trace`
/// settings are an object.
pub fn set_trace_made(&mut self, made: &TraceMade) {
if let Some(t) = self.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(serde_json::Value::as_object_mut) {
t.insert(TRACE_MADE.into(), made.to_json());
}
}
}
#[cfg(test)]
@@ -110,6 +178,39 @@ mod tests {
assert_eq!(g.trace_view(), TraceView::Result);
}
#[test]
fn trace_made_keeps_ranges_and_reads_only_well_formed_ones() {
let ids = [7, 3, 4, 5, 9, 3, u64::MAX].map(crate::NodeId);
let made = TraceMade::of(ids);
assert_eq!(made.to_json(), serde_json::json!([[3, 5], [7, 7], [9, 9], [u64::MAX, u64::MAX]]));
for id in 0..12 {
assert_eq!(made.contains(crate::NodeId(id)), ids.contains(&crate::NodeId(id)), "{id}");
}
assert!(made.contains(crate::NodeId(u64::MAX)));
assert_eq!(TraceMade::from_json(&made.to_json()), Some(made.clone()));
assert_eq!(TraceMade::from_json(&serde_json::json!([])), Some(TraceMade::default()));
for bad in [
serde_json::json!({}),
serde_json::json!([[5, 3]]),
serde_json::json!([[1, 4], [4, 6]]),
serde_json::json!([[6, 7], [1, 2]]),
serde_json::json!([[1]]),
serde_json::json!([[1, 2, 3]]),
serde_json::json!([[-1, 2]]),
serde_json::json!([[1.5, 2]]),
serde_json::json!(["1", "2"]),
] {
assert_eq!(TraceMade::from_json(&bad), None, "{bad}");
}
let mut g = Node::group(crate::NodeId(1), vec![]);
g.set_trace_made(&made);
assert_eq!(g.trace_made(), None, "a group with no trace settings records nothing");
g.extras_mut().trace = Some(Box::new(serde_json::json!({"preset": "Default"})));
assert_eq!(g.trace_made(), None);
g.set_trace_made(&made);
assert_eq!(g.trace_made(), Some(made));
}
#[test]
fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() {
let mut g = Node::group(crate::NodeId(1), vec![]);
+5
View File
@@ -24,6 +24,11 @@ craft-svg = { workspace = true, features = ["tree-render"] }
# The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg).
svgtypes = "0.16"
serde_json = { workspace = true }
# Render Settings › Rendered: the 3D effects' solids drawn as an image with depth and shadow maps.
craft-raster3d = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-raster3d = { workspace = true, features = ["parallel"] }
[dev-dependencies]
vectorcraft-color = { workspace = true }
+183 -21
View File
@@ -43,8 +43,8 @@ pub(crate) fn catalog() -> Vec<EffectInfo> {
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<Option<(DotShape, f64)>> {
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<Self> {
Some(match s.to_ascii_lowercase().as_str() {
@@ -89,6 +106,10 @@ impl DotShape {
/// running along x.
fn path(self, t: f64, s: f64) -> PathData {
let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side)));
// A full-tone dot is the cell itself; Line keeps its overlap along the row.
if t >= 1.0 && self != DotShape::Line {
return square(s);
}
match self {
DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle),
DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse),
@@ -173,13 +194,14 @@ fn curves_area(curves: &[CubicBez]) -> f64 {
curves.iter().map(|c| c.signed_area()).sum()
}
/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`.
/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`, one for each
/// quarter turn or part of one.
fn ellipse_arc(out: &mut Vec<CubicBez>, a: f64, b: f64, t0: f64, t1: f64) {
if t1 <= t0 {
return;
}
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0);
let n = ((t1 - t0) / std::f64::consts::FRAC_PI_2).ceil().max(1.0);
let d = (t1 - t0) / n;
let k = 4.0 / 3.0 * (d / 4.0).tan();
for i in 0..n as usize {
@@ -294,20 +316,27 @@ fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
return four_quadrants(&spot_quadrant(t, h, kind));
}
let mut bp = BezPath::new();
let mut add = |curves: Vec<CubicBez>, first: bool| {
let mut end: Option<Point> = 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<CubicBez>| {
for (k, c) in curves.iter().enumerate() {
if k == 0 {
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
match end {
None => bp.move_to(c.p0),
Some(e) if e.distance(c.p0) < 1e-9 => {}
Some(_) => bp.line_to(c.p0),
}
}
bp.curve_to(c.p1, c.p2, c.p3);
end = Some(c.p3);
}
};
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))));
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)));
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))));
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)));
bp.close_path();
bp
}
@@ -405,27 +434,47 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData {
let i = (x.floor() as usize).min(SIZE_STEPS - 1);
let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0));
let r = lo + (hi - lo) * (x - i as f64);
if matches!(kind, CellKind::Circle | CellKind::Ellipse) {
let (a, b) = if matches!(kind, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) };
if t > 0.0 && a <= 1.0 && b <= 1.0 {
return shapes::ellipse(Rect::new(-a * h, -b * h, a * h, b * h));
}
}
let q1 = mapped(&kind.quadrant(r), |p| Point::new(p.x * h, p.y * h));
PathData::from_bezpath(&four_quadrants(&q1))
}
/// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other
/// three quadrants, counterclockwise.
/// three quadrants, counterclockwise. Quadrants that meet on an axis are joined without an anchor
/// of their own at the join.
fn four_quadrants(q1: &[CubicBez]) -> BezPath {
let mut bp = BezPath::new();
let mut add = |curves: Vec<CubicBez>, first: bool| {
for (k, c) in curves.iter().enumerate() {
let mut end: Option<Point> = 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<CubicBez>| {
for (k, c) in curves.iter().filter(|c| !on_axis(c)).enumerate() {
if k == 0 {
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
match end {
None => bp.move_to(c.p0),
Some(e) if e.distance(c.p0) < 1e-9 => {}
Some(_) => bp.line_to(c.p0),
}
}
bp.curve_to(c.p1, c.p2, c.p3);
end = Some(c.p3);
}
};
add(q1.to_vec(), true);
add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false);
add(mapped(q1, |p| Point::new(-p.x, -p.y)), false);
add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false);
bp.close_path();
add(q1.to_vec());
add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))));
add(mapped(q1, |p| Point::new(-p.x, -p.y)));
add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))));
if end.is_some() {
bp.close_path();
}
bp
}
@@ -525,10 +574,12 @@ impl Halftone {
}
fn from_params(p: &Value) -> Self {
// A named style sets the shape and angle over the stored ones (which hold the defaults).
let styled = style(text(p, "style", "custom")).flatten();
Self {
shape: DotShape::parse(text(p, "shape", "circle")).unwrap_or(DotShape::Circle),
shape: styled.map_or_else(|| DotShape::parse(text(p, "shape", "circle")).unwrap_or(DotShape::Circle), |s| s.0),
frequency: num(p, "frequency", 20.0).clamp(1.0, 300.0),
angle: num(p, "angle", 45.0),
angle: styled.map_or_else(|| num(p, "angle", 45.0), |s| s.1),
mono: !text(p, "mode", "mono").eq_ignore_ascii_case("cmyk"),
color: crate::raster::color_param(p, Color::BLACK),
from_art: flag(p, "fromArt", false),
@@ -731,6 +782,7 @@ mod tests {
use super::*;
use vectorcraft_doc::Effect;
use vectorcraft_geom::Shape;
use vectorcraft_geom::kurbo::PathEl;
/// A black square's samples: `side` points of black from (10, 10), white around it.
fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) {
@@ -765,6 +817,46 @@ mod tests {
assert_eq!(h.color, Color::BLACK);
}
#[test]
fn round_dots_inside_the_cell_have_four_anchors() {
for (shape, tone) in [(DotShape::Circle, 0.5), (DotShape::Ellipse, 0.3)] {
let dot = shape.path(tone, 10.0);
assert_eq!(dot.subpaths.len(), 1, "{shape:?}");
let sp = &dot.subpaths[0];
assert!(sp.closed, "{shape:?}");
assert_eq!(sp.anchors.len(), 4, "{shape:?}: {:?}", sp.anchors);
}
}
/// Dots whose quadrants meet on the axes have no extra anchors at the joins: a Circle dot small
/// enough to stay inside its cell has the anchors of its arcs only, all distinct.
#[test]
fn dot_quadrants_join_without_extra_anchors() {
let dot = DotShape::Circle.path(0.2, 10.0);
let anchors: Vec<Point> = dot.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect();
for (i, a) in anchors.iter().enumerate() {
assert!(anchors[i + 1..].iter().all(|b| a.distance(*b) > 1e-6), "{anchors:?}");
}
for shape in [DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] {
for t in [0.2, 0.6, 0.9] {
for sp in &shape.path(t, 10.0).subpaths {
let n = sp.anchors.len();
for i in 0..n {
let (a, b) = (sp.anchors[i].p, sp.anchors[(i + 1) % n].p);
assert!(n < 2 || a.distance(b) > 1e-6, "{shape:?} at {t}: {:?}", sp.anchors);
}
}
}
}
}
#[test]
fn zero_tone_quadrant_dots_have_empty_paths() {
for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] {
assert!(shape.path(0.0, 10.0).is_empty(), "{shape:?}");
}
}
#[test]
fn values_out_of_range_are_brought_in() {
let h = Halftone::of(&effect(json!({"frequency": 1e308, "angle": "NaN", "shape": 7, "mode": "CMYK", "color": "nope"}))).unwrap();
@@ -801,6 +893,51 @@ mod tests {
fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1))
}
#[test]
fn grid_dots_fill_the_cell_at_full_tone() {
for name in ["gridDots", "gridDotsAngle"] {
let Some(Some((shape, _))) = style(name) else { panic!("{name} is not a style") };
// At 100% the cell's corners are covered, so neighboring cells leave no holes.
assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{name}");
// Below it the corners stay light.
assert!(!covers(shape, 0.9, (0.49, 0.49)), "{name}");
}
}
#[test]
fn full_tone_dots_have_exactly_the_cell_corners() {
let Some(Some((grid_dots, _))) = style("gridDots") else { panic!("gridDots is not a style") };
let corners = [Point::new(-5.0, -5.0), Point::new(5.0, -5.0), Point::new(5.0, 5.0), Point::new(-5.0, 5.0)];
for shape in [grid_dots, DotShape::Ellipse, DotShape::Square, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] {
let dot = shape.path(1.0, 10.0);
assert_eq!(dot.subpaths.len(), 1, "{shape:?}");
let sp = &dot.subpaths[0];
assert!(sp.closed, "{shape:?}");
let anchors: Vec<Point> = sp.anchors.iter().map(|a| a.p).collect();
assert_eq!(anchors.len(), 4, "{shape:?}: {anchors:?}");
for corner in corners {
assert!(anchors.contains(&corner), "{shape:?}: {anchors:?}");
}
}
}
#[test]
fn styles_set_the_shape_and_angle() {
let defaults = crate::effect_info(HALFTONE).unwrap().defaults;
let with = |style: &str| {
let mut p = defaults.clone();
p["style"] = json!(style);
let h = Halftone::of(&effect(p)).unwrap();
(h.shape, h.angle)
};
assert_eq!(with("grid"), (DotShape::Euclidean, 0.0));
assert_eq!(with("gridAngle"), (DotShape::Euclidean, 45.0));
assert_eq!(with("gridDots"), (DotShape::Circle, 0.0));
assert_eq!(with("custom"), (DotShape::Circle, 45.0));
assert_eq!(with("checker"), (DotShape::Circle, 45.0));
assert_eq!((style("GRIDDOTS"), style("custom"), style("checker")), (Some(Some((DotShape::Circle, 0.0))), Some(None), None));
}
#[test]
fn spot_dots_cover_the_tone() {
for shape in [DotShape::Euclidean, DotShape::Elliptical] {
@@ -833,6 +970,31 @@ mod tests {
}
}
#[test]
fn a_dot_inside_its_cell_is_four_curves() {
for shape in [DotShape::Circle, DotShape::Ellipse] {
let bp = shape.path(0.2, 10.0).to_bezpath();
let curves = bp.elements().iter().filter(|el| matches!(el, PathEl::CurveTo(..))).count();
let lines = bp.elements().iter().filter(|el| matches!(el, PathEl::LineTo(..))).count();
assert_eq!((curves, lines), (4, 0), "{shape:?}: {:?}", bp.elements());
}
}
#[test]
fn dot_quadrants_join_without_a_repeated_anchor() {
for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] {
for t in [0.2, 0.45, 0.55, 0.6, 0.85] {
for sp in &shape.path(t, 10.0).subpaths {
let n = sp.anchors.len();
for i in 0..n {
let (a, b) = (sp.anchors[i].p, sp.anchors[(i + 1) % n].p);
assert!(a.distance(b) > 1e-6, "{shape:?} at {t}: {:?}", sp.anchors);
}
}
}
}
}
#[test]
fn euclidean_dots_meet_corner_to_corner_at_half() {
let s = DotShape::Euclidean;
+3 -3
View File
@@ -354,7 +354,7 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
if let Some(m) = crate::addons::halftone::halftone_art(d, n) {
return Some(bake_pieces(d, m));
}
if let Some(m) = crate::revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
if let Some(m) = crate::revolve_art_drawn_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) {
let m = evaluate_container(Some(d), &m).unwrap_or(m);
return Some(bake_pieces(d, m));
}
@@ -871,7 +871,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, &
/// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and
/// effects are dropped. `None` for other kinds of objects.
pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option<Node> {
if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) {
let m = evaluate_container(Some(d), &m).unwrap_or(m);
return Some(bake_pieces(d, m));
}
@@ -963,7 +963,7 @@ pub fn bake_type_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// [`bake_appearance`], or with `outline_strokes` false [`bake_type_appearance`].
fn bake_appearance_as(doc: Option<&Document>, n: &Node, outline_strokes: bool) -> Option<Node> {
if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) {
if let Some(m) = crate::revolve_art_drawn_in(doc, n).or_else(|| crate::solid_art_drawn_in(doc, n)) {
return Some(m);
}
if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) {
+8 -8
View File
@@ -241,29 +241,29 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
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; in the shaded faces 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; with render mode rendered, every light with an intensity above 0 casts shadows in the image), 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|rendered, 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; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made or a later geometry effect reshapes paths but leaves images unchanged; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. 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; in the shaded faces 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; with render mode rendered, every light with an intensity above 0 casts shadows in the image), 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|rendered, quality, resolution and background, 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; in the shaded faces 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; with render mode rendered, every light with an intensity above 0 casts shadows in the image), 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|rendered, quality, resolution and background, 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; in the shaded faces 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; with render mode rendered, every light with an intensity above 0 casts shadows in the image), 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|rendered, quality, resolution and background, as Revolve's; rendered mode checks the paint of every fill and stroke)}. 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,
+10 -6
View File
@@ -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;
@@ -95,14 +96,17 @@ pub use reshape::{
has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_drawn_in, revolve_art_in, revolve_options, validate_revolve,
validate_revolve_in,
};
pub use solids::rendered::{rendered_warning, three_d_bounds_art_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,
BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MATERIAL, MAX_GRAPHICS, MappedGraphic,
MeshGraphics, RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, RenderSettings,
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, render_settings, rendered, renders_image, renders_wireframe, solid_art,
solid_art_drawn_in, 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,
};
+318 -9
View File
@@ -136,6 +136,199 @@ 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<AppearanceItem> {
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`], or for a
/// curved face [`curved_seamed_fill`]; else the outline alone). Each fill covers the face and its
/// seam once. `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<vectorcraft_three_d::Highlight>,
) -> Option<vectorcraft_doc::Node> {
let items = highlight.map(highlight_fills).unwrap_or_default();
if items.is_empty() {
return None;
}
let shape = seamed_fill(path, seam).or_else(|| curved_seamed_fill(path, seam)).unwrap_or_else(|| path.clone());
Some(vectorcraft_doc::Node::path(id, shape, vectorcraft_doc::Appearance { items, ..Default::default() }))
}
/// How far, in points, a curved face's flattened outline may stray from its curves when
/// [`curved_seamed_fill`] tests it.
const HIGHLIGHT_FLATNESS: f64 = 0.05;
/// Curved face `path` and its round seam `seam` wide as one path to fill: the [`footprint`] of the
/// curves themselves, as the face's clip is. `None` unless `path` has curves and its outline,
/// flattened to within [`HIGHLIGHT_FLATNESS`], is a polygon [`seamed_fill`] takes: one closed
/// contour of up to [`SEAMED_FILL_EDGES`] edges that does not fold over itself. Flattening stops
/// once the outline passes that many edges.
fn curved_seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option<vectorcraft_geom::PathData> {
use kurbo::{ParamCurve, ParamCurveExtrema, PathEl, PathSeg, Shape};
let bez = path.to_bezpath();
let elements = bez.elements();
if elements.len() > SEAMED_FILL_EDGES + 2 || !elements.iter().any(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))) {
return None;
}
let segments: Vec<PathSeg> = bez.segments().collect();
for (i, a) in segments.iter().enumerate() {
let b = &segments[(i + 1) % segments.len()];
if matches!((a, b), (PathSeg::Line(_), PathSeg::Line(_))) {
continue;
}
let controls = |s: &PathSeg| match s {
PathSeg::Line(s) => vec![s.p0, s.p1],
PathSeg::Quad(s) => vec![s.p0, s.p1, s.p2],
PathSeg::Cubic(s) => vec![s.p0, s.p1, s.p2, s.p3],
};
let seam = a.end();
let directions: Vec<_> = controls(a)
.into_iter()
.map(|p| p - seam)
.chain(controls(b).into_iter().map(|p| seam - p))
.filter(|v| v.hypot() > 0.0)
.map(|v| v / v.hypot())
.collect();
let separated = directions.iter().any(|a| {
directions.iter().any(|b| {
let axis = *a + *b;
directions.iter().all(|v| axis.dot(*v) > 1e-12)
})
});
if !separated {
return None;
}
}
let mut flat = vectorcraft_geom::BezPath::new();
let mut overflow = false;
let mut last = kurbo::Point::ZERO;
for el in elements {
if overflow {
break;
}
let from = last;
let controls = match el {
PathEl::QuadTo(a, b) => Some([from, *a, *b, *b]),
PathEl::CurveTo(a, b, c) => Some([from, *a, *b, *c]),
_ => None,
};
if let Some(controls) = controls {
let length: f64 = controls.windows(2).map(|pair| pair[0].distance(pair[1])).sum();
if !length.is_finite()
|| length > HIGHLIGHT_FLATNESS * vectorcraft_geom::MAX_FLATTEN_PER_CURVE.powi(2)
|| controls.iter().any(|p| !(p.x.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH && p.y.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH))
{
return None;
}
}
last = match el {
PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => *p,
PathEl::ClosePath => last,
};
let curve = match el {
PathEl::QuadTo(a, b) => Some(PathSeg::Quad(kurbo::QuadBez::new(from, *a, *b))),
PathEl::CurveTo(a, b, c) => Some(PathSeg::Cubic(kurbo::CubicBez::new(from, *a, *b, *c))),
_ => None,
};
// Each curve piece is monotonic in both coordinates before flattening.
let pieces = curve.map_or_else(
|| vec![(from, *el)],
|curve| {
curve
.extrema_ranges()
.into_iter()
.map(|range| {
let piece = curve.subsegment(range);
(piece.start(), piece.as_path_el())
})
.collect()
},
);
for (from, el) in pieces {
if overflow {
break;
}
let start = [PathEl::MoveTo(from)].into_iter().filter(|_| !matches!(el, PathEl::MoveTo(_)));
let mut skip = usize::from(!matches!(el, PathEl::MoveTo(_)));
vectorcraft_geom::flatten(start.chain([el]), HIGHLIGHT_FLATNESS, |e| {
if skip > 0 {
skip -= 1;
} else if flat.elements().len() > SEAMED_FILL_EDGES + 2 {
overflow = true;
} else {
flat.push(e);
}
});
}
}
if overflow {
return None;
}
// Each flattened edge may be HIGHLIGHT_FLATNESS away from its curve.
seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), seam, 2.0 * HIGHLIGHT_FLATNESS)?;
let fill = footprint(&bez, seam);
(fill.bounding_box().is_finite() && fill.area().abs() >= bez.area().abs()).then(|| vectorcraft_geom::PathData::from_bezpath(&fill))
}
/// `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_three_d::Highlight>,
) -> 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.
@@ -179,7 +372,13 @@ const SEAMED_FILL_EDGES: usize = 256;
/// a seam that is not a positive finite width, or a footprint with no finite bounds or less area
/// than the facet.
pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option<vectorcraft_geom::PathData> {
use kurbo::{PathEl, Point, Shape};
seamed_fill_with_clearance(path, seam, 0.0)
}
/// [`seamed_fill`], also `None` when two edges that are not neighbors come within `clearance` of
/// each other.
fn seamed_fill_with_clearance(path: &vectorcraft_geom::PathData, seam: f64, clearance: f64) -> Option<vectorcraft_geom::PathData> {
use kurbo::{Line, ParamCurveNearest, PathEl, Point, Shape};
if !(seam.is_finite() && seam > 0.0) {
return None;
}
@@ -218,6 +417,19 @@ pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Optio
if touch(a, b, c, d) {
return None;
}
if clearance > 0.0 {
let ab = Line::new(a, b);
let cd = Line::new(c, d);
let distance_sq = ab
.nearest(c, 1e-6)
.distance_sq
.min(ab.nearest(d, 1e-6).distance_sq)
.min(cd.nearest(a, 1e-6).distance_sq)
.min(cd.nearest(b, 1e-6).distance_sq);
if distance_sq <= clearance * clearance {
return None;
}
}
}
}
let fill = footprint(&bez, seam);
@@ -231,17 +443,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<vectorcraft_doc::Node>]) -> Option<vectorcraft_doc::Node> {
use std::sync::Arc;
use vectorcraft_doc::{Node, NodeKind};
let facets: Vec<Arc<Node>> = 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::<Option<_>>()?;
let facet = |face: &Arc<Node>| {
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<Arc<Node>> = faces.iter().map(facet).collect::<Option<_>>()?;
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 }))
@@ -609,6 +826,98 @@ mod tests {
}
}
/// A material's highlight over a curved face reaches its seam too, as the face's clip does,
/// wound one way so a nonzero fill screens it once. A curved face that folds over itself keeps
/// its outline alone.
#[test]
fn a_highlight_over_a_curved_face_covers_its_seam() {
use kurbo::Shape;
let circle = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
for path in [circle.clone(), vectorcraft_geom::PathData::from_bezpath(&circle.to_bezpath().reverse_subpaths())] {
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
let Some(shape) = over.path_data() else { panic!("a path") };
let bez = shape.to_bezpath();
assert_ne!(bez.winding(Point::new(5.0, 10.4)), 0, "the seam past the bottom edge");
assert_ne!(bez.winding(Point::new(5.0, 5.0)), 0, "the face");
assert_eq!(bez.winding(Point::new(5.0, 11.0)), 0, "past the seam");
assert!(bez.elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count() >= 2);
}
// A curved face that folds over itself keeps its outline alone, as its own nonzero fill.
let mut folded = vectorcraft_geom::BezPath::new();
folded.move_to((0.0, 0.0));
folded.quad_to((5.0, -1.0), (10.0, 10.0));
folded.line_to((10.0, 0.0));
folded.quad_to((5.0, 1.0), (0.0, 10.0));
folded.close_path();
let folded = vectorcraft_geom::PathData::from_bezpath(&folded);
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &folded, 1.0, Some(highlight)) else { panic!("a highlight") };
assert_eq!(over.path_data(), Some(&folded));
}
/// A curved face whose fold is smaller than the flattening tolerance, so that its flattened
/// outline does not cross itself, still keeps its outline alone, wound either way.
#[test]
fn a_highlight_over_a_fold_smaller_than_flatness_keeps_its_outline() {
let mut folded = vectorcraft_geom::BezPath::new();
folded.move_to((0.0, 0.0));
folded.line_to((10.0, 0.0));
folded.line_to((10.0, 10.0));
folded.line_to((0.0, 10.0));
folded.line_to((0.0, 0.01));
folded.quad_to((5.0, -0.03), (9.0, 0.01));
folded.close_path();
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
for bez in [folded.clone(), folded.reverse_subpaths()] {
let mut flat = vectorcraft_geom::BezPath::new();
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the fold");
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
assert_eq!(over.path_data(), Some(&path));
}
}
/// A face with a collinear cubic that reverses direction keeps its highlight outline.
#[test]
fn a_highlight_over_a_retraced_cubic_keeps_its_outline() {
let mut folded = vectorcraft_geom::BezPath::new();
folded.move_to((0.0, 0.0));
folded.curve_to((-8.0, 0.0), (-4.0, 0.0), (12.0, 0.0));
folded.line_to((12.0, 10.0));
folded.line_to((0.0, 10.0));
folded.close_path();
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
for bez in [folded.clone(), folded.reverse_subpaths()] {
let mut flat = vectorcraft_geom::BezPath::new();
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the reversal");
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
assert_eq!(over.path_data(), Some(&path));
}
}
#[test]
fn a_curved_edge_crossing_its_neighbor_keeps_the_highlight_outline() {
let mut folded = vectorcraft_geom::BezPath::new();
folded.move_to((0.0, 0.0));
folded.line_to((1000.0, 1000.0));
folded.quad_to((500.0, 499.999), (0.0, 0.2));
folded.line_to((-1000.0, 1000.0));
folded.line_to((-1000.0, -1000.0));
folded.close_path();
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
for bez in [folded.clone(), folded.reverse_subpaths()] {
let mut flat = vectorcraft_geom::BezPath::new();
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
assert!(seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0, 2.0 * HIGHLIGHT_FLATNESS).is_some());
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
let over = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)).unwrap();
assert_eq!(over.path_data(), Some(&path));
}
}
/// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the
/// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound
/// either way and in a concave notch. A facet whose footprint would gain or lose area under a
+129 -19
View File
@@ -10,7 +10,7 @@ use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces};
use crate::solids::wireframe::{WireFace, wireframe_params};
use crate::solids::{
Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
Build, Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
};
use crate::util::{flag, num, text};
use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params};
@@ -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<Node>]) -> Option<Node> {
let faces: Vec<Arc<Node>> = run
.iter()
.map(|face| match &face.kind {
NodeKind::Group { children, clip: false } => children.first().cloned(),
_ => Some(face.clone()),
})
.collect::<Option<_>>()?;
let facet = |face: &Arc<Node>| {
let mut facet = face.clone();
while let NodeKind::Group { children, clip: false } = &facet.kind {
facet = children.first()?.clone();
}
Some(facet)
};
let faces: Vec<Arc<Node>> = run.iter().map(facet).collect::<Option<_>>()?;
if faces.is_empty() {
return None;
}
@@ -810,7 +845,7 @@ pub fn revolve_art(n: &Node) -> Option<Node> {
/// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be
/// resolved.
pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art(doc, n, false)
art_reporting(doc, n, false, Build::Vector, &mut None)
}
/// [`expand_revolve_art_in`] without a document.
@@ -819,10 +854,11 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option<Node> {
expand_revolve_art_in(None, n)
}
/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared
/// command and UI remain unchanged.
/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]): in
/// Render Settings › Rendered, the rendered image where it can be made. The shared command and UI
/// remain unchanged.
pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art(doc, n, true)
art_reporting(doc, n, true, Build::Draw, &mut None)
}
/// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on
@@ -881,6 +917,22 @@ fn surface_meshes(
options: Revolve,
(paint, opacity, member): (&Paint, f32, f32),
graphics: bool,
) -> Result<Vec<crate::SolidMesh>, String> {
let material = crate::solids::material::of(&fx.id, &merged_params(&fx.id, &fx.params));
let projection = Some(vectorcraft_three_d::revolve_mesh_projection(b, options));
surface_meshes_of(path, rule, b, fx, options, (paint, opacity, member), graphics)
.map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, projection, ..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<Vec<crate::SolidMesh>, String> {
let color = crate::solids::mesh_color(paint, opacity * member);
let list: Vec<crate::MappedGraphic> = if graphics && fx.id == REVOLVE && options.map_surface {
@@ -922,7 +974,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)
}
@@ -1033,13 +1085,23 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
Ok(out)
}
fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
/// The art [`revolve_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered,
/// the image of the lit surface where it can be made, in place of the shaded faces that
/// [`revolve_art_in`] keeps for bounds, hit testing and snapping.
pub fn revolve_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art_reporting(doc, n, false, Build::Draw, &mut None)
}
/// [`revolve_art_in`], or with `expand` Revolve's Expand Appearance art, built for `build`, with
/// the reason a rendered image can't be made kept in `warning`.
pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option<String>) -> Option<Node> {
let check_only = build == Build::Check;
if !has_revolve(n) {
return None;
}
let n = &*resolve_for(doc, n, "Revolve", false).ok()?;
if is_container(n) {
return group_art(doc, n, expand);
return group_art(doc, n, expand, check_only, warning);
}
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
@@ -1053,7 +1115,43 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let paints = solid_paints(n);
let item = surface_item(&paints)?;
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
if crate::solids::renders_wireframe(fx) {
let p = merged_params(&fx.id, &fx.params);
// Rendered, the surface's image, with the shadows of every light on the surface and on the
// shadow plane; the shaded faces when it can't be made, and for vector measurements.
let image = crate::render_settings(&fx.id, &p).filter(|_| build != Build::Vector).and_then(|settings| {
let result = if crate::solids::rendered::reshapes_paths_only(&n.appearance.effects[index + 1..]) {
Err(crate::solids::rendered::PATHS_ONLY.into())
} else if crate::mapped_graphics(&p).is_empty() && crate::solids::rendered::takes([item], false) {
let b = path.bounds()?;
let (paint, opacity, _) = paint_of(item);
let options = rule_options(fx, rule);
surface_meshes(&path, rule, b, fx, options, (&paint, opacity, 1.0), true).and_then(|meshes| {
let lighting = crate::solids::rendered::lighting(&fx.id, &p);
let lighting = match crate::solids::rendered::plane_settings(&p, &lighting).filter(|_| crate::solids::shadow::casts(opacity)) {
Some(shadow) => {
let mut caster = vectorcraft_three_d::ShadowCaster::new();
let faces = cast_surface(&mut caster, &path, b, options, None)?;
crate::solids::rendered::with_receiver(lighting, &caster, shadow, &[faces])
}
None => lighting,
};
if build == Build::Bounds {
crate::solids::rendered::bounds_art(doc, n.id, &lighting, &meshes, settings)
} else {
crate::solids::rendered::art(doc, n.id, &lighting, &meshes, settings, check_only)
}
})
} else {
Err(crate::solids::rendered::OPAQUE_ONLY.into())
};
crate::solids::rendered::reported(result, warning)
});
if check_only {
return None;
}
if let Some(image) = image {
children.push(image);
} else if crate::solids::renders_wireframe(fx) {
// In wireframe mode the edges of the faces, with no shadow.
children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?);
} else {
@@ -1082,6 +1180,12 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
for (original, item) in originals.into_iter().zip(&items) {
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) {
let fx = item.effects().get(index)?;
if crate::renders_image(fx) {
warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into());
}
if check_only {
continue;
}
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
if crate::solids::renders_wireframe(fx) {
@@ -1234,9 +1338,15 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool {
/// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them,
/// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when
/// the effect is only on the group's own fills or strokes or when its members can't be revolved.
fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
fn group_art(doc: Option<&Document>, n: &Node, expand: bool, check_only: bool, warning: &mut Option<String>) -> Option<Node> {
let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?;
let fx = n.appearance.effects.get(index)?;
if crate::renders_image(fx) {
warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into());
}
if check_only {
return None;
}
let mut shapes = members(n, "").ok()?;
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
let b = union_bounds(&shapes)?;
+1
View File
@@ -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)
}
@@ -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::<usize>();
}
});
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");
}
+185 -55
View File
@@ -41,7 +41,15 @@ pub use vectorcraft_three_d::SurfaceKind;
pub(crate) mod shadow;
pub(crate) mod wireframe;
pub use wireframe::{RENDER, RENDER_MODES, renders_wireframe, three_d_wireframe_in};
pub use wireframe::{
RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, RenderSettings, render_settings, renders_image, renders_wireframe,
three_d_wireframe_in,
};
pub mod rendered;
pub(crate) mod material;
pub use material::MATERIAL;
pub const EXTRUDE: &str = "threeD.extrude";
pub const INFLATE: &str = "threeD.inflate";
@@ -176,6 +184,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 +423,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 +842,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<Facet>, 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<Facet>,
paint: &Paint,
(opacity, blend): (f32, BlendMode),
colored: bool,
faces: bool,
parts: Vec<Vec<Arc<Node>>>,
) -> 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 +876,19 @@ fn surface(n: &Node, facets: Vec<Facet>, 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 +900,7 @@ fn surface(n: &Node, facets: Vec<Facet>, 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 +939,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<Vec<Arc<Node>>>) -> 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 +952,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.
@@ -995,6 +1008,17 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData,
/// fill rule, its shape's scopes and the index of its shape.
type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope], usize);
fn solid_items(shape: &Profile) -> impl Iterator<Item = &AppearanceItem> {
let top_fill = shape.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
shape.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| i)
}
/// The fills and strokes 3D effect `id` draws for `shapes`: every one for Rotate, which draws a
/// plane for each ([`meshes_for`]), and [`solid_items`] for the other effects.
fn drawn_items<'a>(id: &str, shapes: &'a [Profile]) -> Box<dyn Iterator<Item = &'a AppearanceItem> + 'a> {
if is_plane(id) { Box::new(shapes.iter().flat_map(|s| s.items.iter())) } else { Box::new(shapes.iter().flat_map(solid_items)) }
}
/// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes,
/// a group's members from the back up, each with its shape's opacity, the region it paints and its
/// shape's scopes. The solids share the bounds of all their parts (`fallback` when none has any):
@@ -1004,8 +1028,7 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) {
.iter()
.enumerate()
.flat_map(|(member, s)| {
let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(move |(_, i)| {
solid_items(s).map(move |i| {
let (area, rule) = region(&s.path, s.rule, i);
(i, s.opacity, area, rule, s.scopes.as_slice(), member)
})
@@ -2045,12 +2068,57 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it
/// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every
/// surface of the object, and the surfaces.
fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
fn art_for(
doc: Option<&Document>,
n: &Node,
effects: &[Effect],
shapes: &[Profile],
build: Build,
warning: &mut Option<String>,
) -> Option<ShadowAndSurfaces> {
let (fx, later) = effects.split_first()?;
if build == Build::Check && !crate::renders_image(fx) {
return Some((vec![], vec![]));
}
// In wireframe mode the effect draws the edges of the faces it builds, with no shadow.
if wireframe::renders_wireframe(fx) {
return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?));
}
let p = crate::merged_params(&fx.id, &fx.params);
// Rendered, the solids' image, with the shadows of every light on the solids and on the shadow
// plane; the shaded faces when it can't be made, and for vector measurements.
if build != Build::Vector
&& let Some(settings) = wireframe::render_settings(&fx.id, &p)
{
let image = if rendered::reshapes_paths_only(later) {
Err(rendered::PATHS_ONLY.into())
} else if mapped_graphics(&p).is_empty() && rendered::takes(drawn_items(&fx.id, shapes), has_masks(shapes)) {
meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).and_then(|meshes| {
let lighting = rendered::lighting(&fx.id, &p);
let lighting = match cast_shadow_with(&fx.id, &p, shapes, rendered::plane_settings(&p, &lighting))? {
Some((caster, shadow, cast)) => {
let faces: Vec<std::ops::Range<usize>> = cast.iter().map(|c| c.2.clone()).collect();
rendered::with_receiver(lighting, &caster, shadow, &faces)
}
None => lighting,
};
if build == Build::Bounds {
rendered::bounds_art(doc, n.id, &lighting, &meshes, settings)
} else {
rendered::art(doc, n.id, &lighting, &meshes, settings, build == Build::Check)
}
})
} else {
Err(rendered::OPAQUE_ONLY.into())
};
let image = rendered::reported(image, warning);
if build == Build::Check {
return Some((vec![], vec![]));
}
if let Some(image) = image {
return Some((vec![], vec![image]));
}
}
let cast = casts_shadow(&fx.id, &p);
let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?;
// A shadow past the limits draws the source path, as a solid past them does; commands report
@@ -2083,10 +2151,20 @@ pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result<
/// When a member's opacity mask or blending mode applies to its solids ([`masked`]), it applies to
/// the part of the shadow they cast too ([`shadow::scoped_art`]).
fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<Cast<'a>>, String> {
cast_shadow_with(id, p, shapes, shadow::options(p))
}
/// [`cast_shadow`] with the shadow settings `settings` in place of those of `p`.
fn cast_shadow_with<'a>(
id: &str,
p: &Value,
shapes: &'a [Profile],
settings: Option<vectorcraft_three_d::Shadow>,
) -> Result<Option<Cast<'a>>, String> {
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
return Ok(None);
}
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
let (Some(settings), Some(b)) = (settings, union_bounds(shapes)) else { return Ok(None) };
let view = view_options(p);
let mut caster = vectorcraft_three_d::ShadowCaster::new();
// The faces each solid of visible art added, with its member's scopes and its ink (opacity
@@ -2273,8 +2351,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 +2380,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<Facet> {
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<Placed>, Node, &'s [Scope], Vec<Option<PlanarFace>>);
@@ -2368,7 +2454,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 +2478,7 @@ fn surfaces_with(
return None;
}
if graphics_on {
let caps: Vec<Facet> = 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 +2598,8 @@ fn surfaces_with(
.iter()
.enumerate()
.filter_map(|(at, (item, member, _, f, shape))| {
let caps: Vec<Facet> = 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 +2677,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)
})
@@ -2807,21 +2893,48 @@ pub fn solid_art(n: &Node) -> Option<Node> {
/// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be
/// resolved.
pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
solid_art_reporting(doc, n, Build::Vector, &mut None)
}
/// The art [`solid_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered, the
/// image of the lit solids where it can be made ([`rendered`]), in place of the shaded faces that
/// [`solid_art_in`] keeps for bounds, hit testing and snapping.
pub fn solid_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
solid_art_reporting(doc, n, Build::Draw, &mut None)
}
/// What a 3D effect's art is built for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Build {
/// The vector art: the shaded faces and the vector shadow, in every mode but wireframe. No
/// rendered image is made.
Vector,
/// Painted measurement art, with rendered images represented by their rectangles and no pixels.
Bounds,
/// Only whether the rendered image can be made, with the reason in the warning when it can't:
/// no art and no pixels.
Check,
/// The art drawn and exported: the rendered image where it can be made.
Draw,
}
pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option<String>) -> Option<Node> {
if !has_solid(n) {
return None;
}
let n = &*resolve(doc, n, "").ok()?;
if is_container(n) {
return group_solid_art(doc, n);
return group_solid_art(doc, n, build, warning);
}
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
let (sources, paints) = solid_paint_sources(n);
let mut children = vec![];
let remaining: Vec<Effect>;
if let Some((index, fx)) = solid(&n.appearance.effects) {
if let Some((index, _)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
let (shadow, surfaces) =
art_for(doc, n, &n.appearance.effects[index..], &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], build, warning)?;
children.extend(shadow.into_iter().chain(surfaces));
// Later geometry effects act on the projected art as a whole.
remaining = past_effect(&n.appearance.effects, index);
@@ -2835,9 +2948,16 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
// Every item's shadow goes behind every item's art.
let mut shadows = vec![];
for (source, item) in sources.into_iter().zip(&paints) {
if let Some((index, fx)) = solid(item.effects()) {
if let Some((index, _)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(source.unwrap_or(item)));
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
let (shadow, surfaces) = art_for(
doc,
n,
&item.effects()[index..],
&[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }],
build,
warning,
)?;
let later: Vec<Effect> = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect();
let with_later = |mut art: Arc<Node>| {
Arc::make_mut(&mut art).appearance.effects = later.clone();
@@ -2866,11 +2986,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// geometry effects before it reshape the members, those after it bend the result as a whole; the
/// group's own fills and strokes are not drawn. `None` when the effect is only on one of the
/// group's own fills or strokes, or when its members can't become solids.
fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option<Node> {
let (index, fx) = solid(&n.appearance.effects)?;
fn group_solid_art(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option<String>) -> Option<Node> {
let (index, _) = solid(&n.appearance.effects)?;
let mut shapes = members(n, "").ok()?;
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
let (shadow, surfaces) = art_for(doc, n, fx, &shapes)?;
let (shadow, surfaces) = art_for(doc, n, &n.appearance.effects[index..], &shapes, build, warning)?;
let children = shadow.into_iter().chain(surfaces).collect();
let remaining = past_effect(&n.appearance.effects, index);
let mut art = n.clone();
@@ -3176,12 +3296,18 @@ 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<MeshGraphics>,
/// The surface's Roughness and Metallic ([`MATERIAL`]); [`vectorcraft_three_d::Material::DEFAULT`]
/// for the 3D (Classic) effects.
pub material: vectorcraft_three_d::Material,
/// The projection that takes the mesh's points to where the effect draws them on the page;
/// `None` when it is not known.
pub projection: Option<vectorcraft_three_d::MeshProjection>,
}
impl SolidMesh {
/// A mesh painted `color`, with no graphics.
/// A mesh painted `color`, with no graphics, in the default material, with no projection.
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, projection: None }
}
}
@@ -3236,7 +3362,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,19 +3409,20 @@ 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<SolidMesh>, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| {
let mut keep = |out: &mut Vec<SolidMesh>, (mesh, projection): (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, projection, ..part }, limit))
};
if is_plane(&fx.id) {
for s in shapes {
for item in &s.items {
let (paint, opacity, _) = paint_of(item, s.opacity);
let (area, rule) = region(&s.path, s.rule, item);
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?;
keep(&mut out, vectorcraft_three_d::plane_meshed(&area, rule, b, view)?, (&paint, opacity), b)?;
}
}
return Ok(out);
@@ -3332,7 +3459,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
match solid.mesh() {
Ok(mesh) => {
let (paint, opacity, _) = paint_of(item, *member);
keep(&mut out, mesh, (&paint, opacity), bounds)?;
keep(&mut out, (mesh, solid.projection()), (&paint, opacity), bounds)?;
}
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
@@ -3446,3 +3573,6 @@ mod tests_shadow;
#[cfg(test)]
mod tests_revolve_order;
#[cfg(test)]
mod tests_material;
+9 -2
View File
@@ -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<Node> {
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;
+54
View File
@@ -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<Material, String> {
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 }
}
+779
View File
@@ -0,0 +1,779 @@
//! Render Settings › Rendered: the solids of a 3D effect drawn as one image, with a depth buffer,
//! the metallic-roughness shading of every light and the shadows each light casts on the solids,
//! instead of the shaded vector faces. The image lies on the page where the vector faces lie: each
//! mesh point goes through the projection the effect draws its faces with
//! ([`vectorcraft_three_d::MeshProjection`]).
use std::io::Cursor;
use std::sync::Arc;
use craft_raster3d::{Limits, Scene, Vertex, srgb_to_linear, try_encode, try_render_cpu, try_shadow_maps};
use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeId, NodeKind};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_three_d::{Light, MeshProjection};
use super::SolidMesh;
use super::wireframe::RenderSettings;
/// The message a rendered image that can't be made is reported with; the effect then draws its
/// shaded faces.
pub const TOO_LARGE: &str = "The 3D render is too large; showing the shaded faces instead";
/// The message for a solid painted with something other than an opaque solid color in Normal
/// blending, or with graphics; the effect then draws its shaded faces.
pub const OPAQUE_ONLY: &str = "The 3D render shows opaque solid colors only; showing the shaded faces instead";
/// The message for a later geometry effect that reshapes paths but leaves images unchanged.
pub const PATHS_ONLY: &str = "A later effect reshapes the 3D object's paths; showing the shaded faces instead";
/// Do any visible effects reshape paths without also reshaping images in `reshape_leaves`?
pub(crate) fn reshapes_paths_only(effects: &[vectorcraft_doc::Effect]) -> bool {
effects.iter().any(|e| {
e.visible
&& (crate::is_geometry(&e.id) || crate::is_pathfinder(&e.id))
&& e.id != "distort.transform"
&& e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id).is_none()
})
}
/// The message for Revolve on a group or on a fill or stroke, which draws its shaded faces.
pub const OBJECTS_ONLY: &str = "Revolve renders on a single object only; showing the shaded faces instead";
/// Why a visible 3D effect in rendered mode on `n` draws shaded faces instead of an image.
/// Messages are English, to be translated when displayed. `None` when no rendered effect falls back.
pub fn rendered_warning(doc: &vectorcraft_doc::Document, n: &Node) -> Option<String> {
let rendered = |fx: &vectorcraft_doc::Effect| fx.visible && crate::renders_image(fx);
if !n.appearance.effects.iter().any(rendered) && !n.appearance.items.iter().any(|i| i.effects().iter().any(rendered)) {
return None;
}
let mut warning = None;
if crate::has_revolve(n) {
let _ = crate::revolve::art_reporting(Some(doc), n, false, super::Build::Check, &mut warning);
} else {
let _ = super::solid_art_reporting(Some(doc), n, super::Build::Check, &mut warning);
}
warning
}
/// The art of `n`'s 3D effect for painted bounds, with rendered images represented by their page
/// rectangles without pixels. Shaded fallback art and later effects keep their normal bounds.
/// This art is for measurement only; selection and snapping use the vector art instead.
pub fn three_d_bounds_art_in(doc: Option<&vectorcraft_doc::Document>, n: &Node) -> Option<Node> {
crate::revolve::art_reporting(doc, n, false, super::Build::Bounds, &mut None)
.or_else(|| super::solid_art_reporting(doc, n, super::Build::Bounds, &mut None))
}
/// The image rectangle for painted measurements, with the same eligibility and scene limits as
/// the rendered image, without rasterizing or adding an image to the cache.
pub(crate) fn bounds_art(
doc: Option<&vectorcraft_doc::Document>,
id: NodeId,
lighting: &Lighting,
meshes: &[SolidMesh],
settings: RenderSettings,
) -> Result<Option<Arc<Node>>, String> {
art(doc, id, lighting, meshes, settings, true)?;
let m = measure(meshes, lighting, settings, doc.map_or(72.0, |d| d.raster_ppi()), false, &Limits::default())?;
let object = ImageObject {
key: String::new(),
width: m.cols,
height: m.rows,
xf: Affine::new([m.rect.width() / f64::from(m.cols), 0.0, 0.0, m.rect.height() / f64::from(m.rows), m.rect.x0, m.rect.y0]),
link: None,
placement: Default::default(),
pixels: None,
};
Ok(Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object))))))
}
/// The rendered image of `result`, or `None` after a successful check. An error keeps its message
/// in `warning` when no earlier reason is there; the caller then draws its shaded faces.
pub(crate) fn reported(result: Result<Option<Arc<Node>>, String>, warning: &mut Option<String>) -> Option<Arc<Node>> {
match result {
Ok(image) => image,
Err(message) => {
warning.get_or_insert(message);
None
}
}
}
/// The lights a rendered image is shaded with, as the effect's shaded faces are.
#[derive(Clone, Debug, PartialEq)]
pub struct Lighting {
/// The directional lights ([`vectorcraft_three_d::Revolve::active_lights`]).
pub lights: Vec<Light>,
/// Each light's shadow diffusion in points, in the same order as `lights`.
pub diffusion: Vec<f64>,
/// The ambient light, 0 to 2.
pub ambient: f64,
/// Shading on: off, the solids show their paint unlit, as the shaded faces do.
pub shade: bool,
/// Shadows on: each light that lights the art casts shadows on the solids and on
/// [`Lighting::receiver`]. Off, no light casts one.
pub shadows: bool,
/// The part of the shadow plane the shadows fall on, as four corners in mesh space (y up), in
/// order round it ([`receiver`]); `None` without one.
pub receiver: Option<[[f64; 3]; 4]>,
}
impl Lighting {
/// Does light `l` cast shadows in the image: Shading and Shadows are on and it lights the art?
fn casts(&self, l: &Light) -> bool {
self.shade && self.shadows && l.intensity > 0.0
}
}
/// The opacity of the black the shadow plane shows where a shadow falls, as the effect's vector
/// shadow paints it.
const PLANE_SHADOW: f32 = 0.5;
/// How far the shadow plane reaches past the shadows on it, as a share of the solids' largest size,
/// so a soft edge is not cut. VectorCraft's own value.
const PLANE_MARGIN: f64 = 0.05;
/// `lighting` with the part of the shadow plane the shadows of the faces in `faces` of `caster`
/// fall on, with settings `shadow`, for every light that casts one ([`Lighting::casts`]).
pub(crate) fn with_receiver(
mut lighting: Lighting,
caster: &vectorcraft_three_d::ShadowCaster,
shadow: vectorcraft_three_d::Shadow,
faces: &[std::ops::Range<usize>],
) -> Lighting {
let toward: Vec<[f64; 3]> = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.direction()).collect();
lighting.diffusion = lighting
.lights
.iter()
.map(|l| caster.shadow_blur(vectorcraft_three_d::Shadow { softness: l.softness, ..shadow }, faces).unwrap_or(0.0))
.collect();
let softness = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.softness).fold(0.0, f64::max);
let shadow = vectorcraft_three_d::Shadow { softness, ..shadow };
lighting.receiver = caster.receiver(shadow, faces, &toward, PLANE_MARGIN).map(|q| q.map(|[x, y, z]| [x, -y, z]));
lighting
}
/// A rendered image: `cols` × `rows` straight-alpha sRGB RGBA8 pixels covering `rect` on the page,
/// made with `samples` × `samples` samples a pixel.
#[derive(Clone, Debug, PartialEq)]
pub struct Rendered {
pub rect: Rect,
pub cols: u32,
pub rows: u32,
pub samples: u32,
pub pixels: Vec<u8>,
}
/// The margin, as a share of the depth range, the solids' nearest and farthest points keep from the
/// ends of the depth buffer.
const DEPTH_MARGIN: f64 = 0.01;
/// The largest share of the eye's distance a point may lie in front of the projection origin: at it
/// the vector faces stop growing ([`vectorcraft_three_d::MeshProjection::project`]).
const NEAREST: f64 = 0.999;
/// The image of `meshes` lit by `lighting`, with `settings`, at the document's raster effects
/// resolution `doc_ppi` when the settings take it, within `limits`. An error ([`TOO_LARGE`]) when a
/// mesh has no projection or a different one, when a point lies at or behind the eye, when the
/// image has more pixels than `limits` allow even at one sample a pixel, or when the rasterizer
/// refuses the scene. `draft` takes one sample a pixel and draft shadow maps, as Low quality does.
pub fn render(
meshes: &[SolidMesh],
lighting: &Lighting,
settings: RenderSettings,
doc_ppi: f64,
draft: bool,
limits: &Limits,
) -> Result<Rendered, String> {
let too_large = || TOO_LARGE.to_string();
let Measured { projection, rect, z, clip, cols, rows, samples: k, low } = measure(meshes, lighting, settings, doc_ppi, draft, limits)?;
let scale = f64::from(cols * k) / rect.width();
let mut scene = scene(meshes, lighting, projection, z, clip, (cols * k, rows * k), scale).ok_or_else(too_large)?;
scene.ssaa = k;
#[cfg(test)]
RASTERIZATIONS.with(|n| n.set(n.get() + 1));
if scene.lights.iter().any(|l| l.shadow >= 0) {
try_shadow_maps(&mut scene, low, limits).map_err(|_| too_large())?;
}
let (mut image, _) = try_render_cpu(&scene, limits).map_err(|_| too_large())?;
try_encode(&mut image).map_err(|_| too_large())?;
let pixels = image
.data
.iter()
.flat_map(|p| {
let p = if settings.white { [p[0] + 1.0 - p[3], p[1] + 1.0 - p[3], p[2] + 1.0 - p[3], 1.0] } else { *p };
let a = p[3].clamp(0.0, 1.0);
let straight = |c: f32| if a > 0.0 { (c / a).clamp(0.0, 1.0) } else { 0.0 };
[straight(p[0]), straight(p[1]), straight(p[2]), a].map(|c| (c * 255.0).round() as u8)
})
.collect();
Ok(Rendered { rect, cols, rows, samples: k, pixels })
}
#[cfg(test)]
thread_local! {
/// How many rendered images enter the rasterizing path on this thread.
static RASTERIZATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The projection, clip matrix and raster dimensions within the image's sample budget.
struct Measured {
projection: MeshProjection,
rect: Rect,
z: [f64; 2],
clip: [[f32; 4]; 4],
cols: u32,
rows: u32,
samples: u32,
low: bool,
}
/// Measure the image of `meshes` and the shadow plane `lighting` places, and choose its samples,
/// without building a scene or producing pixels.
fn measure(
meshes: &[SolidMesh],
lighting: &Lighting,
settings: RenderSettings,
doc_ppi: f64,
draft: bool,
limits: &Limits,
) -> Result<Measured, String> {
let too_large = || TOO_LARGE.to_string();
let projection = meshes.first().and_then(|m| m.projection).ok_or_else(too_large)?;
if meshes.iter().any(|m| m.projection != Some(projection)) {
return Err(too_large());
}
let (bounds, z) = extent(meshes, receiver(lighting), projection).ok_or_else(too_large)?;
let cell = 72.0 / settings.resolution.unwrap_or(doc_ppi).clamp(1.0, 2400.0);
let (cols, rows) = ((bounds.width() / cell).ceil().max(1.0), (bounds.height() / cell).ceil().max(1.0));
let pixels = cols * rows;
if pixels.is_nan() || pixels > limits.max_pixels as f64 {
return Err(too_large());
}
let (cols, rows) = (cols as u32, rows as u32);
let rect = Rect::new(bounds.x0, bounds.y0, bounds.x0 + f64::from(cols) * cell, bounds.y0 + f64::from(rows) * cell);
let low = draft || settings.quality == 0;
let mut k = if low { 1 } else { settings.samples() };
while k > 1 && pixels * f64::from(k * k) > limits.max_pixels as f64 {
k -= 1;
}
let clip = clip(projection, rect, z).ok_or_else(too_large)?;
Ok(Measured { projection, rect, z, clip, cols, rows, samples: k, low })
}
/// Check scene limits without allocating raster or shadow depth buffers. The counts follow
/// craft-raster3d at 2680a3b3fe464c7afa3d260b33a828fa94e12f6d: lib.rs:178-223,
/// scene.rs:242-278,325-328, raster.rs:245-281,307-385,740-747 and
/// shadow.rs:109-135,262-276,316-356,413-449,500-515,533-538,576-657.
/// Measured solids and the shadow plane lie inside the clip volume, the solids use opaque, visible
/// materials, the plane's two triangles hold no texture and the lights are directional, so each
/// source triangle contributes one bounding box, without clipping or an alpha-discard search. Raster and shadow work have separate budgets, as in the renderer.
fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64, limits: &Limits) -> Result<(), String> {
let m = measure(meshes, lighting, settings, ppi, false, limits)?;
let size = (m.cols * m.samples, m.rows * m.samples);
let s = scene(meshes, lighting, m.projection, m.z, m.clip, size, f64::from(size.0) / m.rect.width()).ok_or(TOO_LARGE)?;
limits.check(s.width, s.height).map_err(|_| TOO_LARGE)?;
if s.indices.len() as u64 / 3 > limits.max_triangles || s.vertices.len() as u64 > limits.max_vertices || s.lights.len() > limits.max_lights {
return Err(TOO_LARGE.into());
}
let transform =
|matrix: &[[f32; 4]], p: [f32; 3], row: usize| matrix[row][0] * p[0] + matrix[row][1] * p[1] + matrix[row][2] * p[2] + matrix[row][3];
let mut work = 0u64;
for tri in s.indices.as_chunks::<3>().0 {
let mut points = [[0.0; 2]; 3];
for (point, &i) in points.iter_mut().zip(tri) {
let p = s.vertices[i as usize].pos;
let c = [0, 1, 2, 3].map(|r| transform(&s.clip, p, r));
// Refuse transforms whose rounding escapes the measured clip volume.
if !c.iter().all(|v| v.is_finite()) || c[3] <= 0.0 || c[2] < 0.0 || c[2] > c[3] {
return Err(TOO_LARGE.into());
}
let iw = 1.0 / c[3];
*point = [(f64::from(c[0] * iw) + 1.0) * 0.5 * f64::from(s.width), (1.0 - f64::from(c[1] * iw)) * 0.5 * f64::from(s.height)];
}
let area = (0..3).map(|i| points[i][0] * points[(i + 1) % 3][1] - points[(i + 1) % 3][0] * points[i][1]).sum::<f64>();
if !area.is_finite() {
return Err(TOO_LARGE.into());
}
if area != 0.0 {
let pixels = bounding_work(points, [s.width, s.height]);
if pixels > 0 {
work = work.saturating_add(pixels + 1);
}
}
if work > limits.max_work {
return Err(TOO_LARGE.into());
}
}
// Shadow maps are made only for the lights that cast shadows, from the triangles that cast them.
let casters: Vec<&[u32; 3]> = s
.indices
.as_chunks::<3>()
.0
.iter()
.filter(|t| s.materials.get(s.vertices[t[0] as usize].material as usize).is_some_and(|m| m.casts_shadows))
.collect();
if casters.is_empty() || s.lights.iter().all(|l| l.shadow < 0) {
return Ok(());
}
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
for v in &s.vertices {
for k in 0..3 {
lo[k] = lo[k].min(f64::from(v.pos[k]));
hi[k] = hi[k].max(f64::from(v.pos[k]));
}
}
let center = [0, 1, 2].map(|k| (lo[k] + hi[k]) * 0.5);
let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() * 0.5 + 1.0;
let kinds: Vec<u32> = s.lights.iter().map(|l| u32::from(l.shadow >= 0)).chain(std::iter::once(0)).collect();
let sizes = craft_raster3d::shadow_sizes(s.width, s.height, m.low, &kinds);
let maps = sizes.iter().flatten().count() as u64;
if maps.saturating_mul(casters.len() as u64) > limits.max_work {
return Err(TOO_LARGE.into());
}
let mut work = 0u64;
for (light, size) in s.lights.iter().zip(sizes) {
let (Some(size), true) = (size, light.shadow >= 0) else { continue };
let dir = light.dir.map(f64::from);
let eye = [0, 1, 2].map(|k| center[k] - dir[k] * radius * 2.0);
let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
let unit = |v: [f64; 3]| v.map(|x| x / dot(v, v).sqrt());
let forward = unit(dir);
let hint = if dir[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] };
let down = unit([0, 1, 2].map(|k| hint[k] - forward[k] * dot(hint, forward)));
let right = unit([
down[1] * forward[2] - down[2] * forward[1],
down[2] * forward[0] - down[0] * forward[2],
down[0] * forward[1] - down[1] * forward[0],
]);
let view = [right, down].map(|row| [row[0] as f32, row[1] as f32, row[2] as f32, (-dot(row, eye)) as f32]);
let focal = (f64::from(size) * 0.5 / radius) as f32;
for tri in &casters {
let points = [0, 1, 2].map(|k| {
let p = s.vertices[tri[k] as usize].pos;
[0, 1].map(|r| f64::from(transform(&view, p, r) * focal + size as f32 * 0.5))
});
let [a, b, c] = points;
let area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
if !area.is_finite() {
return Err(TOO_LARGE.into());
}
let texels = if area.abs() < 1e-12 { 0 } else { bounding_work(points, [size; 2]) };
work = work.saturating_add(texels + 1);
if work > limits.max_work {
return Err(TOO_LARGE.into());
}
}
}
Ok(())
}
/// The pixels inside a triangle's bounding box, clamped to the raster.
fn bounding_work(points: [[f64; 2]; 3], size: [u32; 2]) -> u64 {
[0, 1]
.map(|k| {
let lo = points.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min).floor().clamp(0.0, f64::from(size[k])) as u64;
let hi = points.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max).ceil().clamp(0.0, f64::from(size[k])) as u64;
hi.saturating_sub(lo)
})
.into_iter()
.product()
}
/// The corners of the shadow plane of `lighting`, in mesh space; none without one.
fn receiver(lighting: &Lighting) -> &[[f64; 3]] {
lighting.receiver.as_ref().map_or(&[], |q| q.as_slice())
}
/// The page bounds the points of `meshes` and the shadow plane's corners `plane` project to, and
/// the range of their depths. `None` with no mesh point, a point that isn't finite, or one at or
/// behind the eye.
fn extent(meshes: &[SolidMesh], plane: &[[f64; 3]], projection: MeshProjection) -> Option<(Rect, [f64; 2])> {
let mut bounds: Option<Rect> = None;
let mut z = [f64::INFINITY, f64::NEG_INFINITY];
meshes.iter().flat_map(|m| &m.mesh.positions).next()?;
for p in meshes.iter().flat_map(|m| &m.mesh.positions).chain(plane) {
if !p.iter().all(|v| v.is_finite()) || projection.eye.is_some_and(|e| p[2] >= e * NEAREST) {
return None;
}
let at = projection.project(*p);
let r = Rect::from_points(at, at);
bounds = Some(bounds.map_or(r, |b| b.union(r)));
z = [z[0].min(p[2]), z[1].max(p[2])];
}
bounds.filter(|b| b.width().is_finite() && b.height().is_finite()).map(|b| (b, z))
}
/// The row-major clip matrix that takes a point of the solids' world space (mesh space with y down,
/// about the projection origin) to the image `rect` as [`MeshProjection::project`] places it, with
/// depths `z` kept inside the depth buffer and nearer points deeper in it. `None` when no depth
/// mapping keeps them in order.
fn clip(projection: MeshProjection, rect: Rect, z: [f64; 2]) -> Option<[[f32; 4]; 4]> {
let (rw, rh) = (rect.width(), rect.height());
let a = 2.0 * (projection.origin.x - rect.x0) / rw - 1.0;
let b = 1.0 - 2.0 * (projection.origin.y - rect.y0) / rh;
// w = 1 − z / eye without perspective's eye: 1.
let inv_eye = projection.eye.map_or(0.0, |e| 1.0 / e);
let (z0, z1) = if z[1] > z[0] { (z[0], z[1]) } else { (z[0] - 0.5, z[0] + 0.5) };
let w = |z: f64| 1.0 - z * inv_eye;
// ndc depth (dz · z + d0) / w: the farthest at DEPTH_MARGIN, the nearest at 1 − DEPTH_MARGIN.
// With w positive over [z0, z1] the ndc depth is a linear-fractional function of z, so it rises
// monotonically between those two ends even when dz itself is negative (a near eye).
let (w0, w1) = (w(z0), w(z1));
if !(w0 > 0.0 && w1 > 0.0) {
return None;
}
let (lo, hi) = (DEPTH_MARGIN * w0, (1.0 - DEPTH_MARGIN) * w1);
let dz = (hi - lo) / (z1 - z0);
let d0 = lo - dz * z0;
if !(dz.is_finite() && d0.is_finite() && hi / w1 > lo / w0) {
return None;
}
let m = [[2.0 / rw, 0.0, -a * inv_eye, a], [0.0, -2.0 / rh, -b * inv_eye, b], [0.0, 0.0, dz, d0], [0.0, 0.0, -inv_eye, 1.0]];
let m = m.map(|row| row.map(|v| v as f32));
m.iter().flatten().all(|v| v.is_finite()).then_some(m)
}
/// The scene of `meshes` for an image `size` raster pixels with clip matrix `clip`: every triangle in world
/// space (mesh space with y down, as the page is), opaque ones first, then
/// those of see-through solids from back to front; one material for each mesh; one parallel light,
/// casting shadows, for each of `lighting`'s lights. `scale` is raster pixels per point, including
/// the samples per image pixel.
fn scene(
meshes: &[SolidMesh],
lighting: &Lighting,
projection: MeshProjection,
z: [f64; 2],
clip: [[f32; 4]; 4],
size: (u32, u32),
scale: f64,
) -> Option<Scene> {
let eye = projection.eye.unwrap_or(z[1] + 1.0);
let mut vertices = vec![];
let mut opaque: Vec<[u32; 3]> = vec![];
let mut clear: Vec<([u32; 3], f64)> = vec![];
let mut materials = vec![];
for (index, m) in meshes.iter().enumerate() {
let [r, g, b, alpha] = m.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 });
materials.push(craft_raster3d::Material {
base: [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), 1.0],
metallic: m.material.metallic() as f32,
roughness: m.material.roughness() as f32,
opacity: alpha,
double_sided: true,
unlit: !lighting.shade,
casts_shadows: true,
..Default::default()
});
let base = vertices.len() as u32;
let mesh = &m.mesh;
for (i, p) in mesh.positions.iter().enumerate() {
let n = mesh.normals.get(i).copied().unwrap_or([0.0, 0.0, 1.0]);
vertices.push(Vertex {
pos: [p[0] as f32, -p[1] as f32, p[2] as f32],
normal: [n[0] as f32, -n[1] as f32, n[2] as f32],
uv: mesh.uvs.get(i).map_or([0.0; 2], |uv| [uv[0] as f32, uv[1] as f32]),
tangent: [1.0, 0.0, 0.0, 1.0],
material: index as u32,
});
}
for t in &mesh.triangles {
if t.iter().any(|&i| i as usize >= mesh.positions.len()) {
return None;
}
let tri = t.map(|i| base + i);
if alpha >= 1.0 {
opaque.push(tri);
} else {
let depth = t.iter().map(|&i| mesh.positions[i as usize][2]).sum::<f64>() / 3.0;
clear.push((tri, depth));
}
}
}
clear.sort_by(|a, b| a.1.total_cmp(&b.1));
// The shadow plane: drawn only where a shadow falls on it, black at the vector shadow's
// opacity, behind every surface, so first in the see-through range.
let mut plane = vec![];
if let Some(q) = lighting.receiver.filter(|_| lighting.shade && lighting.shadows) {
let edge = |a: [f64; 3], b: [f64; 3]| [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let (e1, e2) = (edge(q[0], q[1]), edge(q[0], q[3]));
let n = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
if len.is_finite() && len > 0.0 {
let material = materials.len() as u32;
materials.push(craft_raster3d::Material {
base: [0.0, 0.0, 0.0, 1.0],
opacity: PLANE_SHADOW,
double_sided: true,
shadows_only: true,
receives_shadows: true,
casts_shadows: false,
..Default::default()
});
let base = vertices.len() as u32;
for p in q {
vertices.push(Vertex {
pos: [p[0] as f32, -p[1] as f32, p[2] as f32],
normal: [(n[0] / len) as f32, (-n[1] / len) as f32, (n[2] / len) as f32],
uv: [0.0; 2],
tangent: [1.0, 0.0, 0.0, 1.0],
material,
});
}
plane = vec![[base, base + 1, base + 2], [base, base + 2, base + 3]];
}
}
// Later meshes paint over earlier ones in the shaded faces. Submit their opaque triangles
// first so the strict depth test keeps that paint when surfaces share a depth.
let opaque_count = (opaque.len() * 3) as u32;
let indices = opaque.into_iter().rev().flatten().chain(plane.into_iter().flatten()).chain(clear.into_iter().flat_map(|(t, _)| t)).collect();
let lights = lighting
.lights
.iter()
.enumerate()
.filter(|_| lighting.shade)
.map(|(i, l)| {
// The direction the light travels: away from it.
let [x, y, z] = l.direction().map(|v| -v);
let len = (x * x + y * y + z * z).sqrt();
craft_raster3d::Light {
kind: 0,
pos: [0.0; 3],
dir: [(x / len) as f32, (y / len) as f32, (z / len) as f32],
color: l.color.map(|c| srgb_to_linear((c * l.intensity).clamp(0.0, 1.0) as f32)),
cos_inner: 1.0,
cos_outer: 1.0,
falloff: 0,
radius: 0.0,
falloff_distance: 0.0,
// With Shadows off no light casts one, on the solids or on a plane.
shadow: if lighting.casts(l) { 0 } else { -1 },
shadow_darkness: 1.0,
shadow_diffusion: lighting.diffusion.get(i).map_or(l.softness, |blur| blur * scale) as f32,
}
})
.collect();
// Ambient light up to 100% goes through the sRGB curve; above it, the linear value scales with
// the intensity, as the shaded faces' ambient term does.
let ambient = lighting.ambient.clamp(0.0, 2.0) as f32;
let ambient = srgb_to_linear(ambient.min(1.0)) * ambient.max(1.0);
Some(Scene {
width: size.0,
height: size.1,
ssaa: 1,
clip,
// Camera depth: the distance in front of the eye, on the z axis.
view: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, eye as f32], [0.0, 0.0, 0.0, 1.0]],
eye: [0.0, 0.0, eye as f32],
cam_fwd: [0.0, 0.0, -1.0],
ortho: projection.eye.is_none(),
vertices,
indices,
opaque_count,
// Read only by the renderers with auxiliary outputs, which this one does not use.
part_ids: vec![],
materials,
textures: vec![],
texels: vec![],
lights,
shadows: vec![],
shadow_texels: vec![],
env: None,
ambient: [ambient; 3],
linear_io: false,
})
}
/// `image` as an image object of `id`'s art, holding its pixels as a PNG; `None` when it can't be
/// encoded.
pub fn image_node(id: NodeId, image: &Rendered) -> Option<Arc<Node>> {
Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(image_object(image)?)))))
}
/// `image` as an image object holding its pixels as a PNG; `None` when it can't be encoded.
fn image_object(image: &Rendered) -> Option<ImageObject> {
let raw = image::RgbaImage::from_raw(image.cols, image.rows, image.pixels.clone())?;
let mut png = vec![];
raw.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
let blob = ImageBlob::png(png);
let cell = image.rect.width() / f64::from(image.cols);
Some(ImageObject {
key: blob.content_key(),
width: image.cols,
height: image.rows,
xf: Affine::new([cell, 0.0, 0.0, image.rect.height() / f64::from(image.rows), image.rect.x0, image.rect.y0]),
link: None,
placement: Default::default(),
pixels: Some(Arc::new(blob)),
})
}
/// The image a 3D effect with `settings` draws for object `id` from `meshes`, lit by `lighting`, with
/// the raster effects resolution of `doc` (72 ppi without one). An error when it can't be made: the
/// effect then draws its shaded faces. With `check_only`, validate the colors and scene limits
/// without producing pixels, returning `Ok(None)` when it fits.
pub(crate) fn art(
doc: Option<&vectorcraft_doc::Document>,
id: NodeId,
lighting: &Lighting,
meshes: &[SolidMesh],
settings: RenderSettings,
check_only: bool,
) -> Result<Option<Arc<Node>>, String> {
// Mapped graphics and see-through solids keep their shaded faces, which draw the graphics and
// apply a solid's opacity once to the whole surface.
if meshes.iter().any(|m| m.graphics.is_some() || m.color[3].is_nan() || m.color[3] < 1.0) {
return Err(OPAQUE_ONLY.into());
}
let ppi = doc.map_or(72.0, |d| d.raster_ppi());
if check_only {
check(meshes, lighting, settings, ppi, &Limits::default())?;
return Ok(None);
}
let key = image_key(meshes, lighting, settings, ppi);
let made = match cached(key) {
Some(made) => made,
None => {
let made = render(meshes, lighting, settings, ppi, false, &Limits::default())
.and_then(|image| image_object(&image).ok_or_else(|| TOO_LARGE.to_string()));
keep(key, &made);
made
}
};
made.map(|object| Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object))))))
}
/// Most rendered images [`art`] keeps for reuse, and most PNG bytes they hold together. VectorCraft's
/// own values.
const KEPT_IMAGES: usize = 32;
const KEPT_BYTES: usize = 64 << 20;
/// What [`art`] made, newest last, under the key of what it was made from ([`image_key`]).
type Kept = Vec<(u128, Result<ImageObject, String>)>;
#[cfg(not(test))]
static KEPT: std::sync::Mutex<Kept> = std::sync::Mutex::new(Vec::new());
#[cfg(test)]
thread_local! {
/// Each test thread keeps its own images, so a test's count of rasterizations doesn't depend on
/// what other tests drew.
static KEPT: std::cell::RefCell<Kept> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Run `f` on the kept images; `None` when they can't be reached.
fn with_kept<T>(f: impl FnOnce(&mut Kept) -> T) -> Option<T> {
#[cfg(not(test))]
{
KEPT.lock().ok().map(|mut kept| f(&mut kept))
}
#[cfg(test)]
{
KEPT.with(|kept| kept.try_borrow_mut().ok().map(|mut kept| f(&mut kept)))
}
}
/// The image kept under `key`, moved to the newest place.
fn cached(key: u128) -> Option<Result<ImageObject, String>> {
with_kept(|kept| {
let at = kept.iter().position(|(k, _)| *k == key)?;
let entry = kept.remove(at);
let made = entry.1.clone();
kept.push(entry);
Some(made)
})
.flatten()
}
/// Keep `made` under `key`, letting the oldest go past [`KEPT_IMAGES`] or [`KEPT_BYTES`].
fn keep(key: u128, made: &Result<ImageObject, String>) {
let bytes = |m: &Result<ImageObject, String>| m.as_ref().ok().and_then(|o| o.pixels.as_ref()).map_or(0, |b| b.bytes.len());
if bytes(made) > KEPT_BYTES {
return;
}
with_kept(|kept| {
kept.retain(|(k, _)| *k != key);
kept.push((key, made.clone()));
while kept.len() > KEPT_IMAGES || kept.iter().map(|(_, m)| bytes(m)).sum::<usize>() > KEPT_BYTES {
drop(kept.remove(0));
}
});
}
/// A 128-bit hash of everything a rendered image is made from: every mesh's points, normals,
/// texture coordinates, triangles, color, material and projection, the lights, ambient light,
/// shading, shadows and shadow plane, the render settings and the resolution. Moving, turning or
/// reshaping the object, or changing any setting, changes it; panning and redrawing do not.
fn image_key(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64) -> u128 {
use std::hash::{Hash, Hasher};
let half = |seed: u8| {
let mut h = std::collections::hash_map::DefaultHasher::new();
seed.hash(&mut h);
let mut f = |v: f64| v.to_bits().hash(&mut h);
for m in meshes {
let mesh = &m.mesh;
mesh.positions.iter().chain(&mesh.normals).flatten().for_each(|v| f(*v));
mesh.uvs.iter().flatten().for_each(|v| f(*v));
m.color.iter().for_each(|c| f(f64::from(*c)));
f(m.material.roughness());
f(m.material.metallic());
if let Some(p) = m.projection {
[p.origin.x, p.origin.y, p.eye.unwrap_or(f64::NAN)].into_iter().for_each(&mut f);
}
f(mesh.positions.len() as f64);
f(mesh.triangles.len() as f64);
}
for l in &lighting.lights {
[l.rotation, l.height, l.intensity, l.softness, f64::from(u8::from(l.behind))].into_iter().chain(l.color).for_each(&mut f);
}
lighting.receiver.iter().flatten().flatten().for_each(|v| f(*v));
lighting.diffusion.iter().for_each(|v| f(*v));
f(lighting.diffusion.len() as f64);
[lighting.ambient, f64::from(u8::from(lighting.shade)), f64::from(u8::from(lighting.shadows)), lighting.lights.len() as f64]
.into_iter()
.for_each(&mut f);
[settings.quality as f64, settings.resolution.unwrap_or(f64::NAN), f64::from(u8::from(settings.white)), ppi].into_iter().for_each(&mut f);
for m in meshes {
m.mesh.triangles.hash(&mut h);
}
h.finish()
};
(u128::from(half(1)) << 64) | u128::from(half(2))
}
/// Can the solids of `items` be drawn as a rendered image: is each painted with a solid color (or
/// nothing) in Normal blending, with no member's opacity mask or blending mode applying to them
/// (`masked`)? Otherwise the effect draws its shaded faces, which keep gradients, patterns, mapped
/// graphics, masks and blending.
pub(crate) fn takes<'a>(items: impl IntoIterator<Item = &'a vectorcraft_doc::AppearanceItem>, masked: bool) -> bool {
use vectorcraft_doc::AppearanceItem;
use vectorcraft_doc::color::Paint;
!masked
&& items.into_iter().all(|i| match i {
AppearanceItem::Fill(f) => matches!(f.paint, Paint::Solid { .. } | Paint::None) && f.blend == Default::default(),
AppearanceItem::Stroke(s) => matches!(s.paint, Paint::Solid { .. } | Paint::None) && s.blend == Default::default(),
})
}
/// The lights a 3D effect with parameters `p` shades its faces with: Revolve's ([`crate::revolve_options`])
/// for Revolve, the other effects' ([`super::view_options`]) otherwise.
pub(crate) fn lighting(id: &str, p: &serde_json::Value) -> Lighting {
let (lights, ambient, shade) = if id == crate::REVOLVE {
let o = crate::revolve_options(p);
(o.active_lights(), o.ambient, o.shade)
} else {
let v = super::view_options(p);
(v.active_lights(), v.ambient, v.shade)
};
let lit = lights.iter().any(|l| l.intensity > 0.0);
let shadows = super::shadow::rendered_options(p, lit).is_some();
Lighting { lights, diffusion: vec![], ambient, shade, shadows, receiver: None }
}
/// The shadow settings a rendered image of a 3D effect with parameters `p` and lights `lighting`
/// draws its shadow plane with; `None` with Shadows off or no light lighting the art.
pub(crate) fn plane_settings(p: &serde_json::Value, lighting: &Lighting) -> Option<vectorcraft_three_d::Shadow> {
super::shadow::rendered_options(p, lighting.lights.iter().any(|l| l.intensity > 0.0))
}
#[cfg(test)]
#[path = "rendered/tests.rs"]
mod tests;
File diff suppressed because it is too large. Load diff
+14 -2
View File
@@ -25,12 +25,24 @@ pub(crate) fn options(p: &Value) -> Option<Shadow> {
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity);
let lit = flag(p, "shade", true) && intensity > 0.0;
(lit && flag(p, "shadow", false)).then(|| Shadow {
(lit && flag(p, "shadow", false)).then(|| settings(p, first))
}
/// The shadow a rendered image of `p` draws, in which every light casts one: as [`options`], but on
/// when any light lights the art (`lit`), not only the first.
pub(crate) fn rendered_options(p: &Value, lit: bool) -> Option<Shadow> {
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
(lit && flag(p, "shade", true) && flag(p, "shadow", false)).then(|| settings(p, first))
}
/// The plane settings of `p`, with the softness of light `first` (the single light's without one).
fn settings(p: &Value, first: Option<vectorcraft_three_d::Light>) -> Shadow {
Shadow {
position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(),
distance: num(p, "shadowDistance", 0.0) / 100.0,
bounds: num(p, "shadowBounds", 100.0) / 100.0,
softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness),
})
}
}
/// Check the shadow settings in `p`: an error for a value out of its range or of the wrong kind.
+1
View File
@@ -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,
+151
View File
@@ -1029,6 +1029,157 @@ fn red_parts(art: &Node) -> Vec<PathData> {
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::<usize>();
}
});
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<FillLayer> {
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()
}
@@ -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,
@@ -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,
+404
View File
@@ -0,0 +1,404 @@
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, &params).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, &params).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::<Vec<_>>();
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), &params).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, &params);
let facets = side_facets(path, FillRule::NonZero, path.bounds().unwrap_or(Rect::ZERO), &params)
.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, &params).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, &params);
let facets =
facets(EXTRUDE, &path, FillRule::NonZero, path.bounds().unwrap_or(Rect::ZERO), &params).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);
let meshes = three_d_meshes(&n).unwrap_or_else(|e| panic!("extrude: {e}"));
assert!(!meshes.is_empty(), "extrude");
assert!(meshes.iter().all(|m| m.material.is_default()));
}
+1 -1
View File
@@ -356,7 +356,7 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it()
let (path, rule) = profile(&n).unwrap();
vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }]
};
let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap();
let (drawn, _) = art_for(None, &n, std::slice::from_ref(fx), &shapes, Build::Vector, &mut None).unwrap();
let p = crate::merged_params(&fx.id, &fx.params);
let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap();
let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes));
+86 -13
View File
@@ -21,12 +21,84 @@ use crate::{GeomContext, is_geometry};
pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000;
/// The parameter that holds a 3D effect's render settings: an object whose `mode` is one of
/// [`RENDER_MODES`].
/// [`RENDER_MODES`], with the rendered image's `quality` ([`RENDER_QUALITIES`]), `resolution` and
/// `background` ([`RENDER_BACKGROUNDS`]).
pub const RENDER: &str = "render";
/// The render modes of a 3D effect: `shaded` draws the lit faces, `wireframe` the edges of every
/// face ([`renders_wireframe`]).
pub const RENDER_MODES: [&str; 2] = ["shaded", "wireframe"];
/// face ([`renders_wireframe`]), and `rendered` an image of the lit solid with the shadows of its
/// lights ([`render_settings`]).
pub const RENDER_MODES: [&str; 3] = ["shaded", "wireframe", "rendered"];
/// The qualities of the rendered image, from fastest to finest: 1, 2 × 2 and 3 × 3 samples a pixel
/// ([`RenderSettings::samples`]). VectorCraft's own values.
pub const RENDER_QUALITIES: [&str; 3] = ["low", "medium", "high"];
/// What the rendered image shows where no surface is: nothing, or white.
pub const RENDER_BACKGROUNDS: [&str; 2] = ["transparent", "white"];
/// The index in [`RENDER_QUALITIES`] of the quality a `render` without one takes (VectorCraft's own
/// default).
const DEFAULT_QUALITY: usize = 1;
/// The settings of a 3D effect's rendered image ([`render_settings`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RenderSettings {
/// The quality, as an index into [`RENDER_QUALITIES`] (0 low, 1 medium, 2 high).
pub quality: usize,
/// Pixels per inch, 1 to 2400; `None` takes Document Raster Effects Settings › Resolution.
pub resolution: Option<f64>,
/// A white background, which makes the image opaque; otherwise it is transparent where no
/// surface or shadow is.
pub white: bool,
}
impl RenderSettings {
/// The samples a pixel takes along each side at this quality: 1, 2 or 3.
pub fn samples(&self) -> u32 {
self.quality.min(2) as u32 + 1
}
}
/// The settings of the image 3D effect `id` with parameters `p` draws, when its `render` passes
/// [`validate_render`] and sets `mode` to `rendered`; `None` otherwise, when the effect draws its
/// shaded faces or its wireframe (a loaded file whose `render` breaks the rules draws shaded).
pub fn render_settings(id: &str, p: &Value) -> Option<RenderSettings> {
let render = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id))?;
if check_render(render).is_err() || render.get("mode").and_then(Value::as_str) != Some("rendered") {
return None;
}
let quality = render.get("quality").and_then(Value::as_str).and_then(|q| RENDER_QUALITIES.iter().position(|k| *k == q));
Some(RenderSettings {
quality: quality.unwrap_or(DEFAULT_QUALITY),
resolution: render.get("resolution").and_then(Value::as_f64),
white: render.get("background").and_then(Value::as_str) == Some("white"),
})
}
/// Does effect `fx` draw as a rendered image ([`render_settings`])?
pub fn renders_image(fx: &Effect) -> bool {
render_settings(&fx.id, &fx.params).is_some()
}
/// The message a `render` that breaks the rules of [`validate_render`] is refused with.
const RENDER_RULES: &str = "`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), \
resolution (null or a number from 1 to 2400) and background (transparent or white)";
/// Check one `render` value against [`RENDER_RULES`].
fn check_render(render: &Value) -> Result<(), String> {
let one_of = |v: &Value, list: &[&str]| v.as_str().is_some_and(|s| list.contains(&s));
let valid = render.as_object().is_some_and(|fields| {
fields.iter().all(|(key, value)| match key.as_str() {
"mode" => one_of(value, &RENDER_MODES),
"quality" => one_of(value, &RENDER_QUALITIES),
"background" => one_of(value, &RENDER_BACKGROUNDS),
"resolution" => value.is_null() || value.as_f64().is_some_and(|r| (1.0..=2400.0).contains(&r)),
_ => false,
})
});
if valid { Ok(()) } else { Err(RENDER_RULES.into()) }
}
/// The 3D effects that take [`RENDER`]: the 3D and Materials panel's Extrude & Bevel, Revolve,
/// Inflate and Rotate. The 3D (Classic) effects have their own Wireframe surface.
@@ -50,17 +122,14 @@ pub(crate) fn wireframe_params(id: &str, p: &Value) -> bool {
}
/// Check the render settings in 3D effect `id`'s parameters `p`: `render`, when given to one of the
/// effects in [`TAKES_RENDER`], is an object that holds only `mode`, one of [`RENDER_MODES`] (a
/// missing `mode` is `shaded`). The 3D (Classic) effects refuse it as a parameter they do not take.
/// effects in [`TAKES_RENDER`], is an object that holds only `mode` (one of [`RENDER_MODES`]),
/// `quality` (one of [`RENDER_QUALITIES`]), `resolution` (`null`, or a number from 1 to 2400 pixels
/// per inch) and `background` (one of [`RENDER_BACKGROUNDS`]). A key left out takes its default:
/// `shaded`, `medium`, the document's raster effects resolution and `transparent`. The 3D (Classic)
/// effects refuse it as a parameter they do not take.
pub(crate) fn validate_render(id: &str, p: &Value) -> Result<(), String> {
let Some(render) = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id)) else { return Ok(()) };
let valid = render
.as_object()
.is_some_and(|fields| fields.iter().all(|(key, value)| key == "mode" && value.as_str().is_some_and(|m| RENDER_MODES.contains(&m))));
if !valid {
return Err("`render` must be an object holding only `mode`, set to shaded or wireframe".into());
}
Ok(())
check_render(render)
}
/// The art a 3D effect in wireframe mode draws for object `id` in place of its shaded faces: a group
@@ -243,7 +312,11 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<FacesAndShadow,
pub(crate) fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<WireFace>, 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![];
+26 -5
View File
@@ -418,12 +418,23 @@ fn expanding_a_revolve_in_wireframe_mode_gives_the_edges() {
assert!(art.iter().all(|(_, filled, stroke)| !filled && stroke.as_ref().is_some_and(|s| s.width == WIRE_WEIGHT)));
}
/// `render` is checked before an edit: an object holding only `mode`, `shaded` or `wireframe`, and
/// only on the panel's four effects.
/// `render` is checked before an edit: an object holding only `mode` (shaded, wireframe or
/// rendered), `quality` (low, medium or high), `resolution` (null or 1 to 2400) and `background`
/// (transparent or white), and only on the panel's four effects.
#[test]
fn render_settings_are_validated() {
for id in WIRE {
for good in [json!({}), json!({"render": {}}), json!({"render": {"mode": "shaded"}}), json!({"render": {"mode": "wireframe"}})] {
for good in [
json!({}),
json!({"render": {}}),
json!({"render": {"mode": "shaded"}}),
json!({"render": {"mode": "wireframe"}}),
json!({"render": {"mode": "rendered"}}),
json!({"render": {"mode": "rendered", "quality": "high", "resolution": 300, "background": "white"}}),
json!({"render": {"mode": "rendered", "quality": "low", "resolution": null, "background": "transparent"}}),
json!({"render": {"resolution": 1}}),
json!({"render": {"resolution": 2400}}),
] {
assert_eq!(crate::validate_three_d_params(id, &good), Ok(()), "{id} {good}");
}
for bad in [
@@ -431,10 +442,20 @@ fn render_settings_are_validated() {
json!({"render": null}),
json!({"render": {"mode": "raytrace"}}),
json!({"render": {"mode": true}}),
json!({"render": {"mode": "wireframe", "quality": "high"}}),
json!({"render": {"mode": "rendered", "quality": "ultra"}}),
json!({"render": {"mode": "rendered", "resolution": 0.5}}),
json!({"render": {"mode": "rendered", "resolution": 2401}}),
json!({"render": {"mode": "rendered", "resolution": "300"}}),
json!({"render": {"mode": "rendered", "background": "black"}}),
json!({"render": {"mode": "rendered", "samples": 4}}),
] {
let e = crate::validate_three_d_params(id, &bad).unwrap_err();
assert_eq!(e, "`render` must be an object holding only `mode`, set to shaded or wireframe", "{id} {bad}");
assert_eq!(
e,
"`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), resolution (null \
or a number from 1 to 2400) and background (transparent or white)",
"{id} {bad}"
);
}
// The command check on the object refuses it too.
let n = solid_square(id, json!({}));
+5
View File
@@ -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,
@@ -111,6 +114,8 @@ apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] }
zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] }
[dev-dependencies]
# DWG files for the `.dwg` open and place tests, written from DXF by craft-dwg.
craft-dwg = { workspace = true }
# JPEG XL files for the `.jxl` open and place tests.
zune-jpegxl = { workspace = true }
zune-core = { workspace = true }
+10
View File
@@ -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<Value> {
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;
+283 -63
View File
@@ -8,10 +8,12 @@
//! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their
//! visual bounds share, Randomize Opacity gives each selected object a random
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object.
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object,
//! and Add Artboard Guides puts a rectangular guide around artboards ([`artboard_guides`]).
//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view
//! command) are the UI's.
mod artboard_guides;
pub mod marks;
#[cfg(test)]
mod tests;
@@ -21,7 +23,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 +32,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, aligned_symbols, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform,
object_bounds_transform_keeping, refit_drawn, scaling, snaps_after_edit, 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 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
@@ -71,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swap Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected",
"{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected",
exactly_two,
swap
),
@@ -80,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace with Top Object",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}",
"{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}",
has_multi,
replace
),
@@ -89,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Size of Each",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}",
"{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}",
has_selection,
size
),
@@ -98,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Match Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame after it is turned, with no smallest scale. The side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. A size that a target has no width or height to take, or that a stroke or an effect that does not scale keeps it from reaching, is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into or out of a locked layer or group, take a target out of the blend input it is in (to restack the blend itself, select the whole blend), put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place, and with Use Preview Bounds, for a target the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or inside it, or a visible geometry or 3D effect in a placed symbol's art, the match is refused when pixel snapping would move that target's reference point or change a dimension it was asked to match, as it is for a turned target that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol, with or without Use Preview Bounds; to match places, use object.align {to: \"key\"} → {source, count}",
has_multi,
match_objects
),
@@ -134,12 +140,13 @@ pub fn specs() -> Vec<CommandSpec> {
"Sort Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}",
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), corners?: the Scale Corners preference, ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}",
has_multi,
sort
),
]
.into_iter()
.chain(artboard_guides::specs())
.chain(marks::specs())
.collect()
}
@@ -169,10 +176,10 @@ fn size_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {
p.get(key).filter(|v| !v.is_null()).map(|_| number_in(p, key, 0.0, (LEAST, LIMIT), cmd)).transpose()
}
/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes`
/// and, when given, a width and height.
fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value {
let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes });
/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes`,
/// Scale Corners `corners` and, when given, a width and height.
fn place(at: Point, size: Option<(f64, f64)>, strokes: bool, corners: bool) -> Value {
let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes, "corners": corners });
if let Some((w, h)) = size {
q["width"] = json!(w);
q["height"] = json!(h);
@@ -181,14 +188,15 @@ fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value {
}
/// Transform each object of `xfs` by its own transform as undo step `label`, strokes and effects
/// scaling with Scale Strokes & Effects `strokes`, pattern tiles as Transform Pattern Tiles says.
/// When every transform is (within rounding) the identity, nothing changes.
fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, Affine)]) -> Result<()> {
/// scaling with Scale Strokes & Effects `strokes`, corners with Scale Corners `corners`, pattern
/// tiles as the command's params `p` or Transform Pattern Tiles say. When every transform is
/// (within rounding) the identity, nothing changes.
fn transform_each(s: &mut Session, label: &str, p: &Value, strokes: bool, corners: bool, xfs: &[(NodeId, Affine)]) -> Result<()> {
let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9);
if xfs.iter().all(|(_, xf)| still(xf)) {
return Ok(());
}
let p = json!({ "strokes": strokes });
let p = scaling_params(p, strokes, corners);
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
let mut sc = scaling(s, &p);
sc.patterns = transform_patterns(s, &p, &ids)?;
@@ -202,6 +210,17 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A
})
}
/// The params [`scaling`] and [`transform_patterns`] read: Scale Strokes & Effects `strokes`, Scale
/// Corners `corners`, and the `patterns` value of the command's params `p`. That one is absent on a
/// first run, which takes the preference, and present when its journal entry is replayed.
fn scaling_params(p: &Value, strokes: bool, corners: bool) -> Value {
let mut q = json!({ "strokes": strokes, "corners": corners });
if let Some(v) = p.get("patterns").filter(|v| v.is_boolean()) {
q["patterns"] = v.clone();
}
q
}
/// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the
/// command's journal entry, so replaying it scales the same way whatever the preference is then.
fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
@@ -210,6 +229,14 @@ fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
Ok(on)
}
/// The `corners` value of a replayed journal entry, else the Scale Corners preference. The value
/// joins the command's journal entry, so replaying it scales corners the same way.
fn scale_corners(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
let on = switch_or(p, "corners", s.prefs.scale_corners, cmd)?;
s.note_journal("corners", json!(on));
Ok(on)
}
/// The box of object `id` as `object.setBounds` measures it.
fn box_of(s: &Session, id: NodeId) -> Result<OrientedBox> {
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
@@ -267,7 +294,7 @@ fn grid(s: &mut Session, p: &Value) -> Result<Value> {
.enumerate()
.filter_map(|(i, (id, b))| Some((*id, Affine::translate(Point::new(*xs.get(i % cols)?, *ys.get(i / cols)?) - b.center()))))
.collect();
transform_each(s, "Arrange in Grid", false, &xfs)?;
transform_each(s, "Arrange in Grid", p, false, s.prefs.scale_corners, &xfs)?;
Ok(json!({ "count": n }))
}
@@ -295,15 +322,62 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
}
// The first stays; each later one starts `gap` past where the one before it now ends.
let mut end: Option<f64> = 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 = scaling_params(p, false, s.prefs.scale_corners);
let ids: Vec<NodeId> = 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<f64> = 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<Document> = 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() }))
}
@@ -311,12 +385,13 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.swap";
let size = switch_or(p, "size", false, C)?;
let strokes = scale_strokes(s, p, C)?;
let corners = scale_corners(s, p, C)?;
let roots = selected_roots(s)?;
let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) };
let (ba, bb) = (box_of(s, a)?, box_of(s, b)?);
let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes);
let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes, corners);
let xfs = [(a, object_bounds_transform(s, &to(&bb), a)?), (b, object_bounds_transform(s, &to(&ba), b)?)];
transform_each(s, "Swap Objects", strokes, &xfs)?;
transform_each(s, "Swap Objects", p, strokes, corners, &xfs)?;
Ok(json!({}))
}
@@ -324,6 +399,7 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.replace";
let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep");
let strokes = scale_strokes(s, p, C)?;
let corners = scale_corners(s, p, C)?;
let keep = switch_or(p, "keep", false, C)?;
let roots = selected_roots(s)?;
let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else {
@@ -343,9 +419,9 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
}
_ => None,
};
xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes), top)?));
xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes, corners), top)?));
}
let p = json!({ "strokes": strokes });
let p = scaling_params(p, strokes, corners);
let mut sc = scaling(s, &p);
sc.patterns = transform_patterns(s, &p, &[top])?;
let ids = s.edit("Replace with Top Object", |d, sel| {
@@ -375,7 +451,8 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
let proportional = switch_or(p, "proportional", false, C)?;
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
let strokes = scale_strokes(s, p, C)?;
let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) });
let corners = scale_corners(s, p, C)?;
let mut q = json!({ "reference": reference, "strokes": strokes, "corners": corners, "proportional": proportional && (width.is_none() || height.is_none()) });
if let Some(w) = width {
q["width"] = json!(w);
}
@@ -388,7 +465,7 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
xfs.push((id, object_bounds_transform(s, &q, id)?));
}
}
transform_each(s, "Set Size of Each", strokes, &xfs)?;
transform_each(s, "Set Size of Each", p, strokes, corners, &xfs)?;
Ok(json!({ "count": xfs.len() }))
}
@@ -420,6 +497,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
let stacking = switch_or(p, "stacking", false, C)?;
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
let strokes = scale_strokes(s, p, C)?;
let corners = scale_corners(s, p, C)?;
let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?;
if size == "none" && !rotate && !stacking {
return Err(bad(C, "give `size`, `rotate` or `stacking`"));
@@ -451,6 +529,11 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
};
let angle = s.doc()?.doc.bbox_angle(&[source]);
let mut xfs = Vec::with_capacity(targets.len());
// Where each turned target's reference point is before the match; it stays there.
let mut pinned: HashMap<NodeId, Point> = HashMap::new();
// The turned targets whose reference point is checked after pixel snapping.
let mut checked: HashMap<NodeId, Point> = HashMap::new();
let symbols = if rotate { aligned_symbols(&s.doc()?.doc) } else { HashMap::new() };
for &id in &targets {
let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 };
let Some(b) = s.transform_box(&[id]) else {
@@ -467,36 +550,29 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
let mut q = q.clone();
q["reference"] = json!(reference);
q["strokes"] = json!(strokes);
xf = object_bounds_transform(s, &q, id)?;
q["corners"] = json!(corners);
// Any scale the source's size asks for, however small.
xf = object_bounds_transform_keeping(s, &q, id, 0.0)?;
}
// Rotation and the fit below keep the reference point in place.
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
let turned = Affine::rotate_about(-turn.to_radians(), at);
if turn.abs() > 1e-9 {
// Rotation uses the reference point that sizing keeps in place.
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
xf = Affine::rotate_about(-turn.to_radians(), at) * xf;
xf = turned * xf;
let preview = s.bounds_measure().preview;
let d = &s.doc()?.doc;
if preview && d.node(id).is_some_and(|n| effects::preview::draws_geometry(&d.symbol_boxes(), n)) {
pinned.insert(id, at);
}
// Pixel snapping after the turn can move a pixel-aligned target: its point is checked
// too, but not put back, since that would move its aligned art off the grid.
if pinned.contains_key(&id) || d.node(id).is_some_and(|n| snaps_after_edit(n, &symbols)) {
checked.insert(id, at);
}
}
if wanted.is_some() {
let sc = scaling(s, &json!({ "strokes": strokes }));
let d = &s.doc()?.doc;
let symbols = d.symbol_boxes();
let measure = |xf| {
d.node(id).and_then(|n| {
let mut n = n.clone();
transform_node(&mut n, xf, sc, true);
let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO };
effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure())
})
};
let misses = |measured: Option<Rect>| {
measured.is_none_or(|r| match size {
"width" => (r.width() - w).abs() > 1e-6,
"height" => (r.height() - h).abs() > 1e-6,
_ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6,
})
};
// The sized and turned object, measured in its final frame, must have the size asked for.
if misses(measure(xf)) {
return Err(bad(C, format!("object {} can't take the requested size", id.0)));
}
let fit = Fit { at, refi: reference as usize, goal: match_goal(size, (w, h), b.rect), strokes, corners };
xf = fit_turned(s, id, (xf, turned), fit).ok_or_else(|| bad(C, format!("object {} can't take the requested size", id.0)))?;
}
xfs.push((id, xf));
}
@@ -513,6 +589,32 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "a clipping path can't change its place in the stacking order"));
}
let parent = d.parent_of(source);
// Each target leaves its own container, so a target's locked container refuses too.
let locked = |p: Option<NodeId>| p.is_some_and(|p| crate::cmd::layer::locked_within(d, p));
if locked(parent) || targets.iter().any(|t| locked(d.parent_of(*t))) {
return Err(bad(C, "the layer or group is locked"));
}
// A blend's input objects, and art inside them, stay in the blend: the whole blend can still be
// restacked, and art can still move within the blend's input it is in.
let is_blend = |a: &NodeId| d.node(*a).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. }));
let destination = parent.and_then(|p| d.ancestry(p)).unwrap_or_default();
let leaves_blend = |t: &NodeId| {
let chain = d.ancestry(*t).unwrap_or_default();
chain.windows(2).filter(|w| is_blend(&w[0])).any(|w| !destination.windows(2).any(|v| v == w))
};
if targets.iter().any(leaves_blend) {
return Err(bad(C, "a blend's input objects can't leave their blend input: to restack the blend, select the whole blend"));
}
// Live Paint art is rebuilt from its paths when they move: Match Objects leaves it in place.
let in_live_paint =
|id: NodeId| d.ancestry(id).unwrap_or_default().iter().any(|a| d.node(*a).is_some_and(vectorcraft_tools::builder::is_live_paint));
if parent.is_some_and(in_live_paint) || targets.iter().any(|t| d.parent_of(*t).is_some_and(in_live_paint)) {
return Err(bad(C, "Live Paint art can't be restacked here: use the Layers panel"));
}
// The source's container takes each target only as the Layers panel would (not a blend's inputs).
if let Some(n) = targets.iter().filter_map(|id| d.node(*id)).find(|n| !crate::cmd::layer::accepts(d, parent, n)) {
return Err(bad(C, format!("{} can't go beside the source object", n.display_name())));
}
if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
@@ -523,15 +625,30 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
if xfs.is_empty() && !restack {
return Ok(count);
}
let q = json!({ "strokes": strokes, "patterns": patterns });
let q = json!({ "strokes": strokes, "corners": corners, "patterns": patterns });
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
let mut sc = scaling(s, &q);
sc.patterns = transform_patterns(s, &q, &ids)?;
let measure = s.bounds_measure();
let before = s.doc()?.doc.clone();
s.edit("Match Objects", |d, _| {
for (id, xf) in &xfs {
if let Some(n) = d.node_mut(*id) {
transform_node(n, *xf, sc, true);
}
// A live effect that moves the art in page space (a Transform effect's offset) does
// not turn with it: the measured reference point is put back where it was.
if let Some(at) = pinned.get(id)
&& let Some(b) = effects::preview::oriented_bounds_with(d, &[*id], measure)
{
let now = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
let off = *at - now;
if off.hypot() > 1e-9
&& let Some(n) = d.node_mut(*id)
{
transform_node(n, Affine::translate(off), sc, true);
}
}
}
if restack {
let moved = d.remove_many(&targets)?;
@@ -539,11 +656,113 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
// Targets moved out of an Intertwine group leave it as ordinary art.
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
}
if !checked.is_empty() {
// Measured on a snapped copy: the edit itself snaps once, after Global Edit.
let mut snapped = d.clone();
crate::cmd::refresh_pixel_aligned(&before, &mut snapped);
for (id, _) in &xfs {
let Some(at) = checked.get(id) else { continue };
let ob = effects::preview::oriented_bounds_with(&snapped, &[*id], measure);
let kept = ob.is_some_and(|b| (*at - b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize)).hypot() <= 1e-6);
let misses = !kept
|| ob.is_none_or(|b| match size {
"none" => false,
"width" => (b.rect.width() - w).abs() > 1e-6,
"height" => (b.rect.height() - h).abs() > 1e-6,
_ => (b.rect.width() - w).abs() > 1e-6 || (b.rect.height() - h).abs() > 1e-6,
});
if misses {
return Err(bad(C, format!("object {} can't keep its size and reference point as it turns", id.0)));
}
}
}
Ok(())
})?;
Ok(count)
}
/// The size a target of Match Objects ends with: for `size` "width" ("height") the source's width
/// `w` (height `h`), the other side following in proportion to the target's box `b`; for "both", the
/// source's width and height.
fn match_goal(size: &str, (w, h): (f64, f64), b: Rect) -> [f64; 2] {
let follow = |side: f64, from: f64, to: f64| if from > 0.0 { side * to / from } else { side };
match size {
"width" => [w, follow(b.height(), b.width(), w)],
"height" => [follow(b.width(), b.height(), h), h],
_ => [w, h],
}
}
/// What [`fit_turned`] fits a target of Match Objects to.
struct Fit {
/// The target's reference point, which stays in place.
at: Point,
/// That point's index on the 9-point grid.
refi: usize,
/// The width and height wanted ([`match_goal`]).
goal: [f64; 2],
/// Scale Strokes & Effects.
strokes: bool,
/// Scale Corners.
corners: bool,
}
/// `xf`, which sizes and turns object `id`, made to give the object the size `fit.goal` (within
/// 1e-9 of the larger of 1 and each side) as `object.setBounds` measures it in the frame the object
/// ends in. When it misses, for example when a stroke or an effect does not turn with the art,
/// scales in that frame are fitted with [`refit_drawn`] from the object turned by `turned` alone,
/// and point `fit.refi` of the fitted box goes to `fit.at`. The object is measured before Align to
/// Pixel Grid snaps it, as every transform snaps it after. `None` when no scale gives the size.
fn fit_turned(s: &mut Session, id: NodeId, (xf, turned): (Affine, Affine), fit: Fit) -> Option<Affine> {
let Fit { at, refi, goal, strokes, corners } = fit;
let sc = scaling(s, &json!({ "strokes": strokes, "corners": corners }));
let how = s.bounds_measure();
let d = &s.doc().ok()?.doc;
let symbols = d.symbol_boxes();
let n = d.node(id)?;
let moved = |xf: Affine| {
let mut n = n.clone();
n.transform(xf, sc);
n
};
// The angle the object's box ends at after `xf`, as `Node::transform` sets it (a layer keeps its own).
let angle_after = |xf: Affine| if n.is_layer() { n.bbox_angle } else { vectorcraft_doc::orient::transformed_angle(n.bbox_angle, xf) };
// The frame the turn gives; sizing can leave the art without a width or a height to show it.
let frame = OrientedBox { angle: angle_after(turned), rect: Rect::ZERO };
let to_local = frame.to_doc().inverse();
let measure = |xf: Affine| effects::preview::bounds_in_with(&symbols, &moved(xf), to_local, how);
let tolerances = goal.map(|side| 1e-9 * side.max(1.0));
let fits = |r: Rect| [r.width(), r.height()].into_iter().zip(goal).zip(tolerances).all(|((v, g), t)| (v - g).abs() <= t);
let keeps_angle = |xf: Affine| vectorcraft_geom::normalize_deg(angle_after(xf) - frame.angle).abs() <= 1e-6;
let rp = frame.to_local(at);
// The object turned by `turned`, then scaled by `sx` and `sy` in the frame about the reference point.
let scaled = |sx: f64, sy: f64| {
frame.conjugate(Affine::translate(rp.to_vec2()) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-rp.to_vec2())) * turned
};
// `xf` with point `refi` of the box as measured moved to the reference point's place: a stroke
// or an effect that does not turn with the art moves it.
let placed = |xf: Affine| -> Option<(Affine, Rect)> {
let b = measure(xf)?;
let correction = rp - vectorcraft_geom::reference_point(b, refi);
if correction.x.abs() <= 1e-12 && correction.y.abs() <= 1e-12 {
return Some((xf, b));
}
let xf = frame.conjugate(Affine::translate(correction)) * xf;
Some((xf, measure(xf)?))
};
let accepts = |xf: Affine, b: Rect| fits(b) && keeps_angle(xf);
if let Some((xf, _)) = placed(xf).filter(|(xf, b)| accepts(*xf, *b)) {
return Some(xf);
}
// The sizing above can leave the art without a width or a height that the turned object needs,
// so the fit starts again from the object as it is, turned.
let now = measure(turned)?;
let ratio = |g: f64, v: f64| if v > 1e-9 { g / v } else { 1.0 };
let start = (ratio(goal[0], now.width()), ratio(goal[1], now.height()));
let (sx, sy, _) = refit_drawn(|sx, sy| measure(scaled(sx, sy)), refi, goal, start, [true, true], Some(tolerances))?;
placed(scaled(sx, sy)).filter(|(xf, b)| accepts(*xf, *b)).map(|(xf, _)| xf)
}
/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch,
/// chains included, among items of the same key (parent). A sweep along x: only the rects still
/// open where each one starts are compared with it.
@@ -790,6 +1009,7 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
let distribute = switch_or(p, "distribute", false, C)?;
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
let strokes = scale_strokes(s, p, C)?;
let corners = scale_corners(s, p, C)?;
let ids = checked_ids_or_selection(s, p, C)?;
if ids.len() > MAX_OBJECTS {
return Err(bad(C, "too many objects selected (at most 20000)"));
@@ -872,17 +1092,17 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
let q = match apply {
"x" => json!({ "x": v, "reference": 0 }),
"y" => json!({ "y": v, "reference": 0 }),
"width" => json!({ "width": v, "strokes": strokes }),
"height" => json!({ "height": v, "strokes": strokes }),
"width" => json!({ "width": v, "strokes": strokes, "corners": corners }),
"height" => json!({ "height": v, "strokes": strokes, "corners": corners }),
// An area: both sides in proportion; an object without one keeps its size.
_ => {
let (w, h) = (o.b.rect.width(), o.b.rect.height());
let k = if w * h > 1e-12 { (v / (w * h)).sqrt() } else { 1.0 };
json!({ "width": w * k, "height": h * k, "strokes": strokes })
json!({ "width": w * k, "height": h * k, "strokes": strokes, "corners": corners })
}
};
xfs.push((o.id, object_bounds_transform(s, &q, o.id)?));
}
transform_each(s, "Sort Objects", strokes, &xfs)?;
transform_each(s, "Sort Objects", p, strokes, corners, &xfs)?;
Ok(count)
}
@@ -0,0 +1,206 @@
//! Add Artboard Guides (`addon.arrange.artboardGuides`): a rectangular guide around each chosen
//! artboard, `offset` outside its edges (inside when negative), on a top-level layer named
//! Artboard Guides. Its dialog is the UI's.
#[cfg(test)]
mod tests;
use std::collections::HashSet;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes};
use super::super::super::panelcmds::{artboard_at, listed_artboards};
use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or};
use super::{LIMIT, number_in};
use crate::sanity::rect_in_range;
use crate::{DocState, Result, Session};
/// The command.
pub(crate) const COMMAND: &str = "addon.arrange.artboardGuides";
/// The top-level layer the guides go on, made when the document has none of that name.
pub(crate) const LAYER: &str = "Artboard Guides";
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.arrange.artboardGuides",
"Add Artboard Guides",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{offset?: pt −1000000..1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside), artboards?: [index…] (0-based; default: the active artboard, `artboard`), artboard?: index (the active artboard, which the app passes; default the view's, which the journal then records as `artboard` for a replay), all?: false (true: every artboard; not with `artboards`)} add a rectangular guide path around each of those artboards, `offset` from its edges, as one undo step. The guides go on the topmost top-level layer named Artboard Guides, which keeps its lock and visibility; a new one is made above the others when there is none. The guide paths have the current paint (Release Guides makes them paths with it). A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. It is an error when an inset leaves an artboard no width or no height, and when an edge of a guide would lie more than 4,000,000 pt from the origin along either axis. Off without artboards → {ids, layer: id (null when nothing was added and there is no such layer), skipped (guides already there)}",
has_artboards,
artboard_guides
)]
}
/// A document with at least one artboard is open.
fn has_artboards(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
if s.doc().map_err(|e| e.to_string())?.doc.artboards.is_empty() { Err("the document has no artboards".into()) } else { Ok(()) }
}
/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no
/// longer has it, the artboard the document opened on, else the first.
fn active_artboard(st: &DocState) -> usize {
let d = &st.doc;
let at = |id: Option<u32>| id.and_then(|id| d.artboards.iter().position(|a| a.id == id));
at(st.active_artboard).or_else(|| at(d.opened_artboard)).unwrap_or(0)
}
/// The topmost top-level layer named [`LAYER`].
fn guide_layer(d: &Document) -> Option<NodeId> {
d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id)
}
/// `r`'s corners as an exact hash key, whichever way round `r` runs.
fn rect_key(r: Rect) -> [u64; 4] {
let r = r.abs();
[r.x0, r.y0, r.x1, r.y1].map(|v| if v == 0.0 { 0 } else { v.to_bits() })
}
#[cfg(test)]
thread_local! {
static GUIDE_NODES_VISITED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn guide_rectangles(d: &Document, layer: Option<NodeId>) -> HashSet<[u64; 4]> {
let mut rects = HashSet::new();
if let Some(n) = layer.and_then(|id| d.node(id)) {
n.walk(&mut |c| {
#[cfg(test)]
GUIDE_NODES_VISITED.with(|count| count.set(count.get() + 1));
// The anchors' bounds: `traces` only accepts segments that stay between their anchors.
if let NodeKind::Path { path, guide: true, .. } = &c.kind
&& let [sp] = &path.subpaths[..]
&& let Some(first) = sp.anchors.first()
{
let r = sp.anchors.iter().fold(Rect::from_points(first.p, first.p), |r, a| r.union_pt(a.p));
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
if traces(path, &corners) {
rects.insert(rect_key(r));
}
}
});
}
rects
}
/// Does the segment from `a` to `b` run straight along a horizontal or vertical line, from `a` to `b`
/// without turning back? Its handles lie on that line, and the curve's position along it never reverses.
fn straight(a: &Anchor, b: &Anchor) -> bool {
let along = |f: fn(Point) -> f64, g: fn(Point) -> f64| {
if [a.h_out, b.h_in].iter().any(|h| g(*h) != g(a.p)) || g(a.p) != g(b.p) {
return false;
}
let s = (f(b.p) - f(a.p)).signum();
let [p0, p1, p2, p3] = [a.p, a.h_out, b.h_in, b.p].map(|p| f(p) * s);
// The derivative along the line, as a quadratic Bernstein form: never negative on [0, 1].
let (u, v, w) = (p1 - p0, p2 - p1, p3 - p2);
let curve = u - 2.0 * v + w;
let vertex = if curve > 0.0 && (0.0..=1.0).contains(&((u - v) / curve)) { u - (u - v) * (u - v) / curve } else { 0.0 };
u >= 0.0 && w >= 0.0 && vertex >= 0.0
};
if a.p == b.p {
return a.h_out == a.p && b.h_in == a.p;
}
along(|p| p.x, |p| p.y) || along(|p| p.y, |p| p.x)
}
/// Is `path` one closed run of straight segments through `corners`, from any corner, either way round?
fn traces(path: &PathData, corners: &[Point; 4]) -> bool {
let [sp] = &path.subpaths[..] else { return false };
if !sp.closed || sp.anchors.len() < 4 {
return false;
}
let n = sp.anchors.len();
if (0..n).any(|i| !straight(&sp.anchors[i], &sp.anchors[(i + 1) % n])) {
return false;
}
// A last anchor on the first one only closes the path: the check above has kept its handles on that
// point, so the corners are read without it.
let m = if sp.anchors[n - 1].p == sp.anchors[0].p { n - 1 } else { n };
let points: Vec<Point> = sp
.anchors
.iter()
.take(m)
.enumerate()
.filter_map(|(i, a)| {
let prev = sp.anchors[(i + m - 1) % m].p;
let next = sp.anchors[(i + 1) % m].p;
let interior = (prev.x == a.p.x && a.p.x == next.x && a.p.y > prev.y.min(next.y) && a.p.y < prev.y.max(next.y))
|| (prev.y == a.p.y && a.p.y == next.y && a.p.x > prev.x.min(next.x) && a.p.x < prev.x.max(next.x));
(!interior).then_some(a.p)
})
.collect();
let [first, second, _, _] = &points[..] else { return false };
let (Some(start), Some(next)) = (corners.iter().position(|c| c == first), corners.iter().position(|c| c == second)) else {
return false;
};
// 1 runs the way `corners` does, 3 the other way.
let step = (next + 4 - start) % 4;
(step == 1 || step == 3) && points.iter().enumerate().all(|(k, p)| *p == corners[(start + k * step) % 4])
}
fn artboard_guides(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = COMMAND;
let offset = number_in(p, "offset", 0.0, (-LIMIT, LIMIT), C)?;
let all = switch_or(p, "all", false, C)?;
let listed = p.get("artboards").filter(|v| !v.is_null());
if all && listed.is_some() {
return Err(bad(C, "give `all` or `artboards`, not both"));
}
let st = s.doc()?;
let d = &st.doc;
if d.artboards.is_empty() {
return Err(bad(C, "the document has no artboards"));
}
// The active artboard: the one the app passes, else the view's, recorded for a replay.
let active = artboard_at(d, p, "artboard", C)?;
let indices: Vec<usize> = match listed {
Some(v) => listed_artboards(d, v, "artboards", C)?,
None if all => (0..d.artboards.len()).collect(),
None => vec![active.unwrap_or_else(|| active_artboard(st))],
};
if let (false, None, None, Some(&i)) = (all, listed, active, indices.first()) {
s.note_journal("artboard", json!(i));
}
let st = s.doc()?;
let d = &st.doc;
let layer = guide_layer(d);
let mut existing = guide_rectangles(d, layer);
let (mut rects, mut skipped) = (Vec::with_capacity(indices.len()), 0);
for i in indices {
let Some(board) = d.artboards.get(i) else { continue };
let r = board.rect.inflate(offset, offset);
if !(r.width() > 0.0 && r.height() > 0.0) {
return Err(bad(C, format!("the inset leaves artboard {i} ({}) no width or height", board.name)));
}
if !rect_in_range(r) {
return Err(bad(C, "the guide would reach past the edge of the canvas"));
}
if !existing.insert(rect_key(r)) {
skipped += 1;
} else {
rects.push(r);
}
}
if rects.is_empty() {
return Ok(json!({ "ids": [], "layer": layer.map(|l| l.0), "skipped": skipped }));
}
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
let (layer, ids) = s.edit("Add Artboard Guides", |d, _| {
let layer = guide_layer(d).unwrap_or_else(|| d.add_layer(Some(LAYER)));
let mut ids = Vec::with_capacity(rects.len());
for r in &rects {
let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), Default::default());
look.apply(d, &mut n);
if let NodeKind::Path { guide, .. } = &mut n.kind {
*guide = true;
}
ids.push(d.insert(Some(layer), usize::MAX, n)?);
}
Ok((layer, ids))
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "layer": layer.0, "skipped": skipped }))
}
@@ -0,0 +1,336 @@
//! Add Artboard Guides: the guide rectangles it adds and where, the artboards it takes, the layer
//! it reuses, one undo step (none when nothing is added), when it is off, and bad params refused
//! without a change.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{PathData, Point, Rect, SubPath};
use super::{COMMAND, LAYER};
use crate::Session;
/// A new document with one 400 × 300 pt artboard and a second one beside it.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("artboard.new", &json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
s
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn board(s: &Session, i: usize) -> Rect {
s.doc().unwrap().doc.artboards[i].rect
}
fn ids(r: &Value) -> Vec<NodeId> {
r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect()
}
/// The guide rectangle of path `id`: its bounds, and that it is a guide on layer `layer`.
fn guide(s: &Session, layer: NodeId, id: NodeId) -> Rect {
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
assert!(matches!(n.kind, NodeKind::Path { guide: true, .. }), "{id:?} is a guide path");
assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == id), "{id:?} is on the guides layer");
n.geometric_bounds().unwrap()
}
fn near(a: Rect, b: Rect) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-9)
}
fn layer_names(s: &Session) -> Vec<String> {
s.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect()
}
#[test]
fn a_positive_offset_puts_a_guide_outside_the_active_artboard_on_a_new_layer() {
let mut s = session();
let n = steps(&s);
let before = layer_names(&s);
let r = s.execute(COMMAND, &json!({"offset": 9})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
let layer = NodeId(r["layer"].as_u64().unwrap());
assert_eq!(r["skipped"], json!(0));
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
// The active artboard is the first when the view has not picked one.
assert!(near(guide(&s, layer, id), board(&s, 0).inflate(9.0, 9.0)), "{:?}", guide(&s, layer, id));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.last().unwrap().id, layer, "the new layer goes above the others");
assert_eq!(d.layers.last().unwrap().display_name(), LAYER);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer_names(&s), before, "undo takes the layer away with the guide");
}
#[test]
fn the_active_artboard_is_the_one_the_view_keeps() {
let mut s = session();
let second = s.doc().unwrap().doc.artboards[1].id;
s.doc_mut().unwrap().active_artboard = Some(second);
let r = s.execute(COMMAND, &json!({})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
assert!(near(guide(&s, layer, id), board(&s, 1)), "offset 0: on the artboard's edges");
assert_eq!(s.journal.last().unwrap().1["artboard"], json!(1), "the journal records the artboard for a replay");
// The artboard the app passes wins over the view's.
let r = s.execute(COMMAND, &json!({"offset": 4, "artboard": 0})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
assert!(near(guide(&s, layer, id), board(&s, 0).inflate(4.0, 4.0)));
assert!(s.execute(COMMAND, &json!({"artboard": 5})).is_err(), "no such artboard");
}
#[test]
fn a_negative_offset_insets_every_artboard_and_reuses_the_layer_keeping_its_lock_and_visibility() {
let mut s = session();
let layer = NodeId(s.execute("layer.new", &json!({"name": LAYER})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.new", &json!({"name": "Art"})).unwrap();
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
s.execute("layer.setProps", &json!({"ids": [layer.0], "visible": false})).unwrap();
let (layers, n) = (s.doc().unwrap().doc.layers.len(), steps(&s));
let r = s.execute(COMMAND, &json!({"offset": -12, "all": true})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step for every artboard");
assert_eq!(r["layer"], json!(layer.0), "the layer of that name is reused");
assert_eq!(s.doc().unwrap().doc.layers.len(), layers, "no layer is added");
let added = ids(&r);
assert_eq!(added.len(), 2);
for (i, id) in added.into_iter().enumerate() {
assert!(near(guide(&s, layer, id), board(&s, i).inflate(-12.0, -12.0)), "artboard {i}");
}
let l = s.doc().unwrap().doc.node(layer).unwrap().clone();
assert!(l.locked && !l.visible, "the layer keeps its lock and visibility");
}
#[test]
fn listed_artboards_get_a_guide_each_and_a_guide_already_there_is_not_added_again() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1]})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
assert!(near(guide(&s, layer, id), board(&s, 1).inflate(5.0, 5.0)));
// Again: nothing to add, and no undo step.
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1, 1]})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}));
assert_eq!(steps(&s), n, "a run that adds nothing makes no step");
assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before) || *s.doc().unwrap().doc == *before);
// Both artboards: only the new one is added.
let both = s.execute(COMMAND, &json!({"offset": 5, "artboards": [0, 1]})).unwrap();
assert_eq!(both["skipped"], json!(1));
let [first] = ids(&both)[..] else { panic!("one guide: {both}") };
assert!(near(guide(&s, layer, first), board(&s, 0).inflate(5.0, 5.0)));
assert_eq!(steps(&s), n + 1);
}
#[test]
fn a_guide_grouped_inside_the_layer_is_not_added_again() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let d = &s.doc().unwrap().doc;
assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == group));
assert!(d.node(group).unwrap().children().unwrap().iter().any(|c| c.id == id));
let (before, n) = (d.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}));
assert_eq!(steps(&s), n, "a run that adds nothing makes no step");
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
}
#[test]
fn a_guide_drawn_the_other_way_round_or_from_another_corner_is_not_added_again() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0).inflate(5.0, 5.0);
let corners = [Point::new(b.x0, b.y1), Point::new(b.x1, b.y1), Point::new(b.x1, b.y0), Point::new(b.x0, b.y0)];
// Reversed from the top-left corner, reversed from the bottom-left one, and the same way round from the bottom-right one.
for points in [vec![corners[3], corners[0], corners[1], corners[2]], corners.to_vec(), vec![corners[1], corners[0], corners[3], corners[2]]] {
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
if let Some(NodeKind::Path { path, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
*path = PathData::single(SubPath::polyline(&points, true));
}
let n = steps(&s);
let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}), "{points:?}");
assert_eq!(steps(&s), n);
}
}
#[test]
fn collinear_midpoints_do_not_add_another_guide_or_history_step() {
let mut s = session();
let r = s.execute(COMMAND, &json!({})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0);
let points = [
Point::new(b.center().x, b.y0),
Point::new(b.x1, b.y0),
Point::new(b.x1, b.center().y),
Point::new(b.x1, b.y1),
Point::new(b.center().x, b.y1),
Point::new(b.x0, b.y1),
Point::new(b.x0, b.center().y),
Point::new(b.x0, b.y0),
];
for reverse in [false, true] {
let mut points = points.to_vec();
if reverse {
points.reverse();
}
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
*path = PathData::single(SubPath::polyline(&points, true));
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}));
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc, before);
}
}
#[test]
fn a_closing_anchor_on_the_first_one_does_not_add_another_guide_or_history_step() {
let mut s = session();
let r = s.execute(COMMAND, &json!({})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0);
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)];
for reverse in [false, true] {
let mut points = corners.to_vec();
if reverse {
points.reverse();
}
points.push(points[0]);
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
*path = PathData::single(SubPath::polyline(&points, true));
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "reverse: {reverse}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc, before);
}
}
#[test]
fn handles_along_a_side_still_match_and_handles_off_it_do_not() {
let mut s = session();
let r = s.execute(COMMAND, &json!({})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0);
let mid = Point::new(b.center().x, b.y0);
let points = [mid, Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1), Point::new(b.x0, b.y0)];
let corner = points[1];
let set = |s: &mut Session, h_in: Point, h_out: Point, corner_in: Point| {
let mut sp = SubPath::polyline(&points, true);
sp.anchors[0].h_in = h_in;
sp.anchors[0].h_out = h_out;
sp.anchors[1].h_in = corner_in;
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
*path = PathData::single(sp);
};
// The extra anchor's handles lie along the top side: the guide still matches.
// Then a handle past the corner on a segment that still runs one way (along x: 0, 9, 6, 8 eighths).
let eighth = (corner.x - mid.x) / 8.0;
for (h_out, corner_in) in
[(Point::new(mid.x + 20.0, b.y0), corner), (Point::new(mid.x + 9.0 * eighth, b.y0), Point::new(mid.x + 6.0 * eighth, b.y0))]
{
set(&mut s, Point::new(mid.x - 20.0, b.y0), h_out, corner_in);
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "{h_out:?} {corner_in:?}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc, before);
}
// A handle off the side bends it: the path is not that guide, so one is added.
set(&mut s, Point::new(mid.x - 20.0, b.y0), Point::new(mid.x + 20.0, b.y0 + 10.0), corner);
let other = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(other["skipped"], json!(0));
assert_eq!(ids(&other).len(), 1);
}
#[test]
fn every_artboard_shares_one_walk_of_existing_guides() {
let mut s = session();
s.execute(COMMAND, &json!({"all": true})).unwrap();
super::GUIDE_NODES_VISITED.with(|count| count.set(0));
s.execute(COMMAND, &json!({})).unwrap();
let single = super::GUIDE_NODES_VISITED.with(|count| count.replace(0));
assert!(single > 0);
let n = steps(&s);
let r = s.execute(COMMAND, &json!({"all": true})).unwrap();
assert_eq!(super::GUIDE_NODES_VISITED.with(|count| count.get()), single);
assert!(ids(&r).is_empty());
assert_eq!(r["skipped"], json!(2));
assert_eq!(steps(&s), n);
}
#[test]
fn release_guides_gives_back_a_rectangle_path() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 3})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
s.execute("view.guides.release", &json!({"ids": [id.0]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(matches!(n.kind, NodeKind::Path { guide: false, .. }));
assert!(near(n.geometric_bounds().unwrap(), board(&s, 0).inflate(3.0, 3.0)));
}
#[test]
fn an_inset_that_leaves_no_width_or_height_and_bad_params_are_refused_without_a_change() {
let mut s = session();
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
// The second artboard is 100 pt tall: an inset of 50 leaves it no height.
for p in [
json!({"offset": -50, "all": true}),
json!({"offset": -200}),
json!({"offset": "9 pt"}),
json!({"offset": 1_000_001}),
json!({"offset": -1e308}),
json!({"all": 1}),
json!({"all": true, "artboards": [0]}),
json!({"artboards": []}),
json!({"artboards": [2]}),
json!({"artboards": [-1]}),
json!({"artboards": [0.5]}),
json!({"artboards": "0"}),
] {
assert!(s.execute(COMMAND, &p).is_err(), "{p}");
}
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
let e = s.execute(COMMAND, &json!({"offset": -150})).unwrap_err().to_string();
assert!(e.contains("no width or height"), "{e}");
}
#[test]
fn a_guide_past_the_edge_of_the_canvas_is_refused() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 3_999_000, "y": 0, "width": 500, "height": 100})).unwrap();
let n = steps(&s);
let e = s.execute(COMMAND, &json!({"offset": 600, "artboards": [2]})).unwrap_err().to_string();
assert!(e.contains("past the edge of the canvas"), "{e}");
assert_eq!(steps(&s), n);
s.execute(COMMAND, &json!({"offset": 400, "artboards": [2]})).unwrap();
}
#[test]
fn it_is_off_without_artboards() {
let mut s = session();
let enabled = |s: &Session| s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled;
assert!(enabled(&s));
Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear();
assert!(!enabled(&s));
assert!(s.execute(COMMAND, &json!({})).is_err());
}
+96 -10
View File
@@ -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<CommandSpec> {
"Mark Bounds of Each",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \
\"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \
\"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 \
(10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), \
color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object \
(the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, \
stacked directly above its object (above the outermost clip group, clipping sublayer or live object that holds it: \
a blend, compound path, compound shape, Shaper group, Objects on Path group, Live Paint group, dimension, graph, flare, envelope, \
mesh, repeat, intertwine, Image Trace group, generated art group, graph series, graph design copy or \
clipping pieces group, so the clip does not hide them and the live object does not take them in; in isolation mode, \
marks that would go outside the isolated art are an error). Selected parts of compound paths, envelopes, meshes, repeats, \
Shaper groups and blends with a stored spine or Align to Path, and hidden Image Trace sources, are measured as the outermost \
such live object, with one set of marks per object. Other blend keys and compound shape operands keep their own bounds. \
A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds \
such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; \
one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
has_selection,
mark_bounds
)]
@@ -81,13 +96,18 @@ fn corner_paths(r: Rect, length: f64) -> Vec<PathData> {
.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, bool>) -> NodeId {
let (mut at, mut outermost) = (id, id);
while let Some(up) = d.parent_of(at) {
if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() {
let holds = *held.entry(up).or_insert_with(|| d.node(up).is_some_and(|n| n.clips() || !plain(n)) && d.parent_of(up).is_some());
if holds {
outermost = up;
}
at = up;
@@ -95,6 +115,51 @@ fn anchor(d: &Document, id: NodeId) -> NodeId {
outermost
}
/// Whether `n` is a layer or a group with no live role, which keeps new art as an ordinary member.
fn plain(n: &Node) -> bool {
let e = n.extras();
matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })
&& !n.is_compound_shape()
&& e.shaper.is_none()
&& e.objects_on_path.is_none()
&& e.dimension.is_none()
&& e.graph.is_none()
&& e.flare.is_none()
&& e.trace.is_none()
&& e.generated.is_none()
&& e.series_index.is_none()
&& !e.graph_design_art
&& !e.clip_pieces
&& e.live_paint_gaps.is_none()
&& !vectorcraft_tools::builder::is_live_paint(n)
}
/// The outermost live object that draws a selected part with different geometry or placement.
fn measured_object(d: &Document, id: NodeId) -> NodeId {
let (mut at, mut measured) = (id, id);
while let Some(up) = d.parent_of(at) {
if let Some(n) = d.node(up) {
let redraws = match &n.kind {
NodeKind::Compound { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => true,
NodeKind::Blend { spec, .. } => {
(spec.spine.is_some() && !spec.no_spine) || spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath
}
_ => {
n.extras().shaper.is_some()
|| (n.extras().trace.is_some()
&& n.children()
.is_some_and(|children| children.first().is_some_and(|c| c.id == at) && n.editing_children().len() < children.len()))
}
};
if redraws {
measured = up;
}
}
at = up;
}
measured
}
fn mark_bounds(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = COMMAND;
let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle");
@@ -106,18 +171,39 @@ fn mark_bounds(s: &mut Session, p: &Value) -> Result<Value> {
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<NodeId, bool> = HashMap::new();
let mut measured = HashSet::new();
let mut too_small = false;
for id in roots {
if d.node(id).is_none_or(|n| n.is_guide()) {
continue;
}
let id = measured_object(d, id);
if !measured.insert(id) {
continue;
}
let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue };
let placed = matches!(n.kind, NodeKind::Blend { .. }).then(|| {
let mut art = vectorcraft_render::effects::expand_live_deep(Some(d), n);
art.appearance = n.appearance.clone();
art
});
let n = placed.as_ref().unwrap_or(n);
let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) };
let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) else { continue };
// Corner legs are at most half a side, so an object too small for any leg gets no marks.
let (lx, ly) = legs(r, length);
if rectangle || lx > FLAT || ly > FLAT {
marked.push((anchor(d, id), r));
let at = anchor(d, id, &mut held);
// Marks placed outside the isolated art could not be selected or edited there.
if isolation.is_some_and(|iso| iso == at || !d.ancestry(at).is_some_and(|a| a.contains(&iso))) {
return Err(bad(C, "the marks would go outside the isolated art: exit isolation mode first"));
}
marked.push((at, r));
} else {
too_small = true;
}
@@ -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();
@@ -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<NodeId> = (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<Rect> = ids.iter().map(|i| bounds(&s, *i)).collect();
let gaps: Vec<f64> = 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<NodeId> = (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();
@@ -378,6 +439,19 @@ fn match_gives_the_others_the_key_objects_size() {
assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c));
}
#[test]
fn match_keeps_the_proportion_of_a_very_thin_target() {
let b = Rect::new(0.0, 0.0, 1e-10, 1.0);
let [w, h] = super::match_goal("width", (1.0, 5.0), b);
assert_eq!(w, 1.0);
assert!((h - 1e10).abs() <= 1.0, "{h}");
let [w, h] = super::match_goal("height", (5.0, 1.0), Rect::new(0.0, 0.0, 1.0, 1e-10));
assert!((w - 1e10).abs() <= 1.0, "{w}");
assert_eq!(h, 1.0);
// A target with no width keeps its height.
assert_eq!(super::match_goal("width", (1.0, 5.0), Rect::new(0.0, 0.0, 0.0, 3.0)), [1.0, 3.0]);
}
#[test]
fn match_takes_the_top_or_the_bottom_object_without_a_key() {
let mut s = session();
@@ -451,6 +525,67 @@ fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() {
}
}
#[test]
fn match_rotation_refuses_when_pixel_snapping_would_move_the_reference_point() {
for wrap in ["path", "group", "compound"] {
let mut s = session();
let target = rect(&mut s, 0.0, 0.0, 10.0, 11.0);
if wrap != "compound" {
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
}
let target = match wrap {
"group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()),
"compound" => NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()),
_ => target,
};
select(&mut s, &[target]);
if wrap == "compound" {
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
}
let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
select(&mut s, &[source]);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
// Turned a quarter about its center (5, 5.5), the 10 x 11 path's edges land on half points,
// and snapping them back to the grid would move that center.
let e = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string();
assert!(e.contains("reference point"), "{wrap}: {e}");
assert_eq!(steps(&s), n, "{wrap}: no undo step");
assert!(*s.doc().unwrap().doc == *before, "{wrap}");
}
}
#[test]
fn match_rotation_keeps_a_mixed_group_in_one_piece_or_refuses() {
let mut s = session();
let aligned = rect(&mut s, 0.0, 0.0, 10.0, 11.0);
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
let loose = rect(&mut s, 20.0, 0.0, 10.0, 11.0);
select(&mut s, &[aligned, loose]);
let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
select(&mut s, &[source]);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let gap = |s: &Session| {
let (a, b) = (s.transform_box(&[aligned]).unwrap().center(), s.transform_box(&[loose]).unwrap().center());
b - a
};
let before = s.doc().unwrap().doc.clone();
match s.execute("addon.arrange.match", &json!({"rotate": true})) {
// Turned a quarter, the members' centers keep their distance and only change direction.
Ok(_) => assert!((gap(&s).hypot() - 20.0).abs() < 1e-6, "the members moved apart: {:?}", gap(&s)),
Err(e) => {
assert!(e.to_string().contains("reference point"), "{e}");
assert!(*s.doc().unwrap().doc == *before);
}
}
}
#[test]
fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() {
for angle in [0, 30] {
@@ -577,6 +712,44 @@ fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) {
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s));
}
/// Running `cmd` with Scale Corners on doubles the 2 pt corner radius of a 10 pt rounded square,
/// and replaying its journal entry after the preference is turned off scales the corners the same way.
fn replays_the_corner_scaling_it_ran_with(cmd: &str, p: Value) {
let mut s = session();
let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10, "radius": 2})).unwrap()["id"].as_u64().unwrap());
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
let radius = |s: &Session| match s.doc().unwrap().doc.node(a).unwrap().live_shape() {
Some(vectorcraft_doc::LiveShape::Rectangle { radii, xf, .. }) => radii[0] * xf.as_coeffs()[0],
_ => panic!("not a live rectangle"),
};
select(&mut s, &[a, b]);
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap();
s.execute(cmd, &p).unwrap();
assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", radius(&s));
let (id, q) = s.journal.last().unwrap().clone();
assert_eq!(id, cmd);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap();
select(&mut s, &[a, b]);
s.replay(&id, &q).unwrap();
assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", radius(&s));
}
#[test]
fn match_replays_with_the_corner_scaling_it_ran_with() {
replays_the_corner_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
}
#[test]
fn set_size_of_each_replays_with_the_corner_scaling_it_ran_with() {
replays_the_corner_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20}));
}
#[test]
fn swap_replays_with_the_corner_scaling_it_ran_with() {
replays_the_corner_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
}
#[test]
fn match_stacking_leaves_a_clipping_path_in_place() {
let mut s = session();
@@ -603,6 +776,16 @@ fn match_size_refuses_a_target_with_no_width() {
assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line));
}
#[test]
fn match_size_refuses_a_target_with_no_width_for_a_narrow_tall_source() {
let mut s = session();
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
let b = rect(&mut s, 100.0, 0.0, 0.05, 100000.0);
select(&mut s, &[line, b]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both"})]);
}
#[test]
fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() {
let mut s = session();
@@ -689,6 +872,234 @@ fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() {
assert!(*s.doc().unwrap().doc == *before);
}
#[test]
fn match_refuses_restacking_into_a_locked_container() {
for lock_ancestor in [false, true] {
let mut s = session();
let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
select(&mut s, &[source]);
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[group]);
let ancestor = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
select(&mut s, &[source, target]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let locked = if lock_ancestor { ancestor } else { group };
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(locked).unwrap().locked = true;
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let e = s.execute("addon.arrange.match", &json!({"size": "both", "stacking": true})).unwrap_err();
assert!(e.to_string().contains("the layer or group is locked"), "{e}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
}
}
#[test]
fn match_refuses_restacking_among_a_blends_inputs() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
s.execute("object.blend.make", &json!({})).unwrap();
let target = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, target]);
s.execute("select.key", &json!({"id": a.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
assert!(e.to_string().contains("can't go beside the source object"), "{e}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
}
#[test]
fn match_refuses_taking_a_target_out_of_a_locked_container() {
let mut s = session();
let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
select(&mut s, &[target]);
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
select(&mut s, &[source, target]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().locked = true;
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
assert!(e.to_string().contains("the layer or group is locked"), "{e}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
}
#[test]
fn match_refuses_taking_a_target_out_of_a_blend_but_restacks_the_whole_blend() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
let blend = NodeId(s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
let source = rect(&mut s, 250.0, 0.0, 20.0, 20.0);
assert_eq!(layer_order(&s), [blend, between, source]);
select(&mut s, &[a, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
assert!(e.to_string().contains("a blend's input objects"), "{e}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
select(&mut s, &[blend, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!(layer_order(&s), [between, source, blend]);
}
#[test]
fn match_refuses_restacking_live_paint_art_but_moves_beside_a_whole_group() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
select(&mut s, &[a, b]);
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
let target = rect(&mut s, 250.0, 0.0, 20.0, 20.0);
assert_eq!(layer_order(&s), [g, between, target]);
let member = s.doc().unwrap().doc.children(Some(g)).unwrap()[0].id;
select(&mut s, &[member, target]);
s.execute("select.key", &json!({"id": member.0})).unwrap();
let n = steps(&s);
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
assert!(e.to_string().contains("Live Paint art"), "{e}");
assert_eq!(steps(&s), n);
select(&mut s, &[g, target]);
s.execute("select.key", &json!({"id": g.0})).unwrap();
let before = s.doc().unwrap().doc.node(g).unwrap().clone();
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!(layer_order(&s), [g, target, between]);
assert_eq!(s.doc().unwrap().doc.node(g).unwrap(), &before);
}
#[test]
fn match_turns_art_with_a_moving_effect_about_its_measured_point() {
let mut s = session();
s.prefs.use_preview_bounds = true;
let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0);
select(&mut s, &[a]);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
s.execute("effect.apply", &json!({"ids": [b.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap();
let center = |s: &Session| {
let bx = s.transform_box(&[b]).unwrap();
bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4)
};
let before = center(&s);
select(&mut s, &[a, b]);
s.execute("select.key", &json!({"id": a.0})).unwrap();
s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap();
let after = center(&s);
assert!((after - before).hypot() < 1e-6, "{before:?} -> {after:?}");
}
#[test]
fn match_checks_a_pixel_aligned_symbols_measured_point_after_snapping() {
for size in ["none", "both"] {
for dx in [0.0, 0.25] {
let mut s = session();
s.prefs.use_preview_bounds = true;
let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0);
let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
select(&mut s, &[art]);
let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap());
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
s.execute("object.move", &json!({"dx": dx})).unwrap();
s.execute("effect.apply", &json!({"ids": [target.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap();
let center = |s: &Session| {
let b = s.transform_box(&[target]).unwrap();
b.to_doc() * vectorcraft_geom::reference_point(b.rect, 4)
};
let at = center(&s);
select(&mut s, &[source, target]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let result = s.execute("addon.arrange.match", &json!({"rotate": true, "size": size}));
if dx == 0.0 {
result.unwrap();
assert!((center(&s) - at).hypot() < 1e-6, "{size}");
let b = s.transform_box(&[target]).unwrap();
assert!(b.angle.abs() < 1e-6, "{size}: {b:?}");
if size == "both" {
let wanted = s.transform_box(&[source]).unwrap();
assert!((b.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {b:?}");
assert!((b.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {b:?}");
}
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
} else {
let error = result.unwrap_err().to_string();
assert!(error.contains("can't keep its size and reference point as it turns"), "{size}: {error}");
}
assert_eq!(steps(&s), n, "{size}, dx={dx}");
assert!(*s.doc().unwrap().doc == *before, "{size}, dx={dx}");
}
}
}
#[test]
fn match_refuses_when_snapping_moves_a_pixel_aligned_symbol_instance_without_preview_bounds() {
let mut s = session();
s.prefs.use_preview_bounds = false;
let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0);
let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
select(&mut s, &[art]);
let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap());
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
s.execute("object.move", &json!({"dx": 0.25})).unwrap();
select(&mut s, &[source, target]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
// Turned back to its natural angle, the instance snaps to whole points, which moves its center.
let error = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string();
assert!(error.contains("can't keep its size and reference point as it turns"), "{error}");
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before);
}
#[test]
fn match_turns_art_with_a_moving_fill_effect_about_its_measured_point() {
for grouped in [false, true] {
let mut s = session();
s.prefs.use_preview_bounds = true;
let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0);
select(&mut s, &[a]);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
s.execute("effect.apply", &json!({"ids": [b.0], "item": 0, "effect": "distort.transform", "params": {"moveH": 30}})).unwrap();
let b = if grouped {
select(&mut s, &[b]);
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
} else {
b
};
let center = |s: &Session| {
let bx = s.transform_box(&[b]).unwrap();
bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4)
};
let before = center(&s);
select(&mut s, &[a, b]);
s.execute("select.key", &json!({"id": a.0})).unwrap();
s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap();
let after = center(&s);
assert!((after - before).hypot() < 1e-6, "grouped={grouped}: {before:?} -> {after:?}");
let d = &s.doc().unwrap().doc;
assert!((d.bbox_angle(&[b]) - d.bbox_angle(&[a])).abs() < 1e-6);
}
}
#[test]
fn match_replays_with_the_stroke_scaling_it_ran_with() {
replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
@@ -704,6 +1115,169 @@ fn swap_replays_with_the_stroke_scaling_it_ran_with() {
replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
}
/// Running `cmd` with Scale Corners on scales the 2 pt corners of two rounded squares with them,
/// and replaying its journal entry after the preference is turned off scales them the same way.
fn replays_the_corner_shapes_it_ran_with(cmd: &str, p: Value) {
let mut s = session();
let square = |s: &mut Session, x: f64, w: f64| {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": w, "height": w, "radius": 2})).unwrap()["id"].as_u64().unwrap())
};
let a = square(&mut s, 0.0, 10.0);
let b = square(&mut s, 100.0, 20.0);
let shapes = |s: &Session| {
let mut out = vec![];
s.doc().unwrap().doc.walk(|n| out.push(format!("{:?}", n.kind)));
out.sort();
out
};
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap();
select(&mut s, &[a, b]);
s.execute(cmd, &p).unwrap();
let ran = shapes(&s);
let (id, q) = s.journal.last().unwrap().clone();
assert_eq!(id, cmd);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap();
select(&mut s, &[a, b]);
s.replay(&id, &q).unwrap();
assert_eq!(shapes(&s), ran, "{cmd} replayed with other corners");
}
#[test]
fn match_replays_two_rounded_squares_with_the_corners_it_ran_with() {
replays_the_corner_shapes_it_ran_with("addon.arrange.match", json!({"size": "both"}));
}
#[test]
fn set_size_of_each_replays_two_rounded_squares_with_the_corners_it_ran_with() {
replays_the_corner_shapes_it_ran_with("addon.arrange.size", json!({"width": 30, "height": 30}));
}
#[test]
fn swap_replays_two_rounded_squares_with_the_corners_it_ran_with() {
replays_the_corner_shapes_it_ran_with("addon.arrange.swap", json!({"size": true}));
}
#[test]
fn replace_replays_with_the_corner_scaling_it_ran_with() {
replays_the_corner_shapes_it_ran_with("addon.arrange.replace", json!({"fit": "bounds"}));
}
#[test]
fn match_size_reaches_a_size_that_pixel_alignment_then_snaps() {
let mut s = session();
let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[target]);
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
let source = rect(&mut s, 100.0, 0.0, 15.5, 15.5);
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "width"})).unwrap();
let b = bounds(&s, target);
assert!((b.width() - 15.5).abs() <= 1.0 && (b.height() - 15.5).abs() <= 1.0, "{b:?}");
}
#[test]
fn match_size_fits_a_transform_copy_once_the_target_is_turned() {
for size in ["width", "both"] {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap();
let source = rect(&mut s, 100.0, 0.0, 30.0, 20.0);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
let wanted = s.transform_box(&[source]).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": size, "rotate": true, "scaleStrokes": false})).unwrap();
let measured = s.transform_box(&[target]).unwrap();
assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}");
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}");
if size == "both" {
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}");
}
}
}
#[test]
fn match_size_fits_a_turned_target_whose_copy_fills_the_height_before_the_turn() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveV": 10, "copies": 1}})).unwrap();
let source = rect(&mut s, 100.0, 0.0, 20.0, 5.0);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
let wanted = s.transform_box(&[source]).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap();
let measured = s.transform_box(&[target]).unwrap();
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}");
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}");
}
#[test]
fn match_size_keeps_the_center_of_a_turned_target_whose_copy_stays_on_the_page() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let target = rect(&mut s, 0.0, 0.0, 2000.0, 20.0);
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap();
let center = s.transform_box(&[target]).unwrap().center();
let source = rect(&mut s, 100.0, 100.0, 11.0, 20.0);
s.execute("object.rotate", &json!({"angle": 180})).unwrap();
let wanted = s.transform_box(&[source]).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap();
let measured = s.transform_box(&[target]).unwrap();
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}");
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}");
assert!((measured.center() - center).hypot() < 1e-6, "{measured:?} {center:?}");
}
#[test]
fn match_size_refuses_a_width_below_a_fixed_transform_copy() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 100000.05, "copies": 1}})).unwrap();
let before = s.transform_box(&[target]).unwrap();
assert!((before.rect.width() - 100020.05).abs() < 1e-6, "{before:?}");
let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0);
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let out = s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false}));
assert!(out.is_err(), "{out:?} {:?}", s.transform_box(&[target]));
}
#[test]
fn match_size_refuses_dimensions_a_fixed_rotated_copy_cannot_reach_together() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.execute(
"effect.apply",
&json!({"effect": "distort.transform", "item": null, "params": {"rotate": 90, "reference": 4, "moveH": 99990.05, "copies": 1}}),
)
.unwrap();
let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0);
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]);
}
#[test]
fn match_size_takes_a_huge_object_down_to_a_point() {
let mut s = session();
let target = rect(&mut s, 0.0, 0.0, 20000.0, 20000.0);
let source = rect(&mut s, 100.0, 0.0, 1.0, 1.0);
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
let b = bounds(&s, target);
assert!((b.width() - 1.0).abs() < 1e-6 && (b.height() - 1.0).abs() < 1e-6, "{b:?}");
}
#[test]
fn match_refuses_bad_params() {
let mut s = session();
+5 -3
View File
@@ -1,9 +1,10 @@
//! Artwork Cleanup (`addon.cleanup.*`), a built-in add-on: Simplify Anchors (Keep Shape), the
//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup and Rejoin Path
//! Pieces, and its text tools ([`text`]). Its panel and its submenu, Object › Plug-ins › Artwork
//! Cleanup, are the UI's.
//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup, Release All
//! Containers ([`release`]) and Rejoin Path Pieces, and its text tools ([`text`]). Its panel and
//! its submenu, Object › Plug-ins › Artwork Cleanup, are the UI's.
mod checks;
mod release;
#[cfg(test)]
mod tests;
mod text;
@@ -87,6 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
rejoin
),
];
v.extend(release::specs());
v.extend(text::specs());
v
}
@@ -0,0 +1,422 @@
//! Artwork Cleanup's Release All Containers (`addon.cleanup.releaseAll`): every group, clipping
//! mask and compound path in the selection, the objects named or the whole document, taken apart
//! at every level of nesting as one undo step, so that only the objects they held are left.
#[cfg(test)]
mod tests;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, LiveShape, LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_tools::builder::is_live_paint;
use super::checks::{MAX_OBJECTS, Scope};
use super::{named, retain_targets, scope_of};
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
use crate::{EngineError, Result, Session};
/// The command.
const COMMAND: &str = "addon.cleanup.releaseAll";
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.cleanup.releaseAll",
"Release All Containers…",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{scope?: \"selection\"|\"document\" (default: the selection, or the document while nothing is selected), ids?: [id…] (the objects, groups and layers to release in, instead of `scope`; duplicate ids are an error), groups?: bool (true: groups are ungrouped), clipGroups?: bool (true: clipping groups are ungrouped and layers stop clipping unless their clipping path or clipped artwork overlaps a locked artboard, their released clipping paths kept as plain paths), compoundPaths?: bool (true: compound paths, and paths of several subpaths, become one path per subpath); at least one of the three true; `scope` and the three are never null} take apart every container of the kinds asked for, at every level of nesting, as one undo step when one goes; layers stay; each object keeps the opacity of the groups and compound paths it was in, and a compound path's paths take its paint; objects with live effects on their appearance or fill and stroke rows, groups with fill or stroke rows of their own, objects with an opacity mask, compound shapes, Live Paint groups, graphs, dimensions, flares, Objects on Path, generated art, Shaper Groups, Image Trace objects, paths with Live Corners, blends, envelopes, repeats, intertwines and other live objects stay whole, including directly selected or named descendants; the entire clipping mask subtree of a clipping group or layer that stays is left as it is, including directly selected or named descendants; from the selection or the document, locked and hidden objects, and objects on a locked artboard, stay whole; named by `ids`, locked and hidden ones are taken apart too (their objects become locked or hidden as they were), but not those on a locked artboard; the selection keeps what it held, each object taken apart replaced by what it left, locked and hidden objects left out → {scope (\"selection\", \"document\" or \"ids\"), ids (the objects selected), groups, clipGroups, compoundPaths (how many of each were released)}",
has_doc,
release_all
)]
}
/// The kinds of container a request takes apart.
#[derive(Clone, Copy)]
struct Kinds {
groups: bool,
clips: bool,
compounds: bool,
}
impl Kinds {
/// Whether a group is taken apart: a clipping group (`clip`) with `clips`, another with `groups`.
fn takes_group(self, clip: bool) -> bool {
if clip { self.clips } else { self.groups }
}
}
/// One run over the objects: what it takes apart and what it found.
struct Release<'a> {
kinds: Kinds,
/// Locked and hidden objects are taken apart too.
named: bool,
/// The artwork on a locked artboard, which stays whole.
held: &'a HashSet<NodeId>,
/// Groups, clipping groups and layers, and compound paths released.
counts: [usize; 3],
/// Objects made from the containers taken apart.
made: usize,
/// Each container taken apart and the objects left in its place.
left: HashMap<NodeId, Vec<NodeId>>,
}
/// Whether `n` stays whole whatever is asked: a live object kept as a group or compound path
/// (a compound shape, Live Paint group, graph, dimension, flare, Objects on Path, generated art,
/// Shaper Group, Image Trace object, a clipping path's painted pieces), a path with Live Corners,
/// whose parts would lose their editable corners, one with an opacity mask or live effects
/// on its appearance or fill and stroke rows, or a group with fill or stroke rows of its own.
fn live(n: &Node) -> bool {
let x = n.extras();
matches!(&n.kind, NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. })
|| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. }))
|| !n.appearance.effects.is_empty()
|| n.appearance.items.iter().any(|item| !item.effects().is_empty())
|| x.mask.is_some()
|| x.shaper.is_some()
|| x.trace.is_some()
|| x.graph.is_some()
|| x.dimension.is_some()
|| x.flare.is_some()
|| x.objects_on_path.is_some()
|| x.generated.is_some()
|| x.live_paint_gaps.is_some()
|| x.clip_pieces
|| (matches!(&n.kind, NodeKind::Group { .. }) && !n.appearance.items.is_empty())
|| n.is_compound_shape()
|| is_live_paint(n)
}
/// The artwork under `n` is added to `out`.
fn candidates(n: &Node, clips: bool, out: &mut Vec<NodeId>) {
let candidate = match &n.kind {
NodeKind::Layer { .. } => false,
NodeKind::Group { .. } | NodeKind::Compound { .. } => true,
NodeKind::Path { path, .. } => clips || path.subpaths.len() > 1,
_ => clips,
};
if candidate {
out.push(n.id);
}
if let Some(children) = n.children() {
children.iter().for_each(|c| candidates(c, clips, out));
}
}
impl Release<'_> {
fn total(&self) -> usize {
self.counts.iter().sum()
}
/// Whether `n` is left as it is: locked or hidden (unless named), on a locked artboard, or live.
fn keeps(&self, n: &Node) -> bool {
(!self.named && (n.locked || !n.visible)) || self.held.contains(&n.id) || live(n)
}
/// `n` with the containers in it released, into `out`; `member` counts what a container left.
fn node(&mut self, d: &mut Document, n: Arc<Node>, member: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
if self.keeps(&n) {
if member {
self.made(1)?;
}
out.push(n);
return Ok(());
}
match &n.kind {
NodeKind::Group { clip, .. } if self.kinds.takes_group(*clip) => {
let clip = *clip;
self.counts[usize::from(clip)] += 1;
self.take_apart(d, n, clip, false, out)
}
NodeKind::Compound { .. } if self.kinds.compounds => {
self.counts[2] += 1;
self.take_apart(d, n, false, true, out)
}
NodeKind::Path { path, clipping: false, guide: false, .. } if self.kinds.compounds && path.subpaths.len() > 1 => {
self.counts[2] += 1;
self.split(d, (*n).clone(), out)
}
NodeKind::Group { .. } | NodeKind::Layer { .. } => self.keep(d, n, member, out),
_ => {
if member {
self.made(1)?;
}
out.push(n);
Ok(())
}
}
}
/// Group or compound path `n` replaced by its members, released in turn. Members take on the
/// container's opacity, are hidden when it was hidden and locked when it was locked; a
/// compound path's take its paint; a clipping group's clipping path becomes a plain path.
fn take_apart(&mut self, d: &mut Document, n: Arc<Node>, clip: bool, compound: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
let Some(children) = n.children() else { return Ok(()) };
let mut parts = vec![];
for (k, c) in children.iter().enumerate() {
let mut c = (**c).clone();
if clip
&& k == 0
&& let NodeKind::Path { clipping, .. } = &mut c.kind
{
*clipping = false;
}
if compound {
c.appearance = n.appearance.clone();
if n.extras().pixel_aligned {
c.extras_mut().pixel_aligned = true;
}
}
c.opacity *= n.opacity;
c.visible &= n.visible;
c.locked |= n.locked;
self.node(d, Arc::new(c), true, &mut parts)?;
}
self.left.insert(n.id, parts.iter().map(|p| p.id).collect());
out.extend(parts);
Ok(())
}
/// Path `n` of several subpaths as one path per subpath with its paint, in the same stacking
/// order; the first keeps its id.
fn split(&mut self, d: &mut Document, n: Node, out: &mut Vec<Arc<Node>>) -> Result<()> {
let Some(path) = n.path_data() else { return Ok(()) };
if self.made.saturating_add(path.subpaths.len()) > MAX_OBJECTS {
return Err(EngineError::Other("Release All Containers: too many objects to release at once".into()));
}
let mut template = n.clone();
if let NodeKind::Path { path, live, .. } = &mut template.kind {
(*path, *live) = (PathData::single(Default::default()), None);
}
let mut parts = Vec::with_capacity(path.subpaths.len());
for (k, sp) in path.subpaths.iter().enumerate() {
let mut c = if k == 0 { template.clone() } else { d.reid(&template) };
if let NodeKind::Path { path, live, .. } = &mut c.kind {
(*path, *live) = (PathData::single(sp.clone()), None);
}
parts.push(Arc::new(c));
}
self.made(parts.len())?;
self.left.insert(n.id, parts.iter().map(|p| p.id).collect());
out.extend(parts);
Ok(())
}
/// Group or layer `n` kept, with the containers in it released. A layer stops clipping when
/// clipping groups are released; the clipping path of a group or layer that still clips is
/// left as it is. Unchanged, `n` itself goes to `out`.
fn keep(&mut self, d: &mut Document, mut n: Arc<Node>, member: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
if member {
self.made(1)?;
}
let before = self.total();
let mut clips = n.clips();
if clips && n.is_layer() && self.kinds.clips && !n.children().is_some_and(|children| children.iter().any(|c| self.holds_art(c))) {
self.counts[1] += 1;
let n = Arc::make_mut(&mut n);
n.set_clips(false);
clips = false;
if let Some(first) = n.children_mut().and_then(|c| c.first_mut())
&& let NodeKind::Path { clipping, .. } = &mut Arc::make_mut(first).kind
{
*clipping = false;
}
}
let Some(children) = n.children() else {
out.push(n);
return Ok(());
};
let mut kept = Vec::with_capacity(children.len());
for (k, c) in children.iter().enumerate() {
if clips && k == 0 {
if member {
self.made(1)?;
}
kept.push(Arc::clone(c));
} else {
self.node(d, Arc::clone(c), member, &mut kept)?;
}
}
if self.total() != before
&& let Some(ch) = Arc::make_mut(&mut n).children_mut()
{
*ch = kept;
}
out.push(n);
Ok(())
}
fn holds_art(&self, n: &Node) -> bool {
self.held.contains(&n.id) || n.children().is_some_and(|children| children.iter().any(|c| self.holds_art(c)))
}
/// Counts the objects made, refusing a run that makes too many.
fn made(&mut self, count: usize) -> Result<()> {
self.made += count;
if self.made > MAX_OBJECTS {
return Err(EngineError::Other("Release All Containers: too many objects to release at once".into()));
}
Ok(())
}
/// `id`, or the objects left in its place when it was taken apart.
fn replaced(&self, id: NodeId, into: &mut Vec<NodeId>) {
match self.left.get(&id) {
Some(ids) => into.extend(ids),
None => into.push(id),
}
}
}
/// Whether shown artwork in `n` overlaps a locked artboard: a plain group that is not live
/// ([`live`]) by its shown members, anything else by its own bounds.
fn shows_on(locks: &LockedArtboards<'_>, n: &Node) -> bool {
if !n.visible {
return false;
}
match (&n.kind, n.children()) {
(NodeKind::Group { clip: false, .. }, Some(children)) if !live(n) => children.iter().any(|c| shows_on(locks, c)),
_ => locks.holds(n),
}
}
/// Whether `id` is in the clipping mask subtree of a clipping group or layer.
fn in_clipping_mask(d: &Document, id: NodeId) -> bool {
d.ancestry(id).is_some_and(|chain| {
chain
.windows(2)
.any(|pair| d.node(pair[0]).is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == pair[1])))
})
}
fn release_all(s: &mut Session, p: &Value) -> Result<Value> {
if !p.is_object() {
return Err(bad(COMMAND, "parameters must be an object"));
}
for key in ["groups", "clipGroups", "compoundPaths"] {
if p.get(key).is_some_and(|v| !v.is_boolean()) {
return Err(bad(COMMAND, format!("`{key}` must be true or false")));
}
}
if p.get("scope").is_some_and(|v| !matches!(v.as_str(), Some("selection" | "document"))) {
return Err(bad(COMMAND, "`scope` must be \"selection\" or \"document\""));
}
if let Some(ids) = p.get("ids").filter(|v| !v.is_null()) {
let ids = ids.as_array().ok_or_else(|| bad(COMMAND, "`ids` must be an array of non-negative integer object ids"))?;
let mut seen = HashSet::new();
for id in ids {
let id = id.as_u64().ok_or_else(|| bad(COMMAND, "`ids` must contain non-negative integer object ids"))?;
if !seen.insert(id) {
return Err(bad(COMMAND, format!("duplicate object id {id} in `ids`")));
}
}
}
let kinds = Kinds {
groups: switch_or(p, "groups", true, COMMAND)?,
clips: switch_or(p, "clipGroups", true, COMMAND)?,
compounds: switch_or(p, "compoundPaths", true, COMMAND)?,
};
if !(kinds.groups || kinds.clips || kinds.compounds) {
return Err(bad(COMMAND, "`groups`, `clipGroups` and `compoundPaths` are all false: there is nothing to release"));
}
let named = named(p);
if named && p.get("scope").is_some() {
return Err(bad(COMMAND, "give `scope` or `ids`, not both"));
}
let (roots, name) = if named {
let mut roots = checked_ids_or_selection(s, p, COMMAND)?;
retain_targets(&s.doc()?.doc, &mut roots, true, |id| *id);
(roots, "ids")
} else {
match scope_of(s, p, COMMAND)? {
(Scope::Document, name) => (s.doc()?.doc.layers.iter().map(|l| l.id).collect(), name),
(Scope::Objects(mut roots), name) => {
retain_targets(&s.doc()?.doc, &mut roots, false, |id| *id);
(roots, name)
}
}
};
let st = s.doc()?;
let (mut d, mut sel) = ((*st.doc).clone(), st.selection.clone());
// The artwork on a locked artboard, found while nothing is changed yet.
let held: HashSet<NodeId> = if d.artboards.iter().any(|a| a.locked) {
let mut found = vec![];
for n in roots.iter().filter_map(|id| d.node(*id)) {
candidates(n, kinds.clips, &mut found);
}
let locks = d.locked_artboards();
let mut held: HashSet<NodeId> = found.iter().copied().filter(|id| locks.holds_id(*id)).collect();
// A shown clipping group whose clipped artwork overlaps a locked artboard stays whole,
// wherever its clipping path lies, when clipping groups are released; the clipping groups
// the targets are in count too.
let ancestors = roots.iter().filter_map(|id| d.ancestry(*id)).flatten();
let clip_groups: HashSet<NodeId> = found
.iter()
.copied()
.chain(ancestors)
.filter(|id| kinds.clips && d.node(*id).is_some_and(|n| matches!(&n.kind, NodeKind::Group { clip: true, .. })))
.collect();
// Pattern editing mode's art is on no artboard.
let pattern_layer = d.pattern_edit.as_ref().map(|e| e.layer);
for id in clip_groups {
let shown = d.ancestry(id).is_some_and(|chain| chain.iter().all(|a| Some(*a) != pattern_layer && d.node(*a).is_some_and(|n| n.visible)));
if shown
&& let Some(n) = d.node(id)
&& n.children().is_some_and(|c| c.iter().skip(1).any(|c| shows_on(&locks, c)))
{
held.insert(id);
}
}
held
} else {
HashSet::new()
};
let mut run = Release { kinds, named, held: &held, counts: [0; 3], made: 0, left: HashMap::new() };
let mut items = vec![];
for id in roots {
// Direct targets inside a live object or clipping mask stay whole.
let protected =
d.ancestry(id).is_some_and(|chain| chain.iter().take(chain.len().saturating_sub(1)).filter_map(|id| d.node(*id)).any(|n| run.keeps(n)));
if in_clipping_mask(&d, id) || protected {
continue;
}
let Some(n) = d.node_arc(id).cloned() else { continue };
let before = run.total();
let mut out = vec![];
run.node(&mut d, n, false, &mut out)?;
if run.total() != before {
items.push((id, out.into_iter().map(Arc::unwrap_or_clone).collect()));
}
}
let [groups, clips, compounds] = run.counts;
// With nothing to release, the document, the selection and the undo history stay as they are.
if run.total() == 0 {
let ids: Vec<u64> = sel.objects.iter().map(|i| i.0).collect();
return Ok(json!({ "scope": name, "ids": ids, "groups": 0, "clipGroups": 0, "compoundPaths": 0 }));
}
d.insert_beside(items, true)?;
let mut ids = vec![];
for id in sel.objects.iter() {
run.replaced(*id, &mut ids);
}
// Locked and hidden objects, and those in locked or hidden groups, are not selected.
{
let editable = d.editable();
ids.retain(|id| editable(*id));
}
let kept: HashSet<NodeId> = ids.iter().copied().collect();
let removed: Vec<NodeId> = sel.objects.iter().copied().filter(|id| run.left.contains_key(id) || !kept.contains(id)).collect();
sel.remove_all(removed);
let mut seen = HashSet::new();
sel.objects = ids.into_iter().filter(|id| seen.insert(*id)).collect();
sel.prune(&d);
let ids: Vec<u64> = sel.objects.iter().map(|i| i.0).collect();
s.edit("Release All Containers", |doc, selection| {
*doc = d;
*selection = sel;
Ok(())
})?;
Ok(json!({ "scope": name, "ids": ids, "groups": groups, "clipGroups": clips, "compoundPaths": compounds }))
}
@@ -0,0 +1,860 @@
//! Release All Containers: every level taken apart as one undo step, the kinds asked for only,
//! the selection, the document and named objects, clipping layers, what stays whole, and refusals.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, LiveShape, Node, NodeId, NodeKind};
use crate::Session;
const C: &str = "addon.cleanup.releaseAll";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64, y: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap())
}
fn node(s: &Session, id: NodeId) -> Option<Node> {
s.doc().unwrap().doc.node(id).cloned()
}
fn change(s: &mut Session, id: NodeId, f: impl FnOnce(&mut Node)) {
s.edit("t", |d, _| {
f(d.node_mut(id).unwrap());
Ok(())
})
.unwrap();
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.select(|_, sel| sel.set(ids.iter().copied())).unwrap();
}
fn selected(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().selection.objects.to_vec()
}
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
/// The objects directly in layer `k`.
fn layer(s: &Session, k: usize) -> Vec<NodeId> {
s.doc().unwrap().doc.layers[k].children().unwrap().iter().map(|n| n.id).collect()
}
fn group(s: &mut Session, ids: &[NodeId]) -> NodeId {
select(s, ids);
id_of(&s.execute("object.group", &json!({})).unwrap())
}
fn compound(s: &mut Session, ids: &[NodeId]) -> NodeId {
select(s, ids);
id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap())
}
/// A clipping group of `ids`, the last of them the clipping path.
fn clip_group(s: &mut Session, ids: &[NodeId]) -> NodeId {
select(s, ids);
id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap())
}
fn counts(r: &Value) -> (u64, u64, u64) {
(r["groups"].as_u64().unwrap(), r["clipGroups"].as_u64().unwrap(), r["compoundPaths"].as_u64().unwrap())
}
fn plain(s: &Session, id: NodeId) -> bool {
matches!(node(s, id).unwrap().kind, NodeKind::Path { clipping: false, ref path, .. } if path.subpaths.len() == 1)
}
fn red() -> Appearance {
Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 1.0)
}
#[test]
fn release_all_takes_apart_every_level_as_one_step() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let p = rect(&mut s, 70.0, 10.0);
let q = rect(&mut s, 75.0, 15.0);
let holes = compound(&mut s, &[p, q]);
change(&mut s, holes, |n| n.appearance = red().into());
let inner = group(&mut s, &[b, holes]);
change(&mut s, inner, |n| n.opacity = 0.5);
let clipped = rect(&mut s, 110.0, 10.0);
let clip = rect(&mut s, 105.0, 5.0);
let masked = clip_group(&mut s, &[clipped, clip]);
let outer = group(&mut s, &[a, inner, masked]);
select(&mut s, &[outer]);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(counts(&r), (2, 1, 1), "{r}");
assert_eq!(r["scope"], "selection");
assert_eq!(undo_steps(&s), steps + 1, "one undo step");
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Release All Containers");
assert_eq!(layer(&s, 0), [a, b, p, q, clip, clipped], "only paths are left, in their stacking order");
assert!([a, b, p, q, clip, clipped].iter().all(|id| plain(&s, *id)), "the clipping path is a plain path");
assert!(node(&s, outer).is_none() && node(&s, inner).is_none() && node(&s, holes).is_none() && node(&s, masked).is_none());
assert_eq!((node(&s, b).unwrap().opacity, node(&s, p).unwrap().opacity), (0.5, 0.5), "members keep their groups' opacity");
assert_eq!(*node(&s, q).unwrap().appearance, red(), "a compound path's paths take its paint");
assert_eq!(selected(&s), [a, b, p, q, clip, clipped], "what the selected group left is selected");
assert_eq!(r["ids"], json!([a.0, b.0, p.0, q.0, clip.0, clipped.0]));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer(&s, 0), [outer]);
}
#[test]
fn release_all_counts_each_object_left_once() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let c = rect(&mut s, 70.0, 10.0);
let p = rect(&mut s, 100.0, 10.0);
let second = node(&s, p).unwrap().path_data().unwrap().subpaths[0].clone();
change(&mut s, p, |n| {
if let NodeKind::Path { path, .. } = &mut n.kind {
path.subpaths.push(second);
}
});
let inner = group(&mut s, &[a, b, c, p]);
change(&mut s, inner, |n| n.set_clips(true));
let middle = group(&mut s, &[inner]);
let outer = group(&mut s, &[middle]);
let held = std::collections::HashSet::new();
for clips in [true, false] {
let mut d = (*s.doc().unwrap().doc).clone();
let n = d.node_arc(outer).unwrap().clone();
let mut run = super::Release {
kinds: super::Kinds { groups: true, clips, compounds: true },
named: false,
held: &held,
counts: [0; 3],
made: 0,
left: std::collections::HashMap::new(),
};
let mut out = vec![];
run.node(&mut d, n, false, &mut out).unwrap();
if clips {
assert_eq!(out.len(), 5);
assert_eq!(run.made, out.len(), "each path is counted once");
} else {
assert_eq!(out.len(), 1);
let children = out[0].children().unwrap();
assert_eq!(children.len(), 5);
assert_eq!(run.made, out.len() + children.len(), "the kept group and its paths are counted once");
}
}
}
#[test]
fn release_all_takes_only_the_kinds_asked_for() {
let mut s = session();
let p = rect(&mut s, 10.0, 10.0);
let q = rect(&mut s, 15.0, 15.0);
let holes = compound(&mut s, &[p, q]);
let clipped = rect(&mut s, 110.0, 10.0);
let e = rect(&mut s, 105.0, 5.0);
let f = rect(&mut s, 108.0, 8.0);
let clip = compound(&mut s, &[e, f]);
let masked = clip_group(&mut s, &[clipped, clip]);
let outer = group(&mut s, &[holes, masked]);
// Without groups, the group stays and what is inside it is still released, but for the
// clipping path of the clipping group that stays.
select(&mut s, &[outer]);
let r = s.execute(C, &json!({"groups": false, "clipGroups": false})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "{r}");
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(p), Some(outer));
assert!(d.node(holes).is_none() && d.node(clip).is_some() && d.node(masked).is_some());
assert_eq!(selected(&s), [outer]);
// Without compound paths, the groups go and the compound path stays.
let r = s.execute(C, &json!({"compoundPaths": false})).unwrap();
assert_eq!(counts(&r), (1, 1, 0), "{r}");
assert_eq!(layer(&s, 0), [p, q, clip, clipped]);
assert!(matches!(node(&s, clip).unwrap().kind, NodeKind::Compound { .. }));
// Then only compound paths: the clipping path's paths, unpainted as it was.
select(&mut s, &[clip]);
let r = s.execute(C, &json!({"groups": false, "clipGroups": false})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "{r}");
assert_eq!(layer(&s, 0), [p, q, e, f, clipped]);
}
#[test]
fn release_all_splits_paths_of_several_subpaths() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let second = node(&s, b).unwrap().path_data().unwrap().subpaths[0].clone();
change(&mut s, a, |n| {
if let NodeKind::Path { path, .. } = &mut n.kind {
path.subpaths.push(second);
}
});
s.edit("t", |d, _| Ok(d.remove_many(&[b])?)).unwrap();
select(&mut s, &[a]);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "{r}");
let left = layer(&s, 0);
assert_eq!(left.len(), 2);
assert_eq!(left[0], a, "the first subpath keeps the path's id");
assert!(left.iter().all(|id| plain(&s, *id)));
assert_eq!(selected(&s), left);
assert_eq!(node(&s, left[1]).unwrap().appearance, node(&s, a).unwrap().appearance, "each part keeps the path's paint");
}
#[test]
fn release_all_keeps_a_path_of_several_subpaths_with_live_corners_whole() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let plain_path = rect(&mut s, 80.0, 10.0);
let second = node(&s, b).unwrap().path_data().unwrap().subpaths[0].clone();
for id in [a, plain_path] {
let second = second.clone();
change(&mut s, id, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
path.subpaths.push(second);
*live = None;
}
});
}
change(&mut s, a, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
let base = path.clone();
*live = Some(Box::new(LiveShape::Path { base, radii: vec![4.0], kinds: vec![], radii_relative: false }));
}
});
s.edit("t", |d, _| Ok(d.remove_many(&[b])?)).unwrap();
select(&mut s, &[a, plain_path]);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "only the plain path is split: {r}");
let kept = node(&s, a).unwrap();
assert!(matches!(kept.kind, NodeKind::Path { live: Some(_), ref path, .. } if path.subpaths.len() == 2), "Live Corners stay");
assert_eq!(layer(&s, 0).len(), 3);
}
#[test]
fn release_all_runs_on_the_document_while_nothing_is_selected() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let c = rect(&mut s, 70.0, 10.0);
let e = rect(&mut s, 100.0, 10.0);
let plain_group = group(&mut s, &[a]);
let locked = group(&mut s, &[b]);
change(&mut s, locked, |n| n.locked = true);
let hidden = group(&mut s, &[c]);
change(&mut s, hidden, |n| n.visible = false);
// A second layer that clips its art by its first path.
let second = id_of(&s.execute("layer.new", &json!({})).unwrap());
let mask = rect(&mut s, 0.0, 100.0);
let art = rect(&mut s, 10.0, 110.0);
let art_group = group(&mut s, &[art]);
s.edit("t", |d, _| {
let layer = d.node_mut(second).unwrap();
layer.set_clips(true);
if let Some(NodeKind::Path { clipping, .. }) = layer.children_mut().unwrap().first_mut().map(|c| &mut std::sync::Arc::make_mut(c).kind) {
*clipping = true;
}
Ok(())
})
.unwrap();
select(&mut s, &[]);
assert!(s.execute(C, &json!({"scope": "selection"})).is_err(), "nothing selected");
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(r["scope"], "document");
assert_eq!(counts(&r), (2, 1, 0), "{r}");
assert_eq!(undo_steps(&s), steps + 1);
assert_eq!(layer(&s, 0), [a, locked, hidden, e], "locked and hidden groups stay whole");
assert!(node(&s, plain_group).is_none() && node(&s, art_group).is_none());
let d = &s.doc().unwrap().doc;
assert!(!d.node(second).unwrap().clips(), "the layer stays and stops clipping");
assert!(plain(&s, mask), "its clipping path is a plain path");
assert_eq!(layer(&s, 1), [mask, art]);
assert!(selected(&s).is_empty(), "nothing was selected");
// Asked for the document with a selection, the selection keeps what it held.
let g = group(&mut s, &[e]);
select(&mut s, &[g]);
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{r}");
assert_eq!(selected(&s), [e]);
}
#[test]
fn release_all_takes_named_locked_and_hidden_containers() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let locked = group(&mut s, &[a]);
change(&mut s, locked, |n| n.locked = true);
let hidden = group(&mut s, &[b]);
change(&mut s, hidden, |n| n.visible = false);
select(&mut s, &[locked, hidden]);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "from the selection, they stay whole");
let r = s.execute(C, &json!({"ids": [locked.0, hidden.0]})).unwrap();
assert_eq!(r["scope"], "ids");
assert_eq!(counts(&r), (2, 0, 0), "{r}");
assert_eq!(undo_steps(&s), steps + 1);
let (na, nb) = (node(&s, a).unwrap(), node(&s, b).unwrap());
assert!(na.locked && na.visible && !nb.visible && !nb.locked, "their objects become locked or hidden as they were");
assert!(selected(&s).is_empty(), "locked and hidden objects are not selected");
// On a locked artboard, a named group stays whole.
let c = rect(&mut s, 10.0, 200.0);
let on_board = group(&mut s, &[c]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let r = s.execute(C, &json!({"ids": [on_board.0]})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
assert!(node(&s, on_board).is_some());
// Nor does one inside a named layer.
let layer_id = s.doc().unwrap().doc.layers[0].id;
let r = s.execute(C, &json!({"ids": [layer_id.0]})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
}
#[test]
fn release_all_leaves_masked_groups_whole_and_changes_nothing_without_a_container() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 15.0, 15.0);
let held = group(&mut s, &[a, b]);
let m = rect(&mut s, 0.0, 0.0);
s.execute("transparency.makeOpacityMask", &json!({"ids": [held.0, m.0]})).unwrap();
let masked = layer(&s, 0)[0];
assert!(node(&s, masked).unwrap().extras().mask.is_some());
let c = rect(&mut s, 100.0, 10.0);
select(&mut s, &[masked, c]);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "no step when nothing is released");
assert_eq!(r["ids"], json!([masked.0, c.0]), "the selection stays");
assert_eq!(layer(&s, 0), [masked, c]);
// A compound shape is a group that stays whole too.
let e = rect(&mut s, 200.0, 10.0);
let f = rect(&mut s, 210.0, 15.0);
select(&mut s, &[e, f]);
s.execute("object.compoundShape.make", &json!({})).unwrap();
let shape = selected(&s)[0];
assert!(node(&s, shape).unwrap().is_compound_shape());
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
assert!(node(&s, shape).unwrap().is_compound_shape());
}
#[test]
fn release_all_leaves_a_picked_clipping_path_of_a_clipping_group_that_stays() {
let mut s = session();
let clipped = rect(&mut s, 10.0, 10.0);
let e = rect(&mut s, 5.0, 5.0);
let f = rect(&mut s, 8.0, 8.0);
let clip = compound(&mut s, &[e, f]);
let masked = clip_group(&mut s, &[clipped, clip]);
let steps = undo_steps(&s);
for p in [json!({"ids": [clip.0]}), json!({"ids": [clip.0], "clipGroups": false})] {
let r = s.execute(C, &p).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "{p}");
}
select(&mut s, &[clip]);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(clip), Some(masked));
assert!(matches!(d.node(clip).unwrap().kind, NodeKind::Compound { .. }));
}
#[test]
fn release_all_keeps_a_directly_named_descendant_of_a_live_object() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let inner = group(&mut s, &[a]);
let sources = group(&mut s, &[inner]);
change(&mut s, sources, |n| n.name = Some("Live Paint Sources".into()));
let live = group(&mut s, &[sources]);
change(&mut s, live, |n| n.name = Some("Live Paint Group".into()));
change(&mut s, sources, |n| n.visible = false);
assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, live).unwrap()));
let steps = undo_steps(&s);
for id in [sources, inner] {
let r = s.execute(C, &json!({"ids": [id.0]})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, live).unwrap()));
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(sources));
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(inner));
}
}
#[test]
fn release_all_keeps_appearance_effects_and_directly_targeted_descendants() {
for item in [None, Some(0), Some(1)] {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 15.0, 15.0);
let inner = compound(&mut s, &[a, b]);
let c = rect(&mut s, 20.0, 20.0);
select(&mut s, &[inner, c]);
let applied = s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap();
assert_eq!(applied["grouped"], true);
let live = selected(&s)[0];
assert!(matches!(node(&s, live).unwrap().kind, NodeKind::Group { clip: false, .. }));
assert!(!node(&s, live).unwrap().is_compound_shape());
assert_eq!(node(&s, live).unwrap().appearance.effects[0].id, "pathfinder.add");
if let Some(item) = item {
change(&mut s, live, |n| {
let effects = n.appearance.effects.clone();
*n.appearance = red();
*n.appearance.effects_mut(Some(item)).unwrap() = effects;
});
}
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for (target, params) in [
(live, json!({})),
(live, json!({"scope": "document"})),
(live, json!({"ids": [live.0]})),
(inner, json!({})),
(inner, json!({"ids": [inner.0]})),
] {
select(&mut s, &[target]);
let r = s.execute(C, &params).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{item:?}: {params}: {r}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), [target]);
assert_eq!(undo_steps(&s), steps);
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(live));
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(inner));
}
}
}
#[test]
fn release_all_keeps_a_layer_mask_over_locked_artboard_artwork() {
for named in [false, true] {
let mut s = session();
let mask = rect(&mut s, 0.0, 0.0);
let art = rect(&mut s, 10.0, 10.0);
let outside = rect(&mut s, 500.0, 10.0);
let g = group(&mut s, &[outside]);
let layer_id = s.doc().unwrap().doc.layers[0].id;
change(&mut s, layer_id, |n| n.set_clips(true));
change(&mut s, mask, |n| {
if let NodeKind::Path { clipping, .. } = &mut n.kind {
*clipping = true;
}
});
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let p = if named { json!({"ids": [layer_id.0]}) } else { json!({"scope": "document"}) };
let r = s.execute(C, &p).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{p}: {r}");
assert!(node(&s, layer_id).unwrap().clips());
assert!(matches!(node(&s, mask).unwrap().kind, NodeKind::Path { clipping: true, .. }));
assert_eq!(layer(&s, 0), [mask, art, outside]);
assert!(node(&s, g).is_none());
}
}
#[test]
fn release_all_keeps_a_layer_mask_that_alone_overlaps_a_locked_artboard() {
for named in [false, true] {
let mut s = session();
let mask = rect(&mut s, 0.0, 0.0);
let outside = rect(&mut s, 500.0, 10.0);
let g = group(&mut s, &[outside]);
let layer_id = s.doc().unwrap().doc.layers[0].id;
change(&mut s, layer_id, |n| n.set_clips(true));
change(&mut s, mask, |n| {
if let NodeKind::Path { clipping, .. } = &mut n.kind {
*clipping = true;
}
});
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let original_mask = s.doc().unwrap().doc.node_arc(mask).unwrap().clone();
let steps = undo_steps(&s);
let p = if named { json!({"ids": [layer_id.0]}) } else { json!({"scope": "document"}) };
let r = s.execute(C, &p).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{p}: {r}");
assert_eq!(undo_steps(&s), steps + 1);
assert!(node(&s, layer_id).unwrap().clips());
assert!(matches!(node(&s, mask).unwrap().kind, NodeKind::Path { clipping: true, .. }));
assert!(std::sync::Arc::ptr_eq(&original_mask, s.doc().unwrap().doc.node_arc(mask).unwrap()));
assert_eq!(layer(&s, 0), [mask, outside]);
assert!(node(&s, g).is_none());
}
}
#[test]
fn release_all_keeps_a_clipping_group_whose_clipped_art_overlaps_a_locked_artboard() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(g));
assert!(node(&s, g).unwrap().clips());
}
#[test]
fn release_all_keeps_a_named_group_in_a_clipping_group_over_a_locked_artboard() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let other = rect(&mut s, 40.0, 10.0);
let inner = group(&mut s, &[art, other]);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"ids": [inner.0]})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(inner));
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(g));
}
#[test]
fn release_all_takes_apart_a_named_hidden_clipping_group_with_visible_art() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
change(&mut s, g, |n| n.visible = false);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"ids": [g.0]})).unwrap();
assert_eq!(counts(&r), (0, 1, 0), "{r}");
assert!(node(&s, g).is_none());
assert!(!node(&s, art).unwrap().visible);
}
#[test]
fn release_all_takes_apart_a_clipping_group_in_a_named_hidden_group() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
let other = rect(&mut s, 40.0, 10.0);
let outer = group(&mut s, &[g, other]);
change(&mut s, outer, |n| n.visible = false);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"ids": [outer.0]})).unwrap();
assert_eq!(counts(&r), (1, 1, 0), "{r}");
assert!(node(&s, g).is_none());
}
#[test]
fn release_all_ignores_hidden_clipped_art_over_a_locked_artboard() {
let mut s = session();
let hidden = rect(&mut s, 10.0, 10.0);
let shown = rect(&mut s, 600.0, 10.0);
let inner = group(&mut s, &[hidden, shown]);
change(&mut s, hidden, |n| n.visible = false);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 1, 0), "{r}");
assert!(node(&s, g).is_none());
assert!(!node(&s, hidden).unwrap().visible);
}
#[test]
fn release_all_keeps_a_clipping_group_whose_group_stroke_reaches_a_locked_artboard() {
let mut s = session();
let a = rect(&mut s, 600.0, 10.0);
let b = rect(&mut s, 640.0, 10.0);
let inner = group(&mut s, &[a, b]);
change(&mut s, inner, |n| n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 500.0).into());
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(g));
}
#[test]
fn release_all_ungroups_off_artboard_groups_in_a_kept_clipping_group() {
let mut s = session();
let a = rect(&mut s, 600.0, 10.0);
let b = rect(&mut s, 640.0, 10.0);
let inner = group(&mut s, &[a, b]);
let on = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, on, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document", "clipGroups": false})).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{r}");
assert!(node(&s, inner).is_none());
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g));
}
#[test]
fn release_all_takes_apart_pattern_editing_art_over_a_locked_artboard() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
let layer = d.layers[0].id;
d.pattern_edit = Some(vectorcraft_doc::PatternEdit { pattern: "Checks".into(), layer, original: None });
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 1, 0), "{r}");
assert!(node(&s, g).is_none());
}
#[test]
fn release_all_keeps_a_group_with_its_own_fill_or_stroke() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let g = group(&mut s, &[a, b]);
change(&mut s, g, |n| n.appearance = red().into());
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g));
assert_eq!(*node(&s, g).unwrap().appearance, red());
}
#[test]
fn release_all_reuses_unchanged_siblings_when_rebuilding_a_layer() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let g = group(&mut s, &[b]);
let original = s.doc().unwrap().doc.node_arc(a).unwrap().clone();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 0, 0));
assert!(node(&s, g).is_none());
assert!(std::sync::Arc::ptr_eq(&original, s.doc().unwrap().doc.node_arc(a).unwrap()));
}
#[test]
fn release_all_keeps_selection_details_for_untouched_artwork() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let c = rect(&mut s, 70.0, 10.0);
let g = group(&mut s, &[c]);
s.execute("guide.add", &json!({"vertical": true, "pos": 150})).unwrap();
let guide = s.doc().unwrap().doc.ruler_guides()[0].id.unwrap();
s.select(|_, sel| {
sel.set([a, b, g]);
sel.anchors.insert(a, [(0, 0), (0, 2)].into_iter().collect());
sel.anchors.insert(b, [(0, 0), (0, 1)].into_iter().collect());
sel.segments.insert(b, [(0, 0)].into_iter().collect());
sel.guides.push(guide);
sel.key_anchor = Some((a, (0, 0)));
})
.unwrap();
let before = s.doc().unwrap().selection.clone();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 0, 0));
let after = &s.doc().unwrap().selection;
assert_eq!(after.objects, [a, b, c]);
assert_eq!(after.anchors, before.anchors);
assert_eq!(after.segments, before.segments);
assert_eq!(after.guides, before.guides);
assert_eq!(after.key_anchor, before.key_anchor);
assert!(!after.objects.contains(&g));
change(&mut s, c, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
path.subpaths.push(path.subpaths[0].clone());
*live = None;
}
});
s.select(|_, sel| {
sel.anchors.insert(c, [(0, 0), (0, 1)].into_iter().collect());
sel.segments.insert(c, [(0, 0)].into_iter().collect());
})
.unwrap();
let r = s.execute(C, &json!({"ids": [c.0]})).unwrap();
assert_eq!(counts(&r), (0, 0, 1));
let after = &s.doc().unwrap().selection;
assert_eq!(after.anchors, before.anchors);
assert_eq!(after.segments, before.segments);
assert_eq!(after.guides, before.guides);
}
#[test]
fn release_all_keeps_a_directly_named_blend_key() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let key = group(&mut s, &[a, b]);
let c = rect(&mut s, 100.0, 10.0);
select(&mut s, &[key, c]);
let blend = id_of(&s.execute("object.blend.make", &json!({})).unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(key), Some(blend));
let before = s.doc().unwrap().doc.clone();
let selection = selected(&s);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({"ids": [key.0]})).unwrap();
assert_eq!(counts(&r), (0, 0, 0));
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), selection);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn release_all_keeps_a_direct_target_inside_a_compound_clipping_mask() {
for clipping_layer in [false, true] {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let a = rect(&mut s, 5.0, 5.0);
let b = rect(&mut s, 8.0, 8.0);
change(&mut s, a, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
path.subpaths.push(path.subpaths[0].clone());
*live = None;
}
});
let mask = compound(&mut s, &[a, b]);
let container = if clipping_layer {
let id = s.doc().unwrap().doc.layers[0].id;
change(&mut s, id, |n| {
n.children_mut().unwrap().swap(0, 1);
n.set_clips(true);
});
id
} else {
clip_group(&mut s, &[art, mask])
};
assert_eq!(node(&s, container).unwrap().children().unwrap()[0].id, mask);
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for named in [false, true] {
select(&mut s, &[a]);
let p = if named { json!({"ids": [a.0]}) } else { json!({"clipGroups": false}) };
let r = s.execute(C, &p).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{p}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), [a]);
assert_eq!(undo_steps(&s), steps);
}
}
}
#[test]
fn release_all_rejects_null_options_without_editing_artwork() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let g = group(&mut s, &[a]);
for selection in [vec![], vec![g]] {
select(&mut s, &selection);
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for key in ["scope", "groups", "clipGroups", "compoundPaths"] {
let mut p = json!({});
p[key] = Value::Null;
let error = s.execute(C, &p).unwrap_err();
assert!(matches!(error, crate::EngineError::BadParams { ref cmd, .. } if cmd == C), "{p}: {error}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), selection);
assert_eq!(undo_steps(&s), steps);
}
}
}
#[test]
fn release_all_rejects_duplicate_ids_before_traversal() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let g = group(&mut s, &[a]);
let b = rect(&mut s, 50.0, 10.0);
select(&mut s, &[g]);
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for ids in [vec![g.0, g.0], vec![b.0, b.0], vec![g.0, a.0, a.0]] {
let error = s.execute(C, &json!({"ids": ids})).unwrap_err();
assert!(matches!(error, crate::EngineError::BadParams { ref cmd, ref msg } if cmd == C && msg.contains("duplicate")), "{error}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), [g]);
assert_eq!(undo_steps(&s), steps);
}
}
#[test]
fn release_all_refuses_bad_params() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let g = group(&mut s, &[a]);
select(&mut s, &[g]);
let steps = undo_steps(&s);
for bad in [
json!({"groups": false, "clipGroups": false, "compoundPaths": false}),
json!({"groups": "yes"}),
json!({"compoundPaths": 1}),
json!({"scope": "layer"}),
json!({"scope": "document", "ids": [g.0]}),
json!({"ids": [999_999]}),
] {
assert!(s.execute(C, &bad).is_err(), "{bad}");
}
assert_eq!(undo_steps(&s), steps);
assert!(node(&s, g).is_some());
}
+1 -1
View File
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
@@ -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<Value> {
}
let series_groups = cached_series_groups(before, &targets);
let mut seen = std::collections::HashSet::new();
let compound_groups: HashSet<NodeId> = 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<NodeId> = 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<Value> {
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| {
@@ -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<NodeId> = 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::<Vec<_>>()})).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"] {
+30 -1
View File
@@ -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<CommandSpec> {
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)?;
@@ -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<Value> {
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::<Vec<_>>(), "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<u32>| 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)
}
@@ -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<std::sync::Arc<vectorcraft_doc::Node>> {
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, &params).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, &params).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, &params).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, &params).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::<Vec<_>>(), 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, &params).unwrap_err().to_string();
assert!(error.contains("exit isolation mode"), "{error}");
let error = s.execute(FLOOD, &params).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", &params).unwrap();
let r = s.preview("command.batch", &params).unwrap();
s.commit_interaction().unwrap();
r
} else {
s.execute("command.batch", &params).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, &params).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, &params).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, &params)
};
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, &params).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, &params).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, &params);
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]
Loaded 100 of 774 files, more files were not shown because too many files have changed in this diff. Show more