diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c86dfb998a..0ac8a37f83 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,17 +44,19 @@ jobs: # The workspace crates also build without line tables. A panic still names its file and line. dev-debug: "0" # The `build ()` job builds the tests once and writes one nextest archive per shard with - # that shard's test binaries (`cargo xtask ci archive`), then runs the doctests. Five test - # legs download their own archive and run it without building: shards 1 and 2 each run half - # of vectorcraft-ui-egui's tests, and shards 3 to 5 the tests of their own crates - # (xtask/src/shards.rs). The `lint ()` leg runs the other `cargo xtask ci` steps beside - # them, with a dependency cache of its own. `gate ()` passes when the build and every - # test leg that ran passed; `lint ()` is a check of its own. + # that shard's test binaries (`cargo xtask ci archive`), then runs the doctests and the tests + # built without the bundled fonts (`cargo xtask ci after-archive`), whose second build of the + # workspace crates the build job's cache entry keeps. Five test legs download their own archive and + # run it without building: shards 1 and 2 each run half of vectorcraft-ui-egui's tests, and + # shards 3 to 5 the tests of their own crates (xtask/src/shards.rs). The `lint ()` leg + # runs the other `cargo xtask ci` steps beside them, with a dependency cache of its own. + # `gate ()` passes when the build and every test leg that ran passed; `lint ()` is a + # check of its own. test-shards: 5 shard-command: cargo xtask ci shard archive-command: cargo xtask ci archive shard-archives: true - after-archive-command: cargo xtask ci doctests + after-archive-command: cargo xtask ci after-archive lint-command: cargo xtask ci checks # 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 @@ -80,6 +82,11 @@ jobs: pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev + # `.rs` files that no workspace module reaches on purpose: fixture trees (the gate's default) + # and the example panel plug-in, a Cargo project of its own that builds for wasm32 only. + unreached-rs-allow: | + **/fixtures/** + crates/plugins/example-panel/** # The nightly cold run never restores the rolling crates entry, so the old entry is only overlap # while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml index 4ef372c40b..4581f75d39 100644 --- a/.github/workflows/nightly-dispatch.yml +++ b/.github/workflows/nightly-dispatch.yml @@ -16,9 +16,11 @@ jobs: github.repository == 'storytold/vectorcraft' && github.event_name == 'workflow_run' runs-on: ubuntu-latest - timeout-minutes: 5 + # Most of the time is the wait for the producer commit's SonarCloud analysis (up to 280 minutes). + timeout-minutes: 300 permissions: actions: write + checks: read steps: - name: Dispatch only the exact completed producer run and attempt shell: python @@ -27,6 +29,10 @@ jobs: run: | import json import os + import re + import time + import urllib.error + import urllib.parse import urllib.request def require(value, message): @@ -51,22 +57,58 @@ jobs: run_id, attempt = producer.get('id'), producer.get('run_attempt') require(type(run_id) is int and run_id > 0, 'invalid producer run id') require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt') + source = producer.get('head_sha') + require(isinstance(source, str) and re.fullmatch(r'[0-9a-f]{40}', source), 'invalid producer commit') + headers = { + 'Authorization': 'Bearer ' + os.environ['GH_TOKEN'], + 'Accept': 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'vectorcraft-nightly-dispatch' + } + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise RuntimeError('dispatch redirects are forbidden') + opener = urllib.request.build_opener(NoRedirect()) + + def read(path): + request = urllib.request.Request('https://api.github.com/repos/storytold/vectorcraft' + path, headers=headers) + with opener.open(request, timeout=20) as response: + require(response.status == 200, 'read was not accepted') + return json.load(response) + + # Stage 2 admits the producer only on its commit's own SonarCloud analysis, which + # sonarcloud.yml starts when the producer starts. Wait for the check that analysis posts; + # a SonarCloud run that ended without one gets 20 minutes before the wait gives up. + checks_path = '/commits/' + source + '/check-runs?' + urllib.parse.urlencode( + {'app_id': 12526, 'check_name': 'SonarCloud Code Analysis', 'filter': 'latest'}) + runs_path = '/actions/workflows/sonarcloud.yml/runs?' + urllib.parse.urlencode( + {'event': 'workflow_run', 'head_sha': source, 'per_page': 1}) + deadline = time.monotonic() + 280 * 60 + ended = None + while True: + try: + checks = read(checks_path).get('check_runs', []) + if any(c.get('head_sha') == source and c.get('status') == 'completed' for c in checks): + break + runs = read(runs_path).get('workflow_runs', []) + if runs and runs[0].get('status') == 'completed' and ended is None: + ended = time.monotonic() + print('SonarCloud run', runs[0].get('id'), 'ended:', runs[0].get('conclusion')) + except (urllib.error.URLError, OSError, ValueError) as error: + print('Read failed, polling again:', error) + require(ended is None or time.monotonic() < ended + 20 * 60, + 'the SonarCloud run for the producer commit ended without an analysis check') + require(time.monotonic() < deadline, 'no SonarCloud analysis of the producer commit in time') + time.sleep(60) + print('SonarCloud analysis check of', source, 'is complete.') + body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': { 'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt) }}).encode('utf-8') request = urllib.request.Request( 'https://api.github.com/repos/storytold/vectorcraft/actions/workflows/nightly-sign.yml/dispatches', - data=body, method='POST', headers={ - 'Authorization': 'Bearer ' + os.environ['GH_TOKEN'], - 'Accept': 'application/vnd.github+json', - 'Content-Type': 'application/json', - 'X-GitHub-Api-Version': '2022-11-28', - 'User-Agent': 'vectorcraft-nightly-dispatch' - }) - class NoRedirect(urllib.request.HTTPRedirectHandler): - def redirect_request(self, req, fp, code, msg, headers, newurl): - raise RuntimeError('dispatch redirects are forbidden') + data=body, method='POST', headers=dict(headers, **{'Content-Type': 'application/json'})) # One bounded request, no retry: duplicate transport is not publication authority. - with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response: + with opener.open(request, timeout=20) as response: require(response.status == 204, 'dispatch was not accepted') print('Dispatched producer run/attempt to the release-ref validator; not a signing result.') diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 98e9c1d00a..990491929c 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -1,8 +1,12 @@ name: SonarCloud +# Main is analyzed once a day, at the commit the nightly builds: Stage 2 admits a nightly only on +# that commit's own analysis, and nightly-dispatch.yml waits for it before dispatching the signer. on: workflow_dispatch: - push: + workflow_run: + workflows: [VectorCraft unsigned nightly] + types: [requested] branches: [main] pull_request: types: [opened, synchronize, reopened] @@ -12,16 +16,44 @@ permissions: concurrency: group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }} - # A push to main is the run that publishes coverage; superseded runs there would never finish. + # A main run is the analysis a nightly waits for; superseded runs there would never finish. cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} jobs: + nightly-commit: + name: Nightly commit is main's head + # A workflow_run checks out and analyzes main's head, so main must not have moved since the + # nightly started. + if: github.event_name == 'workflow_run' + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - name: Require main's head to be the nightly's commit + env: + NIGHTLY_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_SHA: ${{ github.sha }} + run: | + if [ "$NIGHTLY_SHA" != "$RUN_SHA" ]; then + echo "::error::main moved from $NIGHTLY_SHA to $RUN_SHA after the nightly started; this run would not analyze the nightly's commit" + exit 1 + fi + sonarcloud: + needs: nightly-commit + if: ${{ !cancelled() && contains(fromJSON('["success","skipped"]'), needs.nightly-commit.result) }} # Tracked at @main so org-wide CI improvements propagate without PR churn. # The reusable workflow defaults build-jobs to 2 so a cold instrumented # archive stays within hosted-runner memory (craft-common-actions#333). uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main with: + # Each test writes its own raw coverage profile, about 80 GB per shard at 4 shards, which + # fills the runner. 8 shards halve that. Go back to the default once + # storytold/craft-common-actions#486 merges. + shards: 8 python-coverage-source: .github/scripts python-coverage-script: .github/scripts/tests/test_release_rpm_smoke.py secrets: inherit diff --git a/Cargo.lock b/Cargo.lock index f9720b738e..72c09b4d83 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1256,7 +1256,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-automation", "craft-behavior", @@ -1298,7 +1298,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "crc32fast", "flate2", @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1331,7 +1331,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "rustix 1.1.6", ] @@ -1339,7 +1339,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1383,7 +1383,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-docpath", @@ -1401,8 +1401,9 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ + "craft-codepage", "crc32fast", "flate2", ] @@ -1410,7 +1411,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "egui", ] @@ -1418,7 +1419,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "md-5", "rayon", @@ -1427,12 +1428,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-cms", @@ -1452,7 +1453,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1468,7 +1469,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1478,7 +1479,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "rayon", ] @@ -1486,7 +1487,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1512,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "blake3", "craft-ecproj-format", @@ -1528,7 +1529,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "serde", ] @@ -1536,7 +1537,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1555,7 +1556,7 @@ dependencies = [ [[package]] name = "craft-dwg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "acadrust", "craft-dxf", @@ -1565,7 +1566,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-codepage", "encoding_rs", @@ -1577,7 +1578,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "serde", "serde_json", @@ -1587,12 +1588,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-atomic", "dirs", @@ -1602,7 +1603,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1617,7 +1618,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1636,7 +1637,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1645,7 +1646,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "cap-primitives", "craft-atomic", @@ -1668,12 +1669,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "gif", ] @@ -1681,7 +1682,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "flate2", ] @@ -1689,7 +1690,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1702,7 +1703,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1732,7 +1733,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-dds", "craft-jpeg", @@ -1759,7 +1760,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1777,7 +1778,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "thiserror 2.0.21", ] @@ -1785,7 +1786,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1796,7 +1797,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-host", "craft-i18n", @@ -1811,7 +1812,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-i18n", @@ -1825,7 +1826,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-host", @@ -1843,7 +1844,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1855,7 +1856,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "encoding_rs", "image", @@ -1866,7 +1867,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "chrono", "craft-codepage", @@ -1876,7 +1877,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "uds_windows", "winsafe", @@ -1885,7 +1886,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-keymap", @@ -1901,7 +1902,7 @@ dependencies = [ [[package]] name = "craft-pbr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-texture", "thiserror 2.0.21", @@ -1910,7 +1911,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "flate2", "serde", @@ -1921,7 +1922,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1933,7 +1934,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "async-channel", "async-io", @@ -1947,6 +1948,7 @@ dependencies = [ "futures-lite", "js-sys", "log", + "notify", "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-core-graphics", @@ -1966,7 +1968,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1975,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-host", @@ -1999,7 +2001,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -2010,7 +2012,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-eps", "flate2", @@ -2024,7 +2026,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "encoding_rs", "flate2", @@ -2035,7 +2037,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "dispatch2", "egui", @@ -2048,7 +2050,7 @@ dependencies = [ [[package]] name = "craft-raster3d" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2057,7 +2059,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2076,7 +2078,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-atomic", "craft-host", @@ -2093,7 +2095,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "fax", "hayro-ccitt", @@ -2104,7 +2106,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2125,7 +2127,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2137,7 +2139,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2162,7 +2164,7 @@ dependencies = [ [[package]] name = "craft-texture" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "thiserror 2.0.21", ] @@ -2170,7 +2172,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2185,7 +2187,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-atomic", "craft-behavior", @@ -2200,7 +2202,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2210,7 +2212,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2219,7 +2221,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2234,12 +2236,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2253,7 +2255,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2270,7 +2272,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "accesskit", "craft-behavior", @@ -2308,7 +2310,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2319,7 +2321,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-host", @@ -2337,7 +2339,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-host", @@ -2358,7 +2360,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-host", @@ -2379,7 +2381,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-behavior", "craft-host", @@ -2393,12 +2395,13 @@ dependencies = [ "log", "serde", "smallvec", + "unicode-segmentation", ] [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "base64 0.22.1", "chrono", @@ -2430,7 +2433,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "flate2", "serde", @@ -2441,7 +2444,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2451,7 +2454,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "js-sys", "serde_json", @@ -2462,7 +2465,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "winsafe", ] @@ -2470,7 +2473,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "craft-appkit", "craft-atomic", @@ -2502,7 +2505,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2971,7 +2974,6 @@ dependencies = [ "raw-window-handle", "smithay-clipboard", "web-time", - "webbrowser", "windows-sys 0.61.2", "winit", ] @@ -3862,7 +3864,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3871,7 +3873,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3889,7 +3891,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3907,12 +3909,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "flate2", "hayro-ccitt", @@ -4474,6 +4476,26 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inotify" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592" +dependencies = [ + "bitflags 2.13.2", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + [[package]] name = "inout" version = "0.1.4" @@ -4892,10 +4914,30 @@ dependencies = [ "accesskit_consumer", ] +[[package]] +name = "kqueue" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" +dependencies = [ + "bitflags 2.13.2", + "libc", +] + [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "base64 0.22.1", "bumpalo", @@ -5052,7 +5094,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -5194,6 +5236,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", + "log", "wasi", "windows-sys 0.61.2", ] @@ -5359,6 +5402,35 @@ dependencies = [ "memchr", ] +[[package]] +name = "notify" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5482d5bd11b91a337521980e5d52fe115bdccfb4c217099daaf0abd69159dc4e" +dependencies = [ + "bitflags 2.13.2", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "notify-types", + "objc2-core-foundation", + "objc2-core-services", + "walkdir", + "windows-sys 0.61.2", + "xxhash-rust", +] + +[[package]] +name = "notify-types" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbd044e85df3d939d8e32a1c35a3b737c7d0a4eeb7acd737bd207644e00f4e5f" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "num" version = "0.4.3" @@ -5713,6 +5785,16 @@ dependencies = [ "objc2-core-video", ] +[[package]] +name = "objc2-core-services" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "objc2-core-text" version = "0.3.2" @@ -7618,7 +7700,7 @@ dependencies = [ [[package]] name = "skrifa" version = "0.44.0" -source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" +source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6" dependencies = [ "bytemuck", "read-fonts 0.41.0", @@ -8673,6 +8755,7 @@ dependencies = [ "wayland-backend", "wayland-client", "wayland-protocols", + "webbrowser", "windows", "winit", "winreg", @@ -8780,6 +8863,7 @@ name = "vectorcraft-doc" version = "0.25.1" dependencies = [ "chrono", + "craft-i18n", "craft-image-codecs", "craft-stream-codecs", "flate2", @@ -9010,6 +9094,7 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-effects", "vectorcraft-geom 0.25.1", + "vectorcraft-pathops 0.25.1", "vectorcraft-text", ] @@ -9219,6 +9304,7 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-geom 0.25.1", "vello_cpu", + "windows-registry", "write-fonts", ] @@ -9291,6 +9377,7 @@ dependencies = [ "rustix 1.1.6", "serde", "serde_json", + "sha2 0.10.9", "toml", "vectorcraft-apischema", "vectorcraft-brush", @@ -10574,6 +10661,12 @@ dependencies = [ "tempfile", ] +[[package]] +name = "xxhash-rust" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40de123dbb523ebcc00d61ec01840ad192578afc378d859f3429caa38308fad5" + [[package]] name = "yeslogic-fontconfig-sys" version = "6.0.1" diff --git a/Cargo.toml b/Cargo.toml index 494cc0839f..9aef0a621b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,60 +10,62 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # 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 = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +# Digits typed in any script in numeric fields (`vectorcraft_doc::units`). +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # 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 = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # The DWG reader and writer craft-dwg uses, at the rev craft-libs pins (its Cargo.toml). Tests only: it writes the # R12, R13 and R14 DWG files that craft-dwg's writer, 2000 and later, does not. acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "468b9d8e317755209020d5d3f2f1c8a76210c47f" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # 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 = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # 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 = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # 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 = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # 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 = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -203,16 +205,15 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } # 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" } +skrifa = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" } 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" } diff --git a/ROADMAP.md b/ROADMAP.md index a310f25148..40871e4fc6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,6 +124,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-12-05: Window › Swatch Strip shows a None chip and the document's color swatches as a strip of chips that wraps to the panel's room: docked on the window's bottom edge it runs across in one line, and in a dock column or a narrow floating window it runs down. A click sets the fill and a right-click or Alt-click sets the stroke (#10951). A VectorCraft addition: headline numbers unchanged. - 2026-12-04: Raster Settings OK edits the objects selected when the dialog opened. It keeps the dialog open with the reason if its document is not active, was reverted or had an Undo, a Redo or a canceled edit that put back an earlier state, if a target was changed, deleted, locked or hidden, if another edit is in progress, or if the change is refused. Headline numbers unchanged. - 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. diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index b024135c0a..d23793c802 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index d4d2659b3e..74d7923011 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -23,10 +23,7 @@ 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 } -# `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"] } +eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] } egui = { workspace = true } egui_extras = { workspace = true } serde_json = { workspace = true } @@ -39,6 +36,9 @@ arboard = { workspace = true, features = ["image-data", "wayland-data-control"] image = { workspace = true } # The window's monitors, size and position (the same winit eframe runs on). winit = { version = "0.30", default-features = false } +# Opens the files View PDF after Saving and Show in Browser wrote in the default web browser +# (src/host_services.rs). MIT OR Apache-2.0. +webbrowser = "1.2" [target.'cfg(windows)'.dependencies] clipboard-win = { workspace = true } diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 9e416d7711..ec4f467292 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -80,7 +80,54 @@ fn a_dialog_is_marked_while_it_shows_and_not_after() { /// File → Show in Folder: select `path` in Finder / Explorer, or open its folder elsewhere. fn reveal(path: &str) -> Result<(), String> { explorer_safe(path)?; - reveal_command(path).spawn().map(|_| ()).map_err(|e| format!("can't show {path}: {e}")) + spawn_detached(&mut reveal_command(path)).map(drop).map_err(|e| format!("can't show {path}: {e}")) +} + +/// The thread that waits for a process [`spawn_detached`] started; it returns the exit status. +pub(crate) type Reaper = std::thread::JoinHandle>; + +/// Starts `c` without the caller waiting for it. On Windows dropping the `Child` closes its handle, +/// so there is no reaper. Elsewhere a thread waits for the process, so it is reaped when it ends +/// instead of staying a zombie until the app exits. The thread starts first, so a process is never +/// started without a waiter. +pub(crate) fn spawn_detached(c: &mut std::process::Command) -> std::io::Result> { + #[cfg(windows)] + let started = c.spawn().map(|_| None); + #[cfg(not(windows))] + let started = { + let (send, receive) = std::sync::mpsc::channel::(); + let reaper = std::thread::Builder::new().name("process reaper".into()).spawn(move || match receive.recv() { + Ok(mut child) => child.wait(), + Err(_) => Err(std::io::Error::other("the process did not start")), + })?; + let child = c.spawn()?; + // The reaper holds the receiver until it gets the child, so this send always arrives. + let _ = send.send(child); + Ok(Some(reaper)) + }; + started +} + +/// Linux keeps `/proc/` in state `Z` for a process that ended until its parent waits for it. +/// A pid the kernel has given to a new process since is not in state `Z`. +#[cfg(all(test, target_os = "linux"))] +#[test] +fn a_started_process_is_reaped_once_it_ends() { + let dir = tempfile::tempdir().unwrap(); + let pid_file = dir.path().join("pid"); + let mut c = std::process::Command::new("sh"); + c.arg("-c").arg("echo $$ > \"$1\"; exit 3").arg("sh").arg(&pid_file); + let reaper = spawn_detached(&mut c).unwrap().expect("a reaper on Linux"); + let status = reaper.join().unwrap().unwrap(); + let pid = std::fs::read_to_string(&pid_file).unwrap(); + let pid = pid.trim().to_string(); + assert!(!pid.is_empty(), "the process wrote its pid"); + // `/proc//stat` is `pid (comm) state ...`; a missing file means the pid is free. + let state = std::fs::read_to_string(format!("/proc/{pid}/stat")) + .ok() + .and_then(|s| s.rsplit_once(") ").and_then(|(_, rest)| rest.split(' ').next().map(str::to_string))); + assert_ne!(state.as_deref(), Some("Z"), "process {pid} is still a zombie"); + assert_eq!(status.code(), Some(3), "the reaper reads the process's own exit"); } #[cfg(target_os = "macos")] @@ -108,6 +155,50 @@ fn reveal_command(path: &str) -> std::process::Command { c } +/// Opens the `file:` URL of a file the app wrote (View PDF after Saving, Show in Browser) in the +/// default web browser. +fn open_file_url(url: &str) -> Result<(), String> { + webbrowser::open(url).map_err(|e| format!("can't open {url}: {e}")) +} + +/// Opens a link with the system's handler, without the caller waiting for it: +/// `craft::platform::open::open_external` on macOS and Windows, xdg-open elsewhere ([`link_command`]). +pub(crate) fn open_link(url: &str) -> Result<(), String> { + #[cfg(not(any(target_os = "macos", windows)))] + { + let mut c = link_command(url)?; + c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()); + spawn_detached(&mut c).map(drop).map_err(|e| format!("can't open {url}: {e}")) + } + #[cfg(any(target_os = "macos", windows))] + { + craft::platform::open::open_external(url) + } +} + +/// xdg-open with `url` as its only argument. xdg-open stops with "unexpected option" at any +/// argument that starts with `-`, `--` included, which `craft::platform::open::open_external` puts +/// before the URL, so a URL that starts with `-` is refused here instead. Remove this once +/// craft-libs' `open_external` runs xdg-open without `--`. +#[cfg(not(any(target_os = "macos", windows)))] +fn link_command(url: &str) -> Result { + if url.starts_with('-') { + return Err(format!("can't open {url}: it starts with '-'")); + } + let mut c = std::process::Command::new("xdg-open"); + c.arg(url); + Ok(c) +} + +#[cfg(all(test, not(any(target_os = "macos", windows))))] +#[test] +fn xdg_open_gets_the_link_alone_and_never_an_option() { + let c = link_command("https://discord.gg/artcraft").unwrap(); + assert_eq!(c.get_program(), "xdg-open"); + assert_eq!(c.get_args().collect::>(), ["https://discord.gg/artcraft"], "xdg-open refuses a `--` before the URL"); + assert!(link_command("--help").is_err(), "xdg-open would read it as an option"); +} + /// Read a whole file. A device or pipe may never end: only a regular file is read. fn read_file(path: &str) -> Result, String> { if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() { @@ -183,6 +274,8 @@ pub(crate) fn services(window: Parent) -> Services { reveal: Some(Box::new(reveal)), // Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders. open_file: Some(Box::new(open_file)), + // View PDF after Saving and Show in Browser open the file they wrote. + open_file_url: Some(Box::new(open_file_url)), // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). open_in_photocraft: Some(Box::new(open_in_photocraft)), check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))), @@ -219,7 +312,7 @@ fn open_file(path: &str) -> Result<(), String> { let mut c = std::process::Command::new("xdg-open"); #[cfg(not(windows))] c.arg(path); - c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}")) + spawn_detached(&mut c).map(drop).map_err(|e| format!("can't open {path}: {e}")) } /// Edit Original with Preferences › File Handling › Use System Defaults for Edit Original off @@ -294,7 +387,7 @@ fn launch_application(app: &std::path::Path, path: &str) -> Result } } #[cfg(not(target_os = "macos"))] - c.spawn().map(|_| true).map_err(|e| format!("can't open {path} in {}: {e}", app.display())) + spawn_detached(&mut c).map(|_| true).map_err(|e| format!("can't open {path} in {}: {e}", app.display())) } /// PhotoCraft where it is installed: the first of [`photocraft_candidates`] that is an application. diff --git a/apps/vectorcraft/src/mac_fonts.rs b/apps/vectorcraft/src/mac_fonts.rs index 4e9f996d62..a98f76ea68 100644 --- a/apps/vectorcraft/src/mac_fonts.rs +++ b/apps/vectorcraft/src/mac_fonts.rs @@ -21,9 +21,10 @@ use objc2_core_text::CTFontManagerCopyAvailableFontURLs; /// The most fonts read from the list (a system has a few thousand faces). const MAX_FONTS: usize = 1 << 16; -/// Have the font scans read the font files CoreText lists. +/// Have the font scans read the font files CoreText lists, in place of asking the font service for +/// CoreText's fonts a second time. pub fn install() { - vectorcraft_text::set_platform_font_files(font_files); + vectorcraft_text::set_platform_font_files_complete(font_files); } /// The files of the fonts available to the app as CoreText lists them now (fonts registered since diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 63135d00e5..a234e14868 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -68,6 +68,7 @@ mod single_instance; mod system_fonts; mod tablet; mod window_frame; +mod window_system; mod windows_alt_codes; #[cfg(windows)] mod windows_cores; @@ -91,7 +92,6 @@ use craft::ui::shell::embed; use craft::window::Prefix; use craft::window::policy::{TitleBarPref, decide_for}; use craft::window::restore::Store; -use craft::window::system::SystemWindows; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::file_access::{self, AutomationRoots}; @@ -117,20 +117,9 @@ const MIN_SIZE: [f32; 2] = [800.0, 500.0]; /// framework maximizes the window when its default size would not fit the current screen. fn restore_main_window(window: &winit::window::Window, store: &Store, legacy: Option, wayland: bool) { use craft::behavior::placement::{Defaults, Placement, place}; - use craft::behavior::{Monitor, MonitorKey}; use winit::dpi::{LogicalSize, PhysicalPosition}; - let handles: Vec<_> = window.available_monitors().collect(); - let monitors: Vec<_> = handles - .iter() - .map(|monitor| { - let size = monitor.size(); - let size = [size.width, size.height]; - let position = monitor.position(); - Monitor::new(MonitorKey::new(monitor.name().unwrap_or_default(), size), [position.x, position.y], size, monitor.scale_factor() as f32) - }) - .collect(); - let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor)); + let (monitors, home) = window_system::monitor_layout(window).unwrap_or_default(); let defaults = Defaults::new(DEFAULT_SIZE, MIN_SIZE).with_no_position(wayland); let saved = store.get(craft::window::restore::MAIN).or_else(|| { let old = legacy?; @@ -439,6 +428,17 @@ fn desktop_shell_info(detected: Backend, forced_to_x11: bool) -> ShellInfo { ShellInfo::current().backend(backend) } +/// The UI runtime's install spec for the main window: the app's id, and every `http`, `https` or `mailto` link the +/// app asks to open (Help menu, About, credits, the updater, an object's URL) handed to `open_link`, which is +/// [`host_services::open_link`] in the app. +fn main_window_spec( + shell_info: ShellInfo, + windows: Arc, + open_link: impl Fn(&str) -> Result<(), String> + Send + Sync + 'static, +) -> InstallSpec { + InstallSpec::new(shell_info, windows).app_id(vectorcraft_ui_egui::os_window::app_id()).open_links(open_link) +} + /// The nightly channel this build is, as a string for the log. fn channel_name() -> &'static str { match build_flavor::COMPILED { @@ -885,10 +885,11 @@ fn main() -> std::process::ExitCode { if let Some(window) = &winit_window { restore_main_window(window, &placement, settings.lock().get().ui.legacy_window, wayland); } - let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows)) - .app_id(vectorcraft_ui_egui::os_window::app_id()) - .placement(Arc::new(Mutex::new(placement))) - .frame(decision); + // A pen or a finger in contact counts as the primary button (`windows_stylus`). + let spec = + main_window_spec(shell_info, Arc::new(window_system::DesktopWindows::new(winit_window.as_ref())), host_services::open_link) + .placement(Arc::new(Mutex::new(placement))) + .frame(decision); let spec = match start_pen(&winit_window) { Some(pen) => spec.pen(pen), None => spec, diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index ba5b6a3a18..e522d57277 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -459,21 +459,82 @@ mod system { #[cfg(target_os = "macos")] { let _ = printer; - Command::new("open") - .arg("x-apple.systempreferences:com.apple.Print-Scan-Settings.extension") - .spawn() - .map(|_| ()) - .map_err(|e| e.to_string()) + let mut open = Command::new("open"); + open.arg("x-apple.systempreferences:com.apple.Print-Scan-Settings.extension"); + start_first([open]).map(drop).map_err(|e| e.to_string()) } #[cfg(not(any(windows, target_os = "macos")))] { - if Command::new("system-config-printer").spawn().is_ok() { - return Ok(()); - } - let url = printer.map_or_else(|| "http://localhost:631/printers/".to_string(), |p| format!("http://localhost:631/printers/{p}")); - Command::new("xdg-open").arg(url).spawn().map(|_| ()).map_err(|e| e.to_string()) + start_first(setup_commands(printer)).map(drop).map_err(|e| e.to_string()) } } + + /// The commands [`setup`] tries in order on Linux and the BSDs: the printer settings app, then the + /// CUPS web page for `printer` (or the printer list) in the browser. + #[cfg(not(any(windows, target_os = "macos")))] + pub(super) fn setup_commands(printer: Option<&str>) -> [Command; 2] { + let url = printer.map_or_else(|| "http://localhost:631/printers/".to_string(), |p| format!("http://localhost:631/printers/{p}")); + let mut open = Command::new("xdg-open"); + open.arg(url); + [Command::new("system-config-printer"), open] + } + + /// Starts the first of `commands` that starts, through [`crate::host_services::spawn_detached`], so + /// it is reaped when it ends. Returns the last error when none starts. + #[cfg(not(windows))] + pub(super) fn start_first(commands: impl IntoIterator) -> std::io::Result> { + let mut last = std::io::Error::other("no command to start"); + for mut c in commands { + match crate::host_services::spawn_detached(&mut c) { + Ok(reaper) => return Ok(reaper), + Err(e) => last = e, + } + } + Err(last) + } +} + +/// Linux keeps `/proc/` in state `Z` for a process that ended until its parent waits for it. +#[cfg(all(test, target_os = "linux"))] +mod setup_tests { + use super::system::{setup_commands, start_first}; + use std::process::Command; + + #[test] + fn printer_setup_tries_the_settings_app_then_the_cups_page() { + let [app, page] = setup_commands(Some("Office Laser")); + assert_eq!(app.get_program(), "system-config-printer"); + assert_eq!(app.get_args().count(), 0); + assert_eq!(page.get_program(), "xdg-open"); + assert_eq!(page.get_args().collect::>(), ["http://localhost:631/printers/Office Laser"]); + let [_, list] = setup_commands(None); + assert_eq!(list.get_args().collect::>(), ["http://localhost:631/printers/"]); + } + + #[test] + fn the_settings_fallback_is_reaped_once_it_ends() { + let dir = tempfile::tempdir().unwrap(); + let pid_file = dir.path().join("pid"); + let mut fallback = Command::new("sh"); + fallback.arg("-c").arg("echo $$ > \"$1\"; exit 3").arg("sh").arg(&pid_file); + let reaper = start_first([Command::new("vectorcraft-no-such-program"), fallback]).unwrap().expect("a reaper on Linux"); + let status = reaper.join().unwrap().unwrap(); + assert_eq!(status.code(), Some(3), "the fallback ran after the missing program"); + let pid = std::fs::read_to_string(&pid_file).unwrap(); + let pid = pid.trim(); + assert!(!pid.is_empty(), "the process wrote its pid"); + let state = std::fs::read_to_string(format!("/proc/{pid}/stat")) + .ok() + .and_then(|s| s.rsplit_once(") ").and_then(|(_, rest)| rest.split(' ').next().map(str::to_string))); + assert_ne!(state.as_deref(), Some("Z"), "process {pid} is still a zombie"); + } + + #[test] + fn with_no_command_starting_the_last_error_is_returned() { + // A missing program fails with NotFound; a directory fails with PermissionDenied. + let err = start_first([Command::new("vectorcraft-no-such-program"), Command::new("/")]).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied); + } } #[cfg(all(test, windows))] diff --git a/apps/vectorcraft/src/system_fonts.rs b/apps/vectorcraft/src/system_fonts.rs index fe9df48ca4..0edbdd41ab 100644 --- a/apps/vectorcraft/src/system_fonts.rs +++ b/apps/vectorcraft/src/system_fonts.rs @@ -40,9 +40,10 @@ const MAX_FACE_FILES: u32 = 8; /// The longest file path taken, in UTF-16 units (Windows' own limit). const MAX_PATH: u32 = 32_767; -/// Have the font scans read the font files DirectWrite and GDI list. +/// Have the font scans read the font files DirectWrite and GDI list, in place of asking the font +/// service for DirectWrite's collection a second time. pub fn install() { - vectorcraft_text::set_platform_font_files(font_files); + vectorcraft_text::set_platform_font_files_complete(font_files); } /// The local files of the fonts in DirectWrite's system font collection as it is now (fonts diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index c28fb19c13..f37e5e68b1 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -13,6 +13,27 @@ fn desktop_shell_reports_the_backend_selected_for_docking() { } } +/// The main window's install spec hands each link the app opens to the link opener once: Help › Discord reaches it, +/// and the window integration does not get the same request as well. +#[test] +fn help_links_open_through_the_main_windows_link_opener() { + let opened = Arc::new(Mutex::new(Vec::::new())); + let seen = Arc::clone(&opened); + let spec = main_window_spec(desktop_shell_info(Backend::X11, false), Arc::new(craft::window::system::NoWindows), move |url: &str| { + seen.lock().unwrap().push(url.to_owned()); + Ok(()) + }); + let mut frames = craft::ui::testing::Frames::uninstalled(); + craft::ui::install(&frames.ctx, spec).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + frames.idle(2, |ui| app.tick(ui.ctx())); + + app.open_link("help.discord"); + frames.idle(2, |ui| app.tick(ui.ctx())); + assert_eq!(*opened.lock().unwrap(), ["https://discord.gg/artcraft"], "the opener gets the link once"); + assert!(frames.opened().is_empty(), "the integration is not asked to open it too"); +} + /// The saved UI state of an old `ui.json`, as the legacy import reads it. fn legacy_ui(bytes: &[u8]) -> Option { vectorcraft_ui_egui::parse_legacy(bytes).ok().map(|(settings, _)| settings.ui) diff --git a/apps/vectorcraft/src/window_system.rs b/apps/vectorcraft/src/window_system.rs new file mode 100644 index 0000000000..4c7975a561 --- /dev/null +++ b/apps/vectorcraft/src/window_system.rs @@ -0,0 +1,249 @@ +//! The desktop's monitors for window and popup placement: where each one is, its size and scale, and on Windows the +//! part the taskbar leaves free. + +use std::panic::AssertUnwindSafe; +use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::time::{Duration, Instant}; + +use craft::behavior::{Monitor, MonitorKey}; +use craft::window::system::{HeldButtons, WindowSystem}; +use winit::window::Window; + +use crate::windows_stylus::ContactWindows; + +/// How long one listing of the monitors is used. Placement asks for the monitors several times a frame; a display +/// that is added, removed or moved shows up in the first listing after this. +const RELIST_AFTER: Duration = Duration::from_secs(1); + +/// The monitors in physical desktop pixels, and the index of the one showing `window` (else the primary one). +/// `None` when winit stops on a display that went away while it was being listed (Windows). +pub(super) fn monitor_layout(window: &Window) -> Option<(Vec, Option)> { + let listing = std::panic::catch_unwind(AssertUnwindSafe(|| { + let handles: Vec<_> = window.available_monitors().collect(); + let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor)); + let monitors = handles + .iter() + .map(|handle| { + let size = handle.size(); + let size = [size.width, size.height]; + let position = handle.position(); + let monitor = Monitor::new( + MonitorKey::new(handle.name().unwrap_or_default(), size), + [position.x, position.y], + size, + handle.scale_factor() as f32, + ); + match work_px(&monitor) { + Some((pos, size)) => monitor.with_work_px(pos, size), + None => monitor, + } + }) + .collect(); + (monitors, home) + })); + listing.map_err(|_| log::debug!("a display went away while the monitors were listed")).ok() +} + +/// The work area of the monitor whose top-left pixel is `monitor`'s, from `GetMonitorInfo`. winsafe comes with the +/// wgpu renderer, which every desktop package builds with. +#[cfg(all(windows, feature = "wgpu"))] +fn work_px(monitor: &Monitor) -> Option<([i32; 2], [u32; 2])> { + use winsafe::{HMONITOR, POINT, co}; + let [x, y] = monitor.pos_px; + let info = HMONITOR::MonitorFromPoint(POINT { x, y }, co::MONITOR::DEFAULTTONULL).GetMonitorInfo().ok()?; + let work = info.rcWork; + from_edges(work.left, work.top, work.right, work.bottom) +} + +/// Other platforms report no work area. +#[cfg(not(all(windows, feature = "wgpu")))] +fn work_px(_: &Monitor) -> Option<([i32; 2], [u32; 2])> { + None +} + +/// The top-left corner and size of the pixel rectangle with these edges; `None` for an empty or inverted one. +#[cfg(any(all(windows, feature = "wgpu"), test))] +fn from_edges(left: i32, top: i32, right: i32, bottom: i32) -> Option<([i32; 2], [u32; 2])> { + let width = u32::try_from(right.checked_sub(left)?).ok().filter(|w| *w > 0)?; + let height = u32::try_from(bottom.checked_sub(top)?).ok().filter(|h| *h > 0)?; + Some(([left, top], [width, height])) +} + +/// The platform's window services with a pen or a finger in contact counted as the primary button +/// ([`ContactWindows`]), and the monitors listed through winit. On macOS no monitors are listed: winit +/// gives each display's position in that display's own scale, so the pixel areas of displays with different scales +/// overlap and placement could pick the wrong one. Elsewhere monitors with different scales are not listed either +/// ([`one_scale`]). +pub(super) struct DesktopWindows { + list: Box Option> + Send + Sync>, + now: Box Instant + Send + Sync>, + /// The last listing that succeeded, and when it was made. + listed: Mutex)>>, +} + +impl DesktopWindows { + /// Lists the monitors of `window`'s desktop; none without a window, and none on macOS. + pub(super) fn new(window: Option<&Arc>) -> Self { + let window = if cfg!(target_os = "macos") { Weak::new() } else { window.map_or_else(Weak::new, Arc::downgrade) }; + Self::with(move || window.upgrade().and_then(|window| monitor_layout(&window)).map(|(monitors, _)| monitors), Instant::now) + } + + /// Lists the monitors with `list` (`None` when a listing fails), timed by `now`. + fn with(list: impl Fn() -> Option> + Send + Sync + 'static, now: impl Fn() -> Instant + Send + Sync + 'static) -> Self { + Self { list: Box::new(list), now: Box::new(now), listed: Mutex::default() } + } +} + +impl WindowSystem for DesktopWindows { + fn desktop_pointer(&self) -> Option<[f32; 2]> { + ContactWindows.desktop_pointer() + } + + fn buttons_held(&self) -> Option { + ContactWindows.buttons_held() + } + + fn discard_marked_text(&self) -> bool { + ContactWindows.discard_marked_text() + } + + fn command_held(&self) -> Option { + ContactWindows.command_held() + } + + fn warp_pointer(&self, to: [f32; 2]) -> bool { + ContactWindows.warp_pointer(to) + } + + /// The monitors of the last listing, listed again once [`RELIST_AFTER`] has passed. A listing that fails keeps + /// the last one, and the next call lists again. + fn monitors(&self) -> Vec { + let now = (self.now)(); + let mut listed = self.listed.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((at, monitors)) = listed.as_ref() + && now.saturating_duration_since(*at) < RELIST_AFTER + { + return monitors.clone(); + } + match (self.list)().map(one_scale) { + Some(monitors) => { + *listed = Some((now, monitors.clone())); + monitors + } + None => listed.as_ref().map(|(_, monitors)| monitors.clone()).unwrap_or_default(), + } + } +} + +/// `monitors` when they all have one scale, else none. The framework finds the monitor a palette window is on by +/// testing the window's corner, in the window's own points, at each monitor's scale, so with mixed scales a palette +/// on one monitor can be matched to another and its popups kept in that monitor's work area. Without a listing, +/// popups stay within the span of the app's windows and dialogs reopen where they were saved. +fn one_scale(monitors: Vec) -> Vec { + let mixed = monitors.windows(2).any(|pair| pair[0].scale != pair[1].scale); + if mixed { Vec::new() } else { monitors } +} + +#[cfg(test)] +mod tests { + use super::*; + use craft::behavior::placement::{Defaults, Placement, place}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn monitor(name: &str, pos: [i32; 2], size: [u32; 2], scale: f32) -> Monitor { + Monitor::new(MonitorKey::new(name, size), pos, size, scale) + } + + /// A clock the test moves. + fn clock() -> (Arc>, impl Fn() -> Instant + Send + Sync + 'static) { + let time = Arc::new(Mutex::new(Instant::now())); + let read = Arc::clone(&time); + (time, move || *read.lock().unwrap()) + } + + fn advance(time: &Mutex, by: Duration) { + let mut now = time.lock().unwrap(); + *now += by; + } + + /// The monitors come from the desktop listing, which runs once per [`RELIST_AFTER`] however often placement asks, + /// and a display that changed shows up in the next listing. + #[test] + fn monitors_are_listed_once_a_second_and_follow_display_changes() { + let listings = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&listings); + let (time, now) = clock(); + let system = DesktopWindows::with( + move || { + let n = count.fetch_add(1, Ordering::SeqCst); + let mut monitors = vec![monitor("A", [0, 0], [1920, 1080], 1.0)]; + if n > 0 { + monitors.push(monitor("B", [1920, 0], [2560, 1440], 1.0)); + } + Some(monitors) + }, + now, + ); + let names = |monitors: Vec| monitors.into_iter().map(|m| m.key.name).collect::>(); + assert_eq!(names(system.monitors()), ["A"]); + assert_eq!(names(system.monitors()), ["A"]); + advance(&time, RELIST_AFTER - Duration::from_millis(1)); + assert_eq!(names(system.monitors()), ["A"]); + assert_eq!(listings.load(Ordering::SeqCst), 1, "calls within the reuse time share one listing"); + advance(&time, Duration::from_millis(1)); + assert_eq!(names(system.monitors()), ["A", "B"], "the added display shows up in the next listing"); + assert_eq!(listings.load(Ordering::SeqCst), 2); + } + + /// A listing that fails (a display went away while it was listed) keeps the last monitors, and the next call + /// lists again instead of waiting for the reuse time. + #[test] + fn a_failed_listing_keeps_the_last_monitors() { + let listings = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&listings); + let (time, now) = clock(); + let system = + DesktopWindows::with(move || (count.fetch_add(1, Ordering::SeqCst) == 0).then(|| vec![monitor("A", [0, 0], [1920, 1080], 1.0)]), now); + assert_eq!(system.monitors().len(), 1); + advance(&time, RELIST_AFTER); + assert_eq!(system.monitors().len(), 1, "the failed listing keeps the last one"); + assert_eq!(system.monitors().len(), 1); + assert_eq!(listings.load(Ordering::SeqCst), 3, "each call after a failed listing lists again"); + } + + /// A dialog saved on a monitor that is no longer connected (or at a place no monitor shows) reopens with its whole + /// frame inside a connected monitor's work area, clear of the taskbar. + #[test] + fn a_dialog_saved_off_every_monitor_opens_inside_a_work_area() { + let (_, now) = clock(); + let system = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [1920, 1080], 1.0).with_work_px([0, 0], [1920, 1040])]), now); + let mut saved = Placement::new([600.0, 400.0], 1.0); + saved.position_px = Some([3000, 900]); + let placed = place(Some(&saved), &system.monitors(), None, &Defaults::new([600.0, 400.0], [200.0, 100.0])); + let [x, y] = placed.position_px.expect("the dialog keeps a position"); + let [width, height] = placed.normal.size; + let frame = egui::Rect::from_min_size(egui::pos2(x as f32, y as f32), egui::vec2(width, height)); + let work = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1920.0, 1040.0)); + assert!(work.contains_rect(frame), "{frame:?} is inside {work:?}"); + } + + /// Monitors with different scales are not listed, so a palette's popups on a scale-2 monitor beside a scale-1 one + /// are not kept in the other monitor's work area; monitors that share a scale are listed. + #[test] + fn monitors_with_mixed_scales_are_not_listed() { + let (_, now) = clock(); + let mixed = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [1920, 1080], 1.0), monitor("B", [1920, 0], [3840, 2160], 2.0)]), now); + assert!(mixed.monitors().is_empty(), "mixed scales list no monitors"); + let (_, now) = clock(); + let shared = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [3840, 2160], 1.5), monitor("B", [3840, 0], [3840, 2160], 1.5)]), now); + assert_eq!(shared.monitors().len(), 2, "one scale lists every monitor"); + } + + #[test] + fn work_area_edges_give_corner_and_size() { + assert_eq!(from_edges(-1920, -200, 0, 840), Some(([-1920, -200], [1920, 1040]))); + assert_eq!(from_edges(0, 0, 0, 1040), None, "no width"); + assert_eq!(from_edges(100, 0, 0, 1040), None, "inverted"); + assert_eq!(from_edges(i32::MIN, 0, i32::MAX, 10), None, "overflowing width"); + } +} diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index b8e6b88ee1..155441ae7d 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -28,13 +28,20 @@ //! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel, which //! comes from the tablet driver's Wintab interface instead, when it has one //! ([`crate::windows_wintab`]). +//! +//! The window host reads the mouse buttons Windows reports down ([`ContactWindows`]) to release a +//! press whose release the window never received. A pen or a finger in contact is not a mouse +//! button there, so [`msg_hook`] also notes each pointer in contact, and [`ContactWindows`] reports +//! the primary button down while one is. Otherwise the press of a pen stroke is released on its +//! first move. #![cfg_attr(not(windows), allow(dead_code))] use std::cell::Cell; -use std::sync::OnceLock; +use std::sync::{Mutex, OnceLock, PoisonError}; -use craft::behavior::PointerSample; +use craft::behavior::{Monitor, PointerSample}; use craft::ui::runtime::pen::PenSource; +use craft::window::system::{HeldButtons, SystemWindows, WindowSystem}; /// `POINTER_MESSAGE_FLAG_SECONDBUTTON` (`winuser.h`): in the high word of a pointer message's /// `wParam`, a pen in contact with its barrel button pressed. @@ -44,6 +51,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020; const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002; /// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled. const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000; +/// `POINTER_MESSAGE_FLAG_INCONTACT` (`winuser.h`): a pen or a finger touching the surface. +const POINTER_MESSAGE_FLAG_INCONTACT: usize = 0x0004; /// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`. const PEN_FLAG_INVERTED: u32 = 0x0002; const PEN_FLAG_ERASER: u32 = 0x0004; @@ -67,6 +76,8 @@ const WM_POINTERDOWN: u32 = 0x0246; const WM_POINTERUP: u32 = 0x0247; const WM_POINTERENTER: u32 = 0x0249; const WM_POINTERLEAVE: u32 = 0x024A; +/// `WM_POINTERCAPTURECHANGED` (`winuser.h`): another window took the pointer's capture. +const WM_POINTERCAPTURECHANGED: u32 = 0x024C; /// A pen's tilt along x and y and its barrel rotation, in radians. type Pose = ([f32; 2], f32); @@ -81,6 +92,84 @@ thread_local! { /// The pen source [`msg_hook`] writes, once [`start`] has made it. static FEED: OnceLock = OnceLock::new(); +/// The ids of the pointers in contact (pens and fingers), from [`msg_hook`]. +static CONTACTS: Mutex> = Mutex::new(Vec::new()); + +/// The running platform's window services ([`SystemWindows`]), with the primary button reported +/// down while a pen or a finger is in contact. +pub struct ContactWindows; + +impl WindowSystem for ContactWindows { + fn desktop_pointer(&self) -> Option<[f32; 2]> { + SystemWindows.desktop_pointer() + } + + fn buttons_held(&self) -> Option { + let in_contact = !CONTACTS.lock().unwrap_or_else(PoisonError::into_inner).is_empty(); + with_contact(SystemWindows.buttons_held(), in_contact) + } + + fn discard_marked_text(&self) -> bool { + SystemWindows.discard_marked_text() + } + + fn command_held(&self) -> Option { + SystemWindows.command_held() + } + + fn warp_pointer(&self, to: [f32; 2]) -> bool { + SystemWindows.warp_pointer(to) + } + + fn monitors(&self) -> Vec { + SystemWindows.monitors() + } +} + +/// The buttons `held` with the primary one added while a pointer is `in_contact`; `None` where the +/// platform tells nothing. +fn with_contact(held: Option, in_contact: bool) -> Option { + held.map(|mut held| { + if in_contact { + held.insert(HeldButtons::PRIMARY); + } + held + }) +} + +/// The pointer a message with this `wParam` is about, and whether it is now in contact: a pointer +/// that goes down or moves with `POINTER_MESSAGE_FLAG_INCONTACT` and no cancel is; one that hovers, +/// is canceled, goes up, leaves or loses its capture to another window is not. `None` for any other +/// message. +fn contact_update(message: u32, wparam: usize) -> Option<(u32, bool)> { + let id = (wparam & 0xffff) as u32; + let flags = wparam >> 16; + match message { + WM_POINTERDOWN | WM_POINTERUPDATE => Some((id, flags & POINTER_MESSAGE_FLAG_INCONTACT != 0 && flags & POINTER_MESSAGE_FLAG_CANCELED == 0)), + WM_POINTERUP | WM_POINTERLEAVE | WM_POINTERCAPTURECHANGED => Some((id, false)), + _ => None, + } +} + +/// Notes in `contacts` the pointer that a message with this `wParam` puts in or out of contact +/// ([`contact_update`]). A mouse message that a mouse made (`from_mouse`) ends every contact, so a +/// contact whose end went to another window does not hold the primary button for the mouse. +/// A pointer goes into contact only when `watched` returns true: the thread's hook that sees its +/// sent leave and capture change is installed. Otherwise a later message of the contact tries +/// again. Returns whether the message put a pointer in contact. +fn follow_contact(contacts: &mut Vec, message: u32, wparam: usize, from_mouse: impl FnOnce() -> bool, watched: impl FnOnce() -> bool) -> bool { + match contact_update(message, wparam) { + Some((id, true)) if !contacts.contains(&id) && watched() => { + contacts.push(id); + return true; + } + Some((id, false)) => contacts.retain(|c| *c != id), + None if MOUSE_MESSAGES.contains(&message) && !contacts.is_empty() && from_mouse() => contacts.clear(), + _ => {} + } + false +} + /// The canvas's pen source, which [`msg_hook`] writes before winit handles each message. pub fn start() -> PenSource { FEED.get_or_init(PenSource::default).clone() @@ -99,6 +188,12 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { let Some(msg) = (unsafe { msg.cast::().as_ref() }) else { return false; }; + // SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message. + let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32); + // The contact's sent leave and capture change come through the thread's hook, so a contact is + // noted only once the hook is installed. + let watched = || crate::windows_wintab::hook_sent_messages(msg.time); + follow_contact(&mut CONTACTS.lock().unwrap_or_else(PoisonError::into_inner), msg.message, msg.wParam.0, from_mouse, watched); let Some(pen) = FEED.get() else { return false; }; @@ -119,8 +214,6 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation); Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose, wheel)) }; - // SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message. - let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32); if let Some(sample) = feed_update(msg.message, msg.wParam.0, read_pen, from_mouse) { // The barrel goes first: the contact's press reads it with the sample. pen.set_barrel(sample.is_some() && (msg.wParam.0 >> 16) & POINTER_MESSAGE_FLAG_SECONDBUTTON != 0); @@ -130,14 +223,15 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { } /// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags` -/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen -/// in contact that reports none; the eraser end while it is inverted or its eraser button is +/// reports: the pressure it reports, 0 included, which a pen in contact can report as its tip touches +/// down and lifts (#10231), 0 while it hovers, and a full press for a pen in contact that reports +/// none; the eraser end while it is inverted or its eraser button is /// pressed; how it is held, `pose` ([`pen_pose`]); and `wheel`, the airbrush finger wheel the tablet /// driver's Wintab interface reported for the message, if any ([`crate::windows_wintab`]), kept /// within 0..1 and none when it is not a number. fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose, wheel: Option) -> PointerSample { let pressure = match pressure { - 1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0, + 0..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0, _ if in_contact => 1.0, _ => 0.0, }; @@ -187,9 +281,13 @@ fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { /// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on /// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as -/// [`msg_hook`] does for the messages it sees. +/// [`msg_hook`] does for the messages it sees, and a pointer that leaves it or loses its capture is +/// no longer in contact. #[cfg(windows)] pub fn sent_message(message: u32, wparam: usize) { + if matches!(message, WM_POINTERLEAVE | WM_POINTERCAPTURECHANGED) { + follow_contact(&mut CONTACTS.lock().unwrap_or_else(PoisonError::into_inner), message, wparam, || false, || true); + } if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) { crate::windows_wintab::forget(); } @@ -318,16 +416,86 @@ mod tests { } #[test] - fn a_pens_pressure_is_the_one_winit_gives_its_touch() { + fn a_pen_that_reports_pressure_keeps_zero_at_the_ends_of_a_stroke() { assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 0.5); assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0); assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT, None), eraser_sample(0.0), "hovering"); assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pen in contact that reports no pressure presses fully"); assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pressure without the pressure mask is not one"); - assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0, "as winit, which gives no force for 0"); + assert_eq!( + pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, + 0.0, + "a tip that touches down or lifts with no pressure does not press fully" + ); + assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_ERASER, true, UPRIGHT, None), eraser_sample(0.0), "the eraser end too"); assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT, None).pressure, 0.0); } + #[test] + fn a_pointer_in_contact_holds_the_primary_button() { + assert_eq!(with_contact(Some(HeldButtons::NONE), true), Some(HeldButtons::PRIMARY), "a pen stroke while no mouse button is down"); + assert_eq!(with_contact(Some(HeldButtons::NONE), false), Some(HeldButtons::NONE)); + let held = with_contact(Some(HeldButtons::SECONDARY), true).unwrap_or_default(); + assert!(held.contains(HeldButtons::PRIMARY) && held.contains(HeldButtons::SECONDARY), "the mouse's own buttons stay"); + assert_eq!(with_contact(None, true), None, "a platform that tells nothing still tells nothing"); + } + + #[test] + fn a_pen_stroke_is_in_contact_from_its_down_to_its_up() { + let flags = |f: usize| (f << 16) | 7; + let touching = flags(POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_INCONTACT); + let no_mouse = || -> bool { panic!("a pointer message is not a mouse message") }; + let follow = |contacts: &mut Vec, message: u32, wparam: usize| follow_contact(contacts, message, wparam, no_mouse, || true); + let mut contacts = vec![]; + follow(&mut contacts, WM_POINTERUPDATE, flags(POINTER_MESSAGE_FLAG_INRANGE)); + assert!(contacts.is_empty(), "a hovering pen is in no contact"); + assert!(follow(&mut contacts, WM_POINTERDOWN, touching), "the pen goes into contact"); + assert_eq!(contacts, [7], "the pen touches down"); + assert!(!follow(&mut contacts, WM_POINTERUPDATE, touching), "it is already in contact"); + assert_eq!(contacts, [7], "and stays in contact while it moves"); + follow(&mut contacts, WM_POINTERDOWN, (POINTER_MESSAGE_FLAG_INCONTACT << 16) | 9); + follow(&mut contacts, WM_POINTERUP, flags(POINTER_MESSAGE_FLAG_INRANGE)); + assert_eq!(contacts, [9], "the pen goes up and a finger stays down"); + follow(&mut contacts, WM_POINTERUPDATE, ((POINTER_MESSAGE_FLAG_INCONTACT | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 9); + assert!(contacts.is_empty(), "a canceled contact ends"); + follow(&mut contacts, WM_POINTERDOWN, touching); + follow(&mut contacts, WM_POINTERLEAVE, 7); + assert!(contacts.is_empty(), "a pointer that leaves the window ends its contact"); + follow(&mut contacts, WM_POINTERDOWN, touching); + follow(&mut contacts, WM_POINTERCAPTURECHANGED, 7); + assert!(contacts.is_empty(), "a pointer whose capture another window took ends its contact"); + + // WM_LBUTTONDOWN. + follow(&mut contacts, WM_POINTERDOWN, touching); + follow_contact(&mut contacts, 0x0201, 0, || false, || true); + assert_eq!(contacts, [7], "a mouse message Windows made from the pen keeps the contact"); + follow_contact(&mut contacts, 0x0201, 0, || true, || true); + assert!(contacts.is_empty(), "a press of the mouse ends a contact whose end never arrived"); + // WM_KEYDOWN. + follow(&mut contacts, WM_POINTERDOWN, touching); + follow_contact(&mut contacts, 0x0100, 0, || -> bool { panic!("not a mouse message") }, || true); + assert_eq!(contacts, [7]); + } + + #[test] + fn a_contact_is_noted_only_while_its_end_can_arrive() { + let touching = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_INCONTACT) << 16) | 7; + let no_mouse = || -> bool { panic!("a pointer message is not a mouse message") }; + let mut contacts = vec![]; + assert!(!follow_contact(&mut contacts, WM_POINTERDOWN, touching, no_mouse, || false), "the hook did not install"); + assert!(contacts.is_empty(), "a contact whose leave could not arrive is not noted"); + assert!(follow_contact(&mut contacts, WM_POINTERUPDATE, touching, no_mouse, || true), "the next move tries again"); + assert_eq!(contacts, [7]); + let asked = std::cell::Cell::new(false); + follow_contact(&mut contacts, WM_POINTERUPDATE, touching, no_mouse, || { + asked.set(true); + true + }); + assert!(!asked.get(), "a pointer already in contact does not install the hook again"); + follow_contact(&mut contacts, WM_POINTERUP, 7, no_mouse, || -> bool { panic!("an up is not a contact") }); + assert!(contacts.is_empty()); + } + #[test] fn mouse_messages_from_a_pen_or_a_touch_are_told_apart() { assert!(is_mouse(0), "a mouse"); diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index 31da32a1ff..50ccff2af8 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -625,7 +625,7 @@ fn message(message: u32, wparam: usize, lparam: isize) -> Message { } #[cfg(windows)] -pub use win::{forget, msg_hook, pen_wheel, set_wheel_used, wheel_pen}; +pub use win::{forget, hook_sent_messages, msg_hook, pen_wheel, set_wheel_used, wheel_pen}; #[cfg(windows)] #[allow(unsafe_code)] @@ -758,8 +758,9 @@ mod win { /// The thread's hook on the messages Windows sends to its windows' procedures, which winit's /// message hook does not see: another app becoming the active one (`WM_ACTIVATEAPP`, sent to a /// top-level window of the app, ) - /// closes the context ([`deactivate`]), and a pen's `WM_POINTERENTER` and `WM_POINTERLEAVE` - /// () go to + /// closes the context ([`deactivate`]), and a pointer's `WM_POINTERENTER`, `WM_POINTERLEAVE` + /// () and + /// `WM_POINTERCAPTURECHANGED` go to /// [`crate::windows_stylus::sent_message`]. The hook sees them whichever of the app's windows /// they are sent to (). unsafe extern "system" fn call_wnd_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { @@ -1089,6 +1090,13 @@ mod win { settle(); } + /// Installs [`call_wnd_proc`] for a pointer that went into contact at the message time `time`, + /// so the pointer's sent `WM_POINTERLEAVE` and `WM_POINTERCAPTURECHANGED` reach + /// [`crate::windows_stylus::sent_message`] whether or not a context opens ([`hook_thread`]). + pub fn hook_sent_messages(time: u32) -> bool { + hook_thread(time) + } + /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer /// id `pen` ([`Readings::owner_or`]). pub fn wheel_pen(pen: u32) -> u32 { diff --git a/crates/cad/src/blocks_compat.rs b/crates/cad/src/blocks_compat.rs deleted file mode 100644 index bcc4860314..0000000000 --- a/crates/cad/src/blocks_compat.rs +++ /dev/null @@ -1,115 +0,0 @@ -//! 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 -} diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs index 4b9cf7f902..babf160149 100644 --- a/crates/cad/src/dwg.rs +++ b/crates/cad/src/dwg.rs @@ -245,9 +245,11 @@ fn convert(bytes: &[u8]) -> Result { Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() }) } -/// Can a DWG file of `version` be written? craft-dwg writes 2000, 2004, 2007, 2010, 2013 and 2018. +/// Can a DWG file of `version` be written? DWG export writes 2000, 2004, 2007, 2010, 2013 and 2018. craft-dwg also +/// writes R13 and R14, which DWG export does not offer yet. pub fn writes(version: crate::DxfVersion) -> bool { - craft_dwg::VERSIONS.iter().any(|(code, _)| *code == version.acadver()) + !matches!(version, crate::DxfVersion::R12 | crate::DxfVersion::R13 | crate::DxfVersion::R14) + && craft_dwg::VERSIONS.iter().any(|(code, _)| *code == version.acadver()) } /// A DWG file of `version` from `dxf`, an ASCII DXF of that version as [`crate::export_drawings`] diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index f4c4cf99c8..af90b84748 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -19,10 +19,10 @@ //! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths. //! - `hatch`: pattern hatches' lines and gradient hatches' fills. //! - `text`: text values to plain text. -//! - `acis`: a region's solid-modeler data as its outline. //! - `build`: items to the document. +//! +//! A region's solid-modeler data becomes its outline in `craft_dxf::acis`. -mod acis; mod build; mod curve; mod entity; diff --git a/crates/cad/src/import/acis.rs b/crates/cad/src/import/acis.rs deleted file mode 100644 index 581e168625..0000000000 --- a/crates/cad/src/import/acis.rs +++ /dev/null @@ -1,779 +0,0 @@ -//! The solid-modeler data of a REGION as a filled outline: each face's loops of edges, in world x -//! and y (drawing units). The data comes as text (DXF before 2013, ciphered or not) or binary -//! (DXF 2013 and later keep it in the ACDSDATA section). -//! -//! The model is a list of records pointing at each other: a body holds lumps, a lump shells, a -//! shell faces, a face loops, a loop a ring of coedges. Each coedge uses an edge (forward or -//! reversed), and each edge runs between two vertices along a line, an ellipse or a spline. A -//! curve of any other kind comes in as a straight line between its vertices. -//! -//! The REGION groups are in the DXF Reference -//! (); which -//! DXF versions hold text and which binary data is in . - -use std::collections::HashMap; - -use kurbo::{BezPath, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathSeg}; -use vectorcraft_geom::{Affine, Point}; - -use super::curve; - -/// The most bytes of one region's data read. -pub(crate) const MAX_BYTES: usize = 16 << 20; -/// The most records one region's outline may visit: bodies, lumps, shells, faces and coedges -/// (a loop counts as one at least). -const MAX_VISITS: usize = 1_000_000; -/// The first bytes of binary data: ACIS's, or ASM's (DXF 2018 writes either). -const BINARY_MAGIC: [&[u8]; 2] = [b"ACIS BinaryFile", b"ASM BinaryFile4"]; -/// From this version on, every record starts with its attribute, a history number and one more -/// pointer; before it, with its attribute alone. -const LONG_HEADER_VERSION: u32 = 700; - -type P3 = [f64; 3]; -/// A B-spline: degree, knots, control points, weights (none: all 1). -type Spline = (usize, Vec, Vec, Option>); - -/// One value of a record. -#[derive(Clone, Debug, PartialEq)] -enum Tok { - Ptr(i64), - Num(f64), - Word(String), - /// `forward` (false) or `reversed` (true). - Sense(bool), - Open, - Close, -} - -/// A record: its type (`body`, `plane-surface`…) and its values after the ones every record -/// starts with. -#[derive(Debug)] -struct Rec { - kind: String, - toks: Vec, -} - -impl Rec { - /// The type `base` or one derived from it (`tedge-edge` is an edge). - fn is(&self, base: &str) -> bool { - self.kind == base || self.kind.strip_suffix(base).is_some_and(|k| k.ends_with('-')) - } - - /// The `n`th pointer (-1: none). - fn ptr(&self, n: usize) -> i64 { - self.toks.iter().filter_map(|t| if let Tok::Ptr(p) = t { Some(*p) } else { None }).nth(n).unwrap_or(-1) - } - - /// The sense right after the `n`th pointer: true when reversed (old files write 1). - fn sense_after(&self, n: usize) -> Option { - let mut ptrs = 0; - for t in &self.toks { - if ptrs > n { - return match t { - Tok::Sense(r) => Some(*r), - Tok::Num(v) if v.is_finite() => Some(*v != 0.0), - _ => None, - }; - } - if matches!(t, Tok::Ptr(_)) { - ptrs += 1; - } - } - None - } - - /// The numbers, in order. - fn nums(&self) -> Vec { - self.toks.iter().filter_map(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect() - } -} - -/// The records of one body, and how pointers find them. -struct Model { - recs: Vec, - /// Record number by index, when the records carry their own. - at: HashMap, -} - -impl Model { - fn get(&self, p: i64) -> Option<&Rec> { - if p < 0 { - return None; - } - if self.at.is_empty() { self.recs.get(usize::try_from(p).ok()?) } else { self.recs.get(*self.at.get(&p)?) } - } - - /// The record `p` points at when it is of type `base`. - fn get_is(&self, p: i64, base: &str) -> Option<&Rec> { - self.get(p).filter(|r| r.is(base)) - } - - /// The records of type `base` from `first` along their `next` pointer (pointer `next`), each - /// once. Missing records, wrong types and cycles outside coedge rings set `broken`. - fn chain(&self, first: i64, base: &str, next: usize, broken: &mut bool) -> Vec<&Rec> { - let mut out = vec![]; - let mut seen = std::collections::HashSet::new(); - let mut p = first; - while p >= 0 { - if !seen.insert(p) { - *broken |= base != "coedge"; - break; - } - let Some(r) = self.get_is(p, base) else { - *broken = true; - break; - }; - out.push(r); - p = r.ptr(next); - } - out - } -} - -/// A region's outline: its faces' loops, closed; `approximated` when an edge of a curve type -/// this reader doesn't draw came in as a straight line; `broken` when a topology chain breaks -/// off or a loop's ring of coedges doesn't come back to its first; `ambiguous` when an edge's -/// endpoint lies on separate parts of its curve. -#[derive(Debug)] -pub(crate) struct Outline { - pub path: BezPath, - pub approximated: bool, - pub broken: bool, - pub ambiguous: bool, -} - -/// Text data, ciphered as DXF writes it or not. -pub(crate) fn from_text(text: &str) -> Option { - if text.len() > MAX_BYTES { - return None; - } - let plain; - let text = if text.trim_start().starts_with(|c: char| c.is_ascii_digit()) { - text - } else { - plain = decipher(text); - &plain - }; - outline(&sat_model(text)?) -} - -/// Binary data. -pub(crate) fn from_binary(bytes: &[u8]) -> Option { - if bytes.len() > MAX_BYTES { - return None; - } - outline(&sab_model(bytes)?) -} - -/// DXF's cipher of text data undone: each printable character is mapped back, and the space -/// written after a mapped `A` (a caret, which DXF reads as a control code) is dropped. -fn decipher(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - let mut chars = s.chars().peekable(); - while let Some(c) = chars.next() { - out.push(match c { - ' ' | '\n' | '\r' | '\t' => c, - '@'..='_' => char::from(159 - c as u8), - c if c.is_ascii() && !c.is_ascii_control() => char::from(c as u8 ^ 0x5F), - c => c, - }); - if c == '^' && chars.peek() == Some(&' ') { - chars.next(); - } - } - out -} - -/// How many values every record starts with in data of `version`. -fn header_len(version: u32) -> usize { - if version >= LONG_HEADER_VERSION { 3 } else { 1 } -} - -/// A text value as a value. -fn sat_tok(w: &str) -> Tok { - match w { - "{" => Tok::Open, - "}" => Tok::Close, - "forward" | "forward_v" => Tok::Sense(false), - "reversed" | "reversed_v" => Tok::Sense(true), - _ => { - if let Some(p) = w.strip_prefix('$').and_then(|p| p.parse::().ok()) { - return Tok::Ptr(p); - } - match w.parse::() { - Ok(v) if v.is_finite() => Tok::Num(v), - _ => Tok::Word(w.to_string()), - } - } - } -} - -/// Does this line start a record (`[-] $ …`)? -fn starts_record(line: &str) -> bool { - let mut words = line.split_whitespace(); - let first = words.next().unwrap_or_default(); - let (kind, next) = if first.starts_with('-') && first[1..].parse::().is_ok() { - (words.next().unwrap_or_default(), words.next().unwrap_or_default()) - } else { - (first, words.next().unwrap_or_default()) - }; - kind.starts_with(|c: char| c.is_ascii_alphabetic()) && next.starts_with('$') -} - -/// Text data's records: a version line, product and tolerance lines, then records ending in `#`. -fn sat_model(text: &str) -> Option { - let version = text.split_whitespace().next()?.parse::().ok().filter(|v| v.is_finite() && *v >= 0.0)? as u32; - let skip = header_len(version); - let mut offset = text.find('\n')? + 1; - let start = loop { - let rest = text.get(offset..)?; - let line = rest.split('\n').next().unwrap_or_default(); - if starts_record(line) { - break offset; - } - offset += line.len() + 1; - }; - let body = text.get(start..)?; - let (mut recs, mut at) = (Vec::new(), HashMap::new()); - let mut cur: Vec = vec![]; - let (mut kind, mut index): (Option, Option) = (None, None); - let mut i = 0; - let b = body.as_bytes(); - while i < b.len() { - if b[i].is_ascii_whitespace() { - i += 1; - continue; - } - let end = b[i..].iter().position(u8::is_ascii_whitespace).map_or(b.len(), |n| i + n); - let word = body.get(i..end)?; - i = end; - // A counted string: `@`, a space, then n bytes. - if let Some(n) = word.strip_prefix('@').and_then(|n| n.parse::().ok()) { - let from = (i + 1).min(b.len()); - let to = from.checked_add(n)?.min(b.len()); - cur.push(Tok::Word(body.get(from..to)?.to_string())); - i = to; - continue; - } - let (word, ends) = match word.strip_suffix('#') { - Some(w) => (w, true), - None => (word, false), - }; - if !word.is_empty() { - match &kind { - None if index.is_none() && word.starts_with('-') && word[1..].parse::().is_ok() => { - index = word[1..].parse().ok(); - } - None => { - if word.starts_with("End-of-") || word.starts_with("Begin-of-") { - break; - } - kind = Some(word.to_string()); - } - Some(_) => cur.push(sat_tok(word)), - } - } - if ends { - let toks = cur.split_off(skip.min(cur.len())); - cur.clear(); - if let Some(n) = index.take() { - at.insert(n, recs.len()); - } - recs.push(Rec { kind: kind.take().unwrap_or_default(), toks }); - } - } - Some(Model { recs, at }) -} - -/// Reads binary data's little-endian values. -struct Bytes<'b> { - b: &'b [u8], - i: usize, -} - -impl Bytes<'_> { - fn take(&mut self, n: usize) -> Option<&[u8]> { - let s = self.b.get(self.i..self.i.checked_add(n)?)?; - self.i += n; - Some(s) - } - fn u8(&mut self) -> Option { - self.take(1).map(|s| s[0]) - } - fn i16(&mut self) -> Option { - self.take(2).map(|s| f64::from(i16::from_le_bytes([s[0], s[1]]))) - } - fn u16(&mut self) -> Option { - self.take(2).map(|s| usize::from(u16::from_le_bytes([s[0], s[1]]))) - } - fn i32(&mut self) -> Option { - self.take(4).map(|s| i32::from_le_bytes([s[0], s[1], s[2], s[3]])) - } - fn u32(&mut self) -> Option { - self.take(4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) - } - fn f64(&mut self) -> Option { - let s = self.take(8)?; - Some(f64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])) - } - fn text(&mut self, n: usize) -> Option { - self.take(n).map(|s| String::from_utf8_lossy(s).into_owned()) - } -} - -/// Binary data's records: the magic, four numbers (version first), product and tolerance values, -/// then records of tagged values, each type name made of its parts. -fn sab_model(b: &[u8]) -> Option { - let mut r = Bytes { b: BINARY_MAGIC.iter().find_map(|m| b.strip_prefix(*m))?, i: 0 }; - let version = r.u32()?; - r.take(12)?; - let skip = header_len(version); - let mut recs = vec![]; - let (mut parts, mut kind, mut cur): (Vec, Option, Vec) = (vec![], None, vec![]); - while r.i < r.b.len() { - let tag = r.u8()?; - let tok = match tag { - 0x02 => Tok::Num(f64::from(i8::from_le_bytes([r.u8()?]))), - 0x03 => Tok::Num(r.i16()?), - 0x04 | 0x15 => Tok::Num(f64::from(r.i32()?)), - 0x05 => Tok::Num(f64::from(f32::from_le_bytes(r.take(4)?.try_into().ok()?))), - 0x06 | 0x17 => Tok::Num(r.f64()?), - 0x07 => { - let n = usize::from(r.u8()?); - Tok::Word(r.text(n)?) - } - 0x08 => { - let n = r.u16()?; - Tok::Word(r.text(n)?) - } - 0x09 | 0x12 => { - let n = usize::try_from(r.u32()?).ok()?; - Tok::Word(r.text(n)?) - } - 0x0A => Tok::Sense(true), - 0x0B => Tok::Sense(false), - 0x0C => Tok::Ptr(i64::from(r.i32()?)), - 0x0D | 0x0E => { - let n = usize::from(r.u8()?); - let name = r.text(n)?; - if kind.is_some() { - Tok::Word(name) - } else { - parts.push(name); - if tag == 0x0D { - let k = parts.join("-"); - parts.clear(); - if k.starts_with("End-of-") || k.starts_with("Begin-of-") { - break; - } - kind = Some(k); - } - continue; - } - } - 0x0F => Tok::Open, - 0x10 => Tok::Close, - 0x11 => { - if let Some(k) = kind.take() { - let toks = cur.split_off(skip.min(cur.len())); - recs.push(Rec { kind: k, toks }); - } - cur.clear(); - continue; - } - 0x13 | 0x14 => { - for _ in 0..3 { - cur.push(Tok::Num(r.f64()?)); - } - continue; - } - 0x16 => { - for _ in 0..2 { - cur.push(Tok::Num(r.f64()?)); - } - continue; - } - _ => return None, - }; - // Values before the first record are the header's. - if kind.is_some() { - cur.push(tok); - } - } - Some(Model { recs, at: HashMap::new() }) -} - -/// A body's placement: `p · m · scale + t`. -#[derive(Clone, Copy)] -struct Xf { - m: [P3; 3], - scale: f64, - t: P3, -} - -impl Xf { - const IDENTITY: Xf = Xf { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], scale: 1.0, t: [0.0; 3] }; - - /// A `transform` record's: nine matrix numbers row by row, the translation, the scale. - fn read(r: &Rec) -> Option { - let n: Vec = r.toks.iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect(); - if n.iter().any(|v| !v.is_finite()) { - return None; - } - let v = |i: usize| n.get(i).copied(); - let row = |i: usize| Some([v(i)?, v(i + 1)?, v(i + 2)?]); - let scale = v(12)?; - Some(Xf { m: [row(0)?, row(3)?, row(6)?], t: row(9)?, scale }) - } - - fn vector(&self, p: P3) -> P3 { - let [a, b, c] = self.m; - std::array::from_fn(|i| (p[0] * a[i] + p[1] * b[i] + p[2] * c[i]) * self.scale) - } - - fn point(&self, p: P3) -> P3 { - let v = self.vector(p); - std::array::from_fn(|i| v[i] + self.t[i]) - } -} - -/// Seen from above: x and y. -fn flat(p: P3) -> Point { - Point::new(p[0], p[1]) -} - -fn sub(a: P3, b: P3) -> P3 { - [a[0] - b[0], a[1] - b[1], a[2] - b[2]] -} - -fn dot(a: P3, b: P3) -> f64 { - a[0] * b[0] + a[1] * b[1] + a[2] * b[2] -} - -fn cross(a: P3, b: P3) -> P3 { - [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] -} - -fn p3(n: &[f64], i: usize) -> Option { - Some([*n.get(i)?, *n.get(i + 1)?, *n.get(i + 2)?]) -} - -/// Endpoints farther apart than rounding at their coordinate size allows. -fn endpoints_apart(a: Point, b: Point) -> bool { - a.distance(b) > 1e-6 * (1.0 + a.x.hypot(a.y).max(b.x.hypot(b.y))) -} - -/// Every face's loops of every body, as one path (filled even-odd). -fn outline(m: &Model) -> Option { - let mut o = Outline { path: BezPath::new(), approximated: false, broken: false, ambiguous: false }; - // Records visited at every level together: chains shared between records are walked again - // each time. - let mut visits = 0usize; - let mut spend = |n: usize| { - visits = visits.saturating_add(n.max(1)); - (visits <= MAX_VISITS).then_some(()) - }; - for body in m.recs.iter().filter(|r| r.is("body")) { - spend(1)?; - let xf = if body.ptr(2) == -1 { Xf::IDENTITY } else { Xf::read(m.get_is(body.ptr(2), "transform")?)? }; - for lump in m.chain(body.ptr(0), "lump", 0, &mut o.broken) { - spend(1)?; - for shell in m.chain(lump.ptr(1), "shell", 0, &mut o.broken) { - spend(1)?; - for face in m.chain(shell.ptr(2), "face", 0, &mut o.broken) { - spend(1)?; - for lp in m.chain(face.ptr(1), "loop", 0, &mut o.broken) { - let ring = m.chain(lp.ptr(1), "coedge", 0, &mut o.broken); - spend(ring.len())?; - let complete = ring.last().is_some_and(|c| c.ptr(0) == lp.ptr(1)); - o.broken |= !complete; - let mut bp = BezPath::new(); - for c in ring { - let edge = m.get_is(c.ptr(3), "edge")?; - let (seg, ambiguous) = edge_path(m, edge, c.sense_after(3)?, &xf, &mut o.approximated)?; - o.ambiguous |= ambiguous; - if let (Some(end), Some(start)) = - (bp.elements().last().and_then(|e| e.end_point()), seg.elements().first().and_then(|e| e.end_point())) - { - o.broken |= endpoints_apart(end, start); - } - super::entity::append(&mut bp, &seg); - if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS { - return None; - } - } - if !bp.elements().is_empty() { - if complete - && let (Some(end), Some(start)) = - (bp.elements().last().and_then(|e| e.end_point()), bp.elements().first().and_then(|e| e.end_point())) - { - o.broken |= endpoints_apart(end, start); - } - // A loop of one curve ending where it starts is split in two: as one - // segment, its start and end would become one anchor. - if let [seg] = bp.segments().collect::>()[..] - && !matches!(seg, PathSeg::Line(_)) - { - let (a, b) = seg.subdivide(); - bp = BezPath::from_path_segments([a, b].into_iter()); - } - bp.close_path(); - if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS { - return None; - } - o.path.extend(bp); - } - } - } - } - } - } - let ok = !o.path.elements().is_empty() && curve::bounds(&o.path).is_some(); - ok.then_some(o) -} - -/// A vertex's position. -fn vertex(m: &Model, p: i64) -> Option { - let v = m.get_is(p, "vertex")?; - let n = m.get_is(v.ptr(1), "point")?.nums(); - p3(&n, 0).filter(|p| p.iter().all(|c| c.is_finite())) -} - -/// The edge as a coedge runs it (`reversed`: from its end vertex to its start), from the first -/// point. -fn edge_path(m: &Model, edge: &Rec, reversed: bool, xf: &Xf, approximated: &mut bool) -> Option<(BezPath, bool)> { - let (sv, ev) = (vertex(m, edge.ptr(0))?, vertex(m, edge.ptr(1))?); - let closed = edge.ptr(0) == edge.ptr(1); - let (from, to) = if reversed { (ev, sv) } else { (sv, ev) }; - // Against the curve's own direction? - let back = edge.sense_after(3)? != reversed; - let drawn = match m.get(edge.ptr(3)) { - // Only -1 means the edge has no curve. - None => { - *approximated |= edge.ptr(3) != -1; - None - } - Some(c) if c.is("straight-curve") => None, - Some(c) => { - let bp = if c.is("ellipse-curve") { - ellipse(c, from, to, closed, back, xf).map(|bp| (bp, false)) - } else if c.is("intcurve-curve") { - spline(c, from, to, closed, back, xf) - } else { - None - }; - *approximated |= bp.is_none(); - bp - } - }; - if let Some(bp) = drawn { - return Some(bp); - } - let mut bp = BezPath::new(); - bp.move_to(flat(xf.point(from))); - bp.line_to(flat(xf.point(to))); - Some((bp, false)) -} - -/// An `ellipse-curve` (centre, normal, major axis, ratio) from `from` to `to`; the whole curve -/// when the edge starts and ends at one vertex. It runs counter-clockwise about its normal, -/// clockwise when `back`. -fn ellipse(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option { - let n = c.nums(); - let (centre, normal, major, ratio) = (p3(&n, 0)?, p3(&n, 3)?, p3(&n, 6)?, *n.get(9)?); - let len = dot(normal, normal).sqrt(); - if !(len > 1e-12 && ratio > 0.0 && ratio.is_finite() && dot(major, major) > 1e-24) { - return None; - } - let minor = cross(normal, major).map(|v| v / len * ratio); - let angle = |p: P3| { - let d = sub(p, centre); - (dot(d, minor) / dot(minor, minor)).atan2(dot(d, major) / dot(major, major)) - }; - let (a, b) = (angle(from), angle(to)); - let tau = std::f64::consts::TAU; - let sweep = match (closed, back) { - (true, false) => tau, - (true, true) => -tau, - (false, false) => (b - a).rem_euclid(tau), - (false, true) => -(a - b).rem_euclid(tau), - }; - let (o, u, v) = (flat(xf.point(centre)), flat(xf.vector(major)), flat(xf.vector(minor))); - curve::ellipse(Affine::new([u.x, u.y, v.x, v.y, o.x, o.y]), a, sweep) -} - -/// An `intcurve-curve`'s B-spline (`nubs`, or `nurbs` with weights): degree, form, the knots -/// with their multiplicities (without the end knots, or with them), the control points. -fn bspline(toks: &[Tok]) -> Option { - let at = toks.iter().position(|t| matches!(t, Tok::Word(w) if matches!(w.as_str(), "nubs" | "nurbs" | "nullbs")))?; - let rational = match &toks[at] { - Tok::Word(w) if w == "nurbs" => true, - Tok::Word(w) if w == "nubs" => false, - _ => return None, - }; - let num = |i: usize| if let Some(Tok::Num(v)) = toks.get(i) { Some(*v) } else { None }; - let degree = num(at + 1).filter(|d| (1.0..=32.0).contains(d))? as usize; - let count = num(at + 3).filter(|n| *n >= 1.0 && *n <= toks.len() as f64)? as usize; - let mut knots = vec![]; - let mut i = at + 4; - for _ in 0..count { - let (k, mult) = (num(i)?, num(i + 1)?); - if !(mult >= 1.0 && mult <= (degree + 1) as f64) { - return None; - } - knots.extend(std::iter::repeat_n(k, mult as usize)); - i += 2; - } - let stride = if rational { 4 } else { 3 }; - let values: Vec = toks[i.min(toks.len())..].iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect(); - let available = values.len() / stride; - // The data leaves out the first and last knots; data that keeps them has two points fewer. - let short = (knots.len() + 1).checked_sub(degree)?; - let n = if available >= short { - let (first, last) = (*knots.first()?, *knots.last()?); - knots.insert(0, first); - knots.push(last); - short - } else { - knots.len().checked_sub(degree + 1)? - }; - if n == 0 || n > available { - return None; - } - let pts = values.chunks(stride).take(n).map(|c| [c[0], c[1], c[2]]).collect(); - let weights = rational.then(|| values.chunks(stride).take(n).map(|c| c[3]).collect()); - Some((degree, knots, pts, weights)) -} - -/// The distinct parameters of a cubic's self-intersection, when both lie on the curve. -fn cubic_crossing(cubic: kurbo::CubicBez) -> Option<(f64, f64)> { - let b = (cubic.p1 - cubic.p0) * 3.0; - let c = (cubic.p2 - cubic.p1) * 3.0 - b; - let d = (cubic.p3 - cubic.p0) - b - c; - let det = c.cross(d); - if det == 0.0 { - return None; - } - // Dividing P(s) - P(t) by s - t gives b + c*u + d*(u*u - v) = 0, - // where u = s + t and v = s*t. - let u = -b.cross(d) / det; - let v = u * u - b.cross(c) / det; - let discriminant = u * u - 4.0 * v; - if !discriminant.is_finite() || discriminant <= 0.0 { - return None; - } - let root = discriminant.sqrt(); - let (s, t) = ((u - root) * 0.5, (u + root) * 0.5); - (0.0 <= s && s < t && t <= 1.0).then_some((s, t)) -} - -/// An `intcurve-curve` from `from` to `to` (the part of its spline between them), the whole -/// ring when the edge starts and ends at one vertex; also whether trimming is ambiguous. -fn spline(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option<(BezPath, bool)> { - // The curve's own sense comes before its data. - let open = c.toks.iter().position(|t| *t == Tok::Open)?; - let curve_back = c.toks[..open].contains(&Tok::Sense(true)); - let (degree, knots, pts, weights) = bspline(&c.toks[open..])?; - let ctrl: Vec = pts.into_iter().map(|p| flat(xf.point(p))).collect(); - let full = curve::nurbs(degree, &knots, &ctrl, weights.as_deref())?; - let back = back != curve_back; - let segs: Vec = full.segments().collect(); - let (first, last) = (segs.first()?.start(), segs.last()?.end()); - let ring = first.distance(last) <= 1e-9 * (1.0 + first.to_vec2().hypot()); - let mut lengths = vec![0.0]; - for s in &segs { - lengths.push(lengths.last()? + s.arclen(1e-9)); - } - let total = *lengths.last()?; - let at = |p: P3| { - let p = flat(xf.point(p)); - let near: Vec<_> = segs.iter().enumerate().map(|(i, s)| (s.nearest(p, 1e-9), i)).collect(); - let (n, i) = near.iter().min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq))?; - let along = |i: usize, t: f64| lengths[i] + segs[i].subsegment(0.0..t).arclen(1e-9); - let tolerance = 1e-6 * (1.0 + p.x.hypot(p.y)); - let mut locations: Vec<_> = - near.iter().filter(|(n, i)| !endpoints_apart(p, segs[*i].eval(n.t))).map(|(n, i)| (*i as f64 + n.t, along(*i, n.t))).collect(); - for (i, s) in segs.iter().enumerate() { - if let PathSeg::Cubic(cubic) = s - && let Some((a, b)) = cubic_crossing(*cubic) - && !endpoints_apart(p, cubic.eval(a)) - { - locations.extend([a, b].map(|t| (i as f64 + t, along(i, t)))); - } - } - // Nearby ends at a segment joint, or at a closed curve's seam, are one location. - locations.sort_by(|a, b| a.0.total_cmp(&b.0)); - locations.dedup_by(|a, b| (a.1 - b.1).abs() <= 4.0 * tolerance); - if ring && locations.len() > 1 && (total - (locations.last()?.1 - locations.first()?.1)).abs() <= 4.0 * tolerance { - locations.pop(); - } - Some((*i as f64 + n.t, locations)) - }; - let mut ambiguous = false; - let part = if closed && ring { - let (_, locations) = at(from)?; - ambiguous = locations.len() > 1; - full - } else { - let bounds = if closed { - let (_, locations) = at(from)?; - if let [a, b] = locations.as_slice() { - Some((a.0, b.0)) - } else { - ambiguous = true; - None - } - } else { - let ((ga, a), (gb, b)) = (at(from)?, at(to)?); - ambiguous = a.len() > 1 || b.len() > 1; - Some((ga, gb)) - }; - if let Some((ga, gb)) = bounds { - let (lo, hi) = if back { (gb, ga) } else { (ga, gb) }; - let pieces = if lo <= hi || !ring { - piece(&segs, lo.min(hi), hi.max(lo)) - } else { - [piece(&segs, lo, segs.len() as f64), piece(&segs, 0.0, hi)].concat() - }; - if pieces.is_empty() { - return None; - } - BezPath::from_path_segments(pieces.into_iter()) - } else { - full - } - }; - Some((if back { part.reverse_subpaths() } else { part }, ambiguous)) -} - -/// The parts of `segs` from `lo` to `hi`, counted in segments (2.5: halfway along the third). -fn piece(segs: &[PathSeg], lo: f64, hi: f64) -> Vec { - let mut out = vec![]; - for (i, s) in segs.iter().enumerate() { - let (t0, t1) = ((lo - i as f64).max(0.0), (hi - i as f64).min(1.0)); - if t1 > t0 { - out.push(s.subsegment(t0..t1)); - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cubic_crossings_have_two_distinct_parameters() { - let cubic = kurbo::CubicBez::new((36.0, -18.0), (-28.0, 26.0), (-28.0, -26.0), (36.0, 18.0)); - let (s, t) = cubic_crossing(cubic).unwrap(); - assert!((s - 0.25).abs() < 1e-12 && (t - 0.75).abs() < 1e-12, "{s}, {t}"); - let plain = kurbo::CubicBez::new((0.0, 0.0), (30.0, 50.0), (70.0, -50.0), (100.0, 0.0)); - assert!(cubic_crossing(plain).is_none()); - } - - #[test] - fn deciphering_maps_each_character_back_and_drops_the_caret_space() { - // "Ab@_ 7#" ciphered: A→^ (and a space), b→=, @→_, _→@, 7→h, #→|. - assert_eq!(decipher("^ =_@ h|"), "Ab@_ 7#"); - } -} diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 98f28f6ebc..11bfac399c 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -28,8 +28,19 @@ const THINNEST: f64 = 0.25; /// The most objects an import makes. const MAX_NODES: usize = if cfg!(test) { 100_000 } else { 2_000_000 }; /// The most block work an import does, whatever it produces: one per insert copy drawn, and one -/// per item of the block looked at for it (art on hidden layers too). +/// per item of the block looked at for it (art on hidden layers too), and the same for each block +/// whose dashes and widths are checked for a symbol's scale. const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 }; +/// The most scale checks kept for one block at one depth that left out a block inside itself +/// under different ancestors. +const MAX_SCANS_HERE: usize = 16; +/// The most blocks the checks of which blocks a block places look at in one import; past it the +/// checks take the art as different for each placement (a symbol of its own). +const MAX_SHAPE_WORK: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 }; +/// The most bytes of block names the shape checks keep in their sets of placed blocks. +const MAX_REACH_KEPT: usize = if cfg!(test) { 1_000_000 } else { 32_000_000 }; +/// The most "yes" scale scans kept for one block and what it inherits. +const MAX_SCALED_YES: usize = 4; /// The most path elements an import makes (blocks drawn as art are copied for every placement). pub(crate) const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 }; /// The most dash lengths an import keeps (every dashed path holds its own copy of its pattern). @@ -52,6 +63,7 @@ const TOO_MANY: &str = "the drawing has more than 2,000,000 objects: the rest ar const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points: the rest are left out"; const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to place: the rest are left out"; const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid"; +const TOO_SMALL: &str = "block copies drawn too small to place are left out"; const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out"; const NO_IMAGE_FILE: &str = "images that name no image file are left out"; const FAR_CLIPS: &str = "images whose clip boundaries reach out of range are left out"; @@ -86,6 +98,47 @@ struct Inherit { layer: Option, } +/// A symbol's block, what it inherits, the scale slot, the depth when the nesting limit may cut +/// off its art, and its ancestors that it places (sorted). +type SymbolKey = (String, Inherit, u64, Option, Vec>); + +/// A shape check's block, its levels to the nesting limit and the ancestors it holds for. +type ShapeKey = (Rc, u32, Vec>); + +/// The blocks a block places within some levels (`None`: the shape checks' budgets ran out). +type Reach = Option>>; + +/// A kept scale scan: the shallowest and deepest depths it holds at, whether the nesting limit +/// cut off art, and the blocks it went into to reach dashes or wide polylines. +type ScaledLook = (u32, u32, bool, Rc>); + +/// A scale scan of a block that left out a block inside itself: its answer, whether the nesting +/// limit cut off art, the blocks it went into and the ones it left out. +#[derive(Debug)] +struct ScanHere { + scaled: bool, + cut: bool, + reached: HashSet, + left_out: HashSet, +} + +/// A step of the scale scan in progress: a block it went into, a block it left out as a block +/// inside itself, or a kept scan it reused. +#[derive(Debug)] +enum Trail { + Went(String), + LeftOut(String), + Reused(Rc), +} + +/// What tells two [`Trail`] steps apart: a block's name, or which kept scan was reused. +#[derive(PartialEq, Eq, Hash)] +enum TrailKey { + Went(String), + LeftOut(String), + Reused(*const ScanHere), +} + /// Objects, path elements, dash lengths and text bytes taken from the import's limits. #[derive(Clone, Copy, Debug, Default)] struct Cost { @@ -124,8 +177,38 @@ pub(crate) struct Build<'d, 'a> { blocks: HashMap>>, bounds: HashMap>, sensitive: HashMap, - /// Symbol names by block and what it inherits (`None`: the block has no art). - symbols: HashMap<(String, Inherit), Option>, + /// Symbol names by block, what it inherits, the scale its art is drawn at (the bits of + /// [`symbol_scale`]'s answer), the depth when the nesting limit may cut off some of its art + /// there, and the ancestors it places, which are left out of its art (`None`: the block has + /// no art). + symbols: HashMap>, + /// The blocks a block places within some levels below itself (see [`Build::reach_within`]). + reaches: HashMap, + /// The blocks each block places directly (see [`Build::placed_blocks`]). + placed: HashMap>>, + /// How many levels of blocks a block draws below itself (see [`Build::height_under`]). + block_height: HashMap, + /// Whether a block placed with so many levels left before the nesting limit reaches it (see + /// [`Build::reaches_limit`]). + limit_reached: HashMap, + /// The ancestors a block places, by block, levels to the nesting limit and ancestors. + ancestors_placed: HashMap>>, + /// One shared copy of each ancestor name the keys above hold. + interned: HashSet>, + /// The steps the shape checks have taken (see [`Build::shape_step`]). + shape_work: usize, + /// How many bytes of names the kept sets of `reaches` hold. + reach_kept: usize, + /// Whether a block placed with what it inherits draws dashes or wide polylines, whose + /// lengths and widths follow the insert's scale: the depths each answer holds at, whether + /// the nesting limit cut off art, and for a "yes" the blocks it went into to reach the dashes + /// or wide polylines (see [`Build::scaled_look`]). + /// A "yes" keeps up to [`MAX_SCALED_YES`] answers that reached their dashes by different blocks. + scaled_looks: HashMap<(String, Inherit, bool), Vec>, + /// The same answers for scans that left out a block inside itself, by depth. + scaled_looks_here: HashMap<(String, Inherit, u32), Vec>>, + /// The steps of the scale scan in progress. + scan_trail: Vec, /// Names of the symbols made so far, and the next suffix to try for each label. symbol_names: HashSet, next_suffix: HashMap, @@ -206,6 +289,17 @@ impl<'d, 'a> Build<'d, 'a> { bounds: HashMap::new(), sensitive: HashMap::new(), symbols: HashMap::new(), + reaches: HashMap::new(), + placed: HashMap::new(), + shape_work: 0, + reach_kept: 0, + limit_reached: HashMap::new(), + ancestors_placed: HashMap::new(), + interned: HashSet::new(), + block_height: HashMap::new(), + scaled_looks: HashMap::new(), + scaled_looks_here: HashMap::new(), + scan_trail: Vec::new(), symbol_names: HashSet::new(), next_suffix: HashMap::new(), stack: vec![], @@ -418,6 +512,185 @@ impl<'d, 'a> Build<'d, 'a> { true } + /// The blocks block `name` places directly, once each (inserts on a hidden layer other than + /// layer 0 are left out, as `art` leaves them out), or `None` when it is missing or an + /// external reference. Read once per block. + fn placed_blocks(&mut self, name: &str) -> Option>> { + if let Some(p) = self.placed.get(name) { + return Some(p.clone()); + } + if !self.blocks.contains_key(name) && self.d.blocks.get(name).is_none_or(|b| b.xref) { + return None; + } + let items = self.block(name)?; + let mut seen = HashSet::new(); + let mut placed = vec![]; + for it in items.iter() { + if let Geom::Insert(ins) = &it.geom + && !(it.props.layer != "0" && self.d.layer(&it.props.layer).is_some_and(|l| l.hidden)) + && seen.insert(ins.block.as_str()) + { + placed.push(ins.block.clone()); + } + } + let placed = Rc::new(placed); + self.placed.insert(name.to_string(), placed.clone()); + Some(placed) + } + + /// The shared copy of block name `name`. + fn intern(&mut self, name: &str) -> Rc { + if let Some(n) = self.interned.get(name) { + return n.clone(); + } + let n: Rc = Rc::from(name); + self.interned.insert(n.clone()); + n + } + + /// Counts one step of the shape checks against their import-wide budget; false once it is + /// spent, when the checks give their cautious answers. + fn shape_step(&mut self) -> bool { + self.shape_work = self.shape_work.saturating_add(1); + self.shape_work <= MAX_SHAPE_WORK + } + + /// The blocks block `name` places within `levels` levels below itself, not looking below an + /// ancestor (only blocks drawn above the nesting limit are read), or `None` when the shape + /// checks' budgets ran out. + fn reach_within(&mut self, name: &str, levels: u32) -> Option>> { + // A set that met no ancestor is kept for any ancestors that it does not hold, where it + // meets none either; one cut short at an ancestor is kept for these ancestors alone. + let open = (self.intern(name), levels, vec![]); + if let Some(r) = self.reaches.get(&open) + && r.as_ref().is_none_or(|r| !self.stack.iter().any(|s| r.contains(s))) + { + return r.clone(); + } + let stack: Vec> = self.stack.clone().iter().map(|s| self.intern(s)).collect(); + let key = (open.0.clone(), levels, stack); + if let Some(r) = self.reaches.get(&key) { + return r.clone(); + } + // Past the shape checks' budget the block is taken to place every ancestor. The kept + // entries hold at most `MAX_REACH_KEPT` bytes in all (names, with a word or so of overhead + // each, and each key's ancestors); past it a result is used without being kept. + let mut seen = HashSet::new(); + let mut size = 64usize.saturating_add(key.2.len().saturating_mul(16)); + // An ancestor is left out where it is placed, so nothing is looked at below it. + let stack = self.stack.clone(); + let mut stopped_at_ancestor = false; + let mut layer = vec![name.to_string()]; + let mut complete = true; + 'levels: for _ in 0..levels { + let mut next = vec![]; + for n in &layer { + for child in self.placed_blocks(n).unwrap_or_default().iter() { + if !self.shape_step() { + complete = false; + break 'levels; + } + if seen.contains(child) { + continue; + } + size = size.saturating_add(child.len().saturating_add(32)); + seen.insert(child.clone()); + if stack.contains(child) { + stopped_at_ancestor = true; + } else { + next.push(child.clone()); + } + } + } + if next.is_empty() { + break; + } + layer = next; + } + let r = complete.then(|| Rc::new(seen)); + if !complete { + size = 64usize.saturating_add(key.2.len().saturating_mul(16)); + } + if self.reach_kept.saturating_add(size) <= MAX_REACH_KEPT { + self.reach_kept += size; + self.reaches.insert(if stopped_at_ancestor || !complete { key } else { open }, r.clone()); + } + r + } + + /// Does block `name` placed `depth` deep draw blocks down to the nesting limit, which then + /// cuts off art? Counted under `ancestors`, the ancestors it places, which are left out, as is + /// a block inside itself. Yes when the shape checks' budget ran out. + fn reaches_limit(&mut self, name: &str, depth: u32, ancestors: &[Rc]) -> bool { + let limit = match MAX_NEST.checked_sub(depth) { + Some(limit) if limit > 0 => limit, + _ => return true, + }; + let key = (self.intern(name), limit, ancestors.to_vec()); + if let Some(r) = self.limit_reached.get(&key) { + return *r; + } + let r = self.height_under(name, limit, &mut ancestors.iter().map(|a| a.to_string()).collect()).0.is_none(); + if self.shape_work <= MAX_SHAPE_WORK { + self.limit_reached.insert(key, r); + } + r + } + + /// How many levels of blocks block `name` draws below itself under the blocks in `path`, or + /// `None` for `limit` levels or more (`limit` is at least 1); with the shallowest index in + /// `path` of a block it left out as a block inside itself (`usize::MAX`: none). Each child + /// looked at counts against the shape checks' budget. Only blocks drawn above the limit are + /// read. + fn height_under(&mut self, name: &str, limit: u32, path: &mut Vec) -> (Option, usize) { + if let Some(&h) = self.block_height.get(name) { + return ((h < limit).then_some(h), usize::MAX); + } + if !self.shape_step() { + return (None, 0); + } + path.push(name.to_string()); + let mut h = Some(0); + let mut hit = usize::MAX; + for child in self.placed_blocks(name).unwrap_or_default().iter() { + if !self.shape_step() { + (h, hit) = (None, 0); + break; + } + // A missing block draws nothing at any depth. + if !self.blocks.contains_key(child) && self.d.blocks.get(child).is_none_or(|b| b.xref) { + continue; + } + // A block inside itself is left out. + if let Some(i) = path.iter().position(|p| p == child) { + hit = hit.min(i); + continue; + } + // A child at the limit is not drawn, and is not read. + if limit == 1 { + h = None; + break; + } + let (child_h, child_hit) = self.height_under(child, limit - 1, path); + hit = hit.min(child_hit); + h = h.zip(child_h).map(|(a, b)| a.max(b.saturating_add(1))); + if h.is_none() { + break; + } + } + path.pop(); + // A count that left out a block inside itself anywhere below may count a path that is a + // loop under other ancestors, and one stopped at the limit may not have looked at every + // child, so only a complete count with neither is kept. + if let Some(h) = h + && hit == usize::MAX + && self.shape_work <= MAX_SHAPE_WORK + { + self.block_height.insert(name.to_string(), h); + } + (h, hit) + } + /// A block's bounds in its coordinates less its base point. fn block_bounds(&mut self, name: &str, depth: u32) -> Option { if let Some(b) = self.bounds.get(name) { @@ -817,7 +1090,9 @@ impl<'d, 'a> Build<'d, 'a> { // Text space is y-down points; the item's is y-up drawing units. let m = map * t.xf * Affine::FLIP_Y; let s = m.determinant().abs().sqrt(); - if !(s > 1e-12 && s.is_finite()) { + // Any invertible map will do: a symbol drawn at a tiny insert scale draws its text far + // below a point per unit, and its instances scale it back up. + if !(s > 0.0 && s.is_finite() && s.recip().is_finite()) { return None; } let d = self.d; @@ -937,15 +1212,39 @@ impl<'d, 'a> Build<'d, 'a> { let base = self.d.blocks.get(&ins.block).map_or(Point::ZERO, |b| b.base); let unbase = Affine::translate(-base.to_vec2()); let anonymous = ins.block.starts_with('*'); - // An empty symbol is drawn again only for a cell that places an instance of it. - let symbol = if anonymous { None } else { self.symbol(&ins.block, &child, depth, false) }; - // The symbol's art when this insert took it out. - let mut taken = None; + // The art of each symbol this insert took out, by symbol (cells at other scales place + // other symbols). + let mut taken: HashMap> = HashMap::new(); let mut parts = vec![]; + // An array's cells share their scale: the symbol is looked up again only when it changes. + let mut last: Option<(f64, Option<(String, f64)>)> = None; for cell in &ins.cells { - let node = match &symbol { - Some(name) => { - let xf = map * *cell * self.symbol_map.inverse(); + if anonymous { + parts.extend(self.art(&ins.block, map * *cell * unbase, &child, depth)); + continue; + } + let scale = symbol_scale(map * *cell, self.symbol_map); + let symbol = match &last { + Some((s, symbol)) if s.to_bits() == scale.to_bits() => symbol.clone(), + _ => { + // An empty symbol is drawn again only for a cell that places an instance of it. + let symbol = self.symbol(&ins.block, &child, scale, depth, false); + last = Some((scale, symbol.clone())); + symbol + } + }; + let node = match symbol { + Some((name, drawn_at)) => { + let name = &name; + // The symbol's art is drawn `drawn_at` times larger than a drawing unit at the + // import's scale; the instance takes the rest of the transform. The two factors + // are inverted apart, so a tiny `drawn_at` at a tiny fitted scale does not + // overflow the inverse of their product. + let xf = map * *cell * Affine::scale(drawn_at.recip()) * self.symbol_map.inverse(); + if !xf.as_coeffs().iter().all(|c| c.is_finite()) { + self.warn(TOO_SMALL); + continue; + } // Its image clips where this instance places them: inside another symbol, their // box joins that symbol's; else, when it may leave the canvas, this placement // draws the block's art, which checks each clip where it lands. @@ -960,8 +1259,8 @@ impl<'d, 'a> Build<'d, 'a> { self.warn(TOO_MANY); break; } - let back = taken.take().is_some_and(|art| self.restore(name, art)); - if !back && self.symbol(&ins.block, &child, depth, true).is_none() { + let back = taken.remove(name).is_some_and(|art| self.restore(name, art)); + if !back && self.symbol(&ins.block, &child, scale, depth, true).is_none() { continue; } reach = reach_of(self); @@ -972,8 +1271,10 @@ impl<'d, 'a> Build<'d, 'a> { // This placement draws the art instead of the symbol. The art of a symbol // no instance places yet is taken out, so that it isn't kept and charged // as well; an instance in a later cell puts it back. - if taken.is_none() { - taken = self.take_unused(name); + if !taken.contains_key(name) + && let Some(art) = self.take_unused(name) + { + taken.insert(name.clone(), art); } if self.nodes >= MAX_NODES { self.warn(TOO_MANY); @@ -998,7 +1299,6 @@ impl<'d, 'a> Build<'d, 'a> { self.nodes += 1; Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf })) } - None if anonymous => self.art(&ins.block, map * *cell * unbase, &child, depth), None => None, }; parts.extend(node); @@ -1049,17 +1349,263 @@ impl<'d, 'a> Build<'d, 'a> { } } - /// The symbol for block `name` placed with `inh` (made once per look). One whose art was - /// taken out is drawn again when `draw` is set, and else returned empty. - fn symbol(&mut self, name: &str, inh: &Inherit, depth: u32, draw: bool) -> Option { + /// Does block `name` placed with `inh` at `depth` draw dashes or wide polylines (its own art + /// or that of the blocks it places)? Also the depths the answer holds at (shallowest, + /// deepest). A scan cut short by the nesting limit may miss art that a shallower placement + /// draws, so a "no" holds only from the depth it was made at; a complete "no" holds from + /// depth 0. A "yes" holds at every depth from which the dashes or wide polylines it found are + /// still within the nesting limit. A "no" that left out a block inside itself, or that the + /// work budget stopped, holds nowhere. Last, whether the nesting limit cut off any of the + /// block's art at this depth. `nested` is set when the scan of an enclosing block asks. + fn scaled_look(&mut self, name: &str, inh: &Inherit, depth: u32, nested: bool) -> (bool, (u32, u32), bool, Rc>) { + // A block inside itself is left out only under this chain of ancestors, so the answer + // holds nowhere else. It is left out at any depth, so the nesting limit cuts off nothing. + if self.stack.iter().any(|s| s == name) { + self.warn(NESTED); + self.scan_trail.push(Trail::LeftOut(name.to_string())); + return (false, (u32::MAX, 0), false, Rc::default()); + } + let items = self.block(name); + // A placement past the nesting limit draws none of the block, so its items are not + // looked at or charged for, and no answer made at a shallower depth applies. + if items.is_some() && depth >= MAX_NEST { + self.warn(NESTED); + return (false, (depth, u32::MAX), true, Rc::default()); + } + // A block can have a "yes" for shallow placements and a "no" for deep ones, so each answer + // is kept with its own depths. A "yes" holds only while none of the blocks it went into to + // reach the dashes or wide polylines is an ancestor, which would leave them out. + let key = (name.to_string(), inh.clone()); + for s in [true, false] { + let stack = &self.stack; + if let Some((lo, hi, cut, via)) = self + .scaled_looks + .get(&(key.0.clone(), key.1.clone(), s)) + .and_then(|answers| answers.iter().find(|(lo, hi, _, via)| (*lo..=*hi).contains(&depth) && !via.iter().any(|v| stack.contains(v)))) + { + return (s, (*lo, *hi), *cut, via.clone()); + } + } + let context = (key.0.clone(), key.1.clone(), depth); + let stack = &self.stack; + let here = self.scaled_looks_here.get(&context).and_then(|answers| { + // The scan holds again when it would leave out the same ancestors: each block it + // left out is still an ancestor, and no block it went into is one. + answers.iter().find(|a| a.left_out.iter().all(|l| stack.contains(l)) && !stack.iter().any(|s| a.reached.contains(s))) + }); + if let Some(a) = here.cloned() { + // Which of the blocks it went into hold the dashes is not kept, so all of them count. + let via = Rc::new(if a.scaled { a.reached.iter().cloned().collect() } else { vec![] }); + if !nested { + return (a.scaled, (u32::MAX, 0), a.cut, via); + } + let (scaled, cut) = (a.scaled, a.cut); + // The scan in progress keeps one reference to it, not a copy of its names (see + // `keep_new_steps`). + self.scan_trail.push(Trail::Reused(a)); + return (scaled, (u32::MAX, 0), cut, via); + } + let trail_start = self.scan_trail.len(); + // Looking at a block's items counts against the block work as placing it does, so the + // scan stops at the same limit as `art`. + self.visits = self.visits.saturating_add(1 + items.as_ref().map_or(0, |i| i.len())); + if self.visits > MAX_VISITS { + self.warn(TOO_MUCH_BLOCK_WORK); + return (false, (u32::MAX, 0), false, Rc::default()); + } + let Some(items) = items else { return (false, (0, u32::MAX), false, Rc::default()) }; + if !self.enter(name, depth) { + return (false, (depth, u32::MAX), true, Rc::default()); + } + self.scan_trail.push(Trail::Went(name.to_string())); + // The steps this scan has recorded, so that each is kept once. + let mut seen = HashSet::from([TrailKey::Went(name.to_string())]); + let mut stopped = false; + let mut s = false; + let mut from = 0; + let mut cut = false; + // The blocks gone into to reach the art that made `s`. + let mut via = Rc::default(); + // The deepest placement at which the art that made `s` is still drawn. + let mut until = MAX_NEST - 1; + for it in items.iter() { + #[cfg(test)] + SCALED_LOOK_ITEMS.with(|n| n.set(n.get().saturating_add(1))); + // Art on a hidden layer is not drawn (see `art`), so it does not make the block's + // look depend on its scale. + if self.d.layer(self.layer_name(&it.props, inh)).is_some_and(|l| l.hidden) && it.props.layer != "0" { + continue; + } + s = match &it.geom { + Geom::Path { fill: true, .. } => false, + Geom::Path { width, .. } => { + *width > 0.0 || self.d.linetypes.get(&self.linetype(&it.props, inh)).is_some_and(|p| p.iter().take(64).any(|v| *v < 0.0)) + } + // Gradients fill, and pattern lines carry their own dashes at the lineweight. + Geom::Shaded { .. } | Geom::Text(_) | Geom::Image(_) => false, + Geom::Insert(ins) => { + let child = self.inherit(&it.props, inh); + // An anonymous block is drawn with all it inherits (see `insert`); a named one + // is looked up as its symbol is. + let keep = ins.block.starts_with('*') || self.is_sensitive(&ins.block, depth + 1); + let child = if keep { child } else { Inherit::default() }; + let mark = self.scan_trail.len(); + let (scaled, (child_lo, child_hi), child_cut, child_via) = self.scaled_look(&ins.block, &child, depth + 1, true); + if !self.keep_new_steps(mark, &mut seen) { + stopped = true; + break; + } + cut |= child_cut; + if scaled { + until = child_hi.saturating_sub(1); + let mut v = Vec::with_capacity(child_via.len() + 1); + v.push(ins.block.clone()); + v.extend(child_via.iter().cloned()); + via = Rc::new(v); + } else { + from = from.max(child_lo.saturating_sub(1)); + } + scaled + } + }; + if s { + break; + } + } + self.stack.pop(); + if stopped { + return (false, (u32::MAX, 0), false, Rc::default()); + } + let holds = if s { (0, until) } else { (from, u32::MAX) }; + if (holds.0..=holds.1).contains(&depth) { + let answers = self.scaled_looks.entry((key.0, key.1, s)).or_default(); + // A "no" replaces the one before; a "yes" is kept beside others, the oldest going first. + if !s { + answers.clear(); + } else if answers.len() >= MAX_SCALED_YES { + answers.remove(0); + } + answers.push((holds.0, holds.1, cut, via.clone())); + } else { + // An answer that left out a block inside itself holds again wherever it would leave + // out the same ancestors. A block left out because the scan itself went into it + // is left out under any ancestors. + let mut reached = HashSet::new(); + let mut hits = HashSet::new(); + let mut reused = HashSet::new(); + for step in self.scan_trail.get(trail_start..).unwrap_or_default() { + match step { + Trail::Went(n) => { + reached.insert(n.clone()); + } + Trail::LeftOut(n) => { + hits.insert(n.clone()); + } + Trail::Reused(a) => { + if reused.insert(Rc::as_ptr(a)) { + reached.extend(a.reached.iter().cloned()); + hits.extend(a.left_out.iter().cloned()); + } + } + } + } + let left_out = hits.into_iter().filter(|n| !reached.contains(n)).collect(); + let answer = Rc::new(ScanHere { scaled: s, cut, reached, left_out }); + // Each lookup tries the kept answers one by one, so few are kept for each block and + // depth: a new one replaces the oldest. + let answers = self.scaled_looks_here.entry(context).or_default(); + if answers.len() >= MAX_SCANS_HERE { + answers.remove(0); + } + answers.push(answer); + #[cfg(test)] + SCANS_HERE_MOST.with(|n| n.set(n.get().max(answers.len()))); + } + (s, holds, cut, via) + } + + /// Keeps the steps recorded on the scan trail from `mark` on that the scan has not recorded + /// yet (`seen`), and drops the rest. A kept reuse of a scan counts against the block work + /// for each block it names, like looking at them. False when that work goes past the budget. + fn keep_new_steps(&mut self, mark: usize, seen: &mut HashSet) -> bool { + let steps: Vec = self.scan_trail.drain(mark..).collect(); + for step in steps { + let key = match &step { + Trail::Went(n) => TrailKey::Went(n.clone()), + Trail::LeftOut(n) => TrailKey::LeftOut(n.clone()), + Trail::Reused(a) => TrailKey::Reused(Rc::as_ptr(a)), + }; + if !seen.insert(key) { + continue; + } + if let Trail::Reused(a) = &step { + self.visits = self.visits.saturating_add(a.reached.len() + a.left_out.len()); + if self.visits > MAX_VISITS { + self.warn(TOO_MUCH_BLOCK_WORK); + return false; + } + } + self.scan_trail.push(step); + } + #[cfg(test)] + SCAN_TRAIL_MOST.with(|n| n.set(n.get().max(self.scan_trail.len()))); + true + } + + /// The symbol for block `name` placed with `inh` at `scale` (from [`symbol_scale`]), made + /// once per look, with the scale its art is drawn at: `scale` when the block draws dashes or + /// wide polylines, else 1. One whose art was taken out is drawn again when `draw` is set, and + /// else returned empty. + fn symbol(&mut self, name: &str, inh: &Inherit, scale: f64, depth: u32, draw: bool) -> Option<(String, f64)> { + // A block inside itself is left out here, without a symbol that other placements would + // find. + if self.stack.iter().any(|s| s == name) { + self.warn(NESTED); + return None; + } let inh = if self.is_sensitive(name, depth) { inh.clone() } else { Inherit::default() }; - let key = (name.to_string(), inh); + self.scan_trail.clear(); + let (scaled, ..) = self.scaled_look(name, &inh, depth, false); + let scale = if scaled { scale } else { 1.0 }; + let slot = scale.to_bits(); + // The art drawn here may also differ by the depth (the nesting limit) and by the + // ancestors it places (left out of it), whatever the scan found before it stopped. The + // depth counts only where the block's art reaches the nesting limit, under any ancestors. + // Only an ancestor it places above the nesting limit changes the art (all of them when the + // checks' budget ran out). + // Down to the nesting limit itself: an ancestor there is left out either way, and counting + // it here keeps it from looking like art the limit cuts off. The answer is kept for these + // ancestors, whether or not the set it came from could be kept. The keys share one copy + // of each ancestor's name. + let levels = MAX_NEST.saturating_sub(depth); + let context: ShapeKey = (self.intern(name), levels, self.stack.clone().iter().map(|s| self.intern(s)).collect()); + let left_out = match self.stack.is_empty() { + true => vec![], + false => match self.ancestors_placed.get(&context) { + Some(found) => found.clone(), + None => { + let reach = self.reach_within(name, levels); + let mut found: Vec> = context.2.iter().filter(|s| reach.as_ref().is_none_or(|r| r.contains(&***s))).cloned().collect(); + found.sort(); + found.dedup(); + // Charged to the same budget as the kept sets. + let size = 64usize.saturating_add(context.2.len().saturating_add(found.len()).saturating_mul(16)); + if self.reach_kept.saturating_add(size) <= MAX_REACH_KEPT { + self.reach_kept += size; + self.ancestors_placed.insert(context, found.clone()); + } + found + } + }, + }; + let deep = self.reaches_limit(name, depth, &left_out); + let key = (name.to_string(), inh, slot, deep.then_some(depth), left_out); if let Some(s) = self.symbols.get(&key) { let s = s.clone()?; if !draw || !self.empty.contains(&s) { - return Some(s); + return Some((s, scale)); } - let (art, reach, cost) = self.symbol_art(name, &key.1, depth); + let (art, reach, cost) = self.symbol_art(name, &key.1, scale, depth); let slot = self.symbol_slot.get(&s).and_then(|i| self.doc.symbols.get_mut(*i)); return match (art, slot) { (Some(art), Some(slot)) => { @@ -1070,7 +1616,7 @@ impl<'d, 'a> Build<'d, 'a> { None => self.symbol_reach.remove(&s), }; self.empty.remove(&s); - Some(s) + Some((s, scale)) } // Nothing of it fits now: what it took goes back, and it stays empty. _ => { @@ -1080,7 +1626,7 @@ impl<'d, 'a> Build<'d, 'a> { } }; } - let (art, reach, cost) = self.symbol_art(name, &key.1, depth); + let (art, reach, cost) = self.symbol_art(name, &key.1, scale, depth); let made = art.map(|art| { let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()); let symbol = unique(label, &mut self.next_suffix, &self.symbol_names); @@ -1094,15 +1640,15 @@ impl<'d, 'a> Build<'d, 'a> { symbol }); self.symbols.insert(key, made.clone()); - made + made.map(|s| (s, scale)) } - /// The art of the symbol for block `name` placed with `inh`, the box of its image clips, and - /// what it took from the limits itself (not the symbols made while drawing it, which other - /// instances may use). - fn symbol_art(&mut self, name: &str, inh: &Inherit, depth: u32) -> (Option, Option, Cost) { + /// The art of the symbol for block `name` placed with `inh`, drawn `scale` times larger, the + /// box of its image clips, and what it took from the limits itself (not the symbols made while + /// drawing it, which other instances may use). + fn symbol_art(&mut self, name: &str, inh: &Inherit, scale: f64, depth: u32) -> (Option, Option, Cost) { let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base); - let map = self.symbol_map * Affine::translate(-base.to_vec2()); + let map = self.symbol_map * Affine::scale(scale) * Affine::translate(-base.to_vec2()); let outer = self.clip_reach.take(); let before = self.cost(); let outer_nested = std::mem::take(&mut self.nested); @@ -1169,6 +1715,19 @@ fn drop_unplaced_symbols(doc: &mut Document) { doc.symbols.retain(|_| keep.next().unwrap_or(false)); } +/// How much larger than `symbol_map` an insert copy drawn by `placed` is (the square root of the +/// ratio of their areas), rounded to 9 significant digits so that copies at one scale share a +/// symbol; 1 when either is degenerate. +fn symbol_scale(placed: Affine, symbol_map: Affine) -> f64 { + let s = (placed.determinant().abs() / symbol_map.determinant().abs()).sqrt(); + if !(s.is_finite() && s > 0.0) { + return 1.0; + } + let digits = 10f64.powi(8 - s.log10().floor() as i32); + let r = (s * digits).round() / digits; + if r.is_finite() && r > 0.0 { r } else { 1.0 } +} + /// Fit text stretched or squeezed across, aligned text scaled as a whole, to run its span /// (`s`: points per drawing unit), measured in the font it is set in. fn fill_span(obj: &mut TextObject, span: Span, s: f64) { @@ -1207,6 +1766,14 @@ fn rgb_color([r, g, b]: [u8; 3]) -> Color { thread_local! { /// How many names [`unique`] tried on this thread (tests). pub(crate) static SYMBOL_NAMES_TRIED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many block items [`Build::scaled_look`] looked at on this thread (tests). + pub(crate) static SCALED_LOOK_ITEMS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The most scale checks [`Build::scaled_look`] kept for one block at one depth on this + /// thread (tests). + pub(crate) static SCANS_HERE_MOST: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The most steps the scan trail of [`Build::scaled_look`] held after reusing a kept scan on + /// this thread (tests). + pub(crate) static SCAN_TRAIL_MOST: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Whether `taken` holds `name`, counted as one name tried (tests). diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index bfe6fe9bd3..d61e001632 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -8,9 +8,10 @@ use kurbo::{BezPath, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Shape}; use vectorcraft_doc::Justify; use vectorcraft_geom::{Affine, Point, Vec2}; +use craft_dxf::acis; use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath}; -use super::acis; +use super::build::MAX_ELEMENTS; use super::curve::{self, Vertex}; use super::hatch::{self, Grad, NoPattern}; use super::reader::{aci_paper, point}; @@ -478,26 +479,12 @@ impl Converter { /// A region as a filled path: its solid-modeler data as text in groups 1 (a line each) and 3 /// (the rest of a long line), or, from DXF 2013 on, binary data kept by handle. fn region(&mut self, e: &EntityRecord<'_>) -> Option { - let g = e.groups(); - let own = g.subclass("AcDbModelerGeometry"); - let tags = if own.0.is_empty() { g.0 } else { own.0 }; - let mut text = String::new(); - for t in tags { - match t.code { - 1 => { - if !text.is_empty() { - text.push('\n'); - } - text.push_str(t.str_ref().unwrap_or_default()); - } - 3 => text.push_str(t.str_ref().unwrap_or_default()), - _ => {} - } - if text.len() > acis::MAX_BYTES { - return None; - } - } - let outline = if text.trim().is_empty() { acis::from_binary(self.regions.get(&e.record().handle()?)?) } else { acis::from_text(&text) }?; + let text = acis::text_data(e)?; + let outline = if text.trim().is_empty() { + acis::from_binary(self.regions.get(&e.record().handle()?)?, MAX_ELEMENTS) + } else { + acis::from_text(&text, MAX_ELEMENTS) + }?; if outline.approximated { self.warn(REGION_CURVES); } diff --git a/crates/cad/src/import/reader.rs b/crates/cad/src/import/reader.rs index 1adc71c563..da72ec714c 100644 --- a/crates/cad/src/import/reader.rs +++ b/crates/cad/src/import/reader.rs @@ -1,7 +1,7 @@ //! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer, //! linetype and text style tables; the blocks; the entities; the layouts; the image files. -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::rc::Rc; use craft_dxf::model::{self, EntityRecord}; @@ -132,7 +132,7 @@ impl<'a> Drawing<'a> { d.images.entry(h).or_insert(ImageFile { path: def.file, size: def.size }); } } - d.regions = Rc::new(region_data(&doc)); + d.regions = Rc::new(craft_dxf::acis::binary_data(&doc)); for b in doc.blocks { if b.name.is_empty() { continue; @@ -169,69 +169,6 @@ impl<'a> Drawing<'a> { } } -/// The binary data of each region in the ACDSDATA section: an `ACDSRECORD` names its entity's -/// handle (320), then holds the bytes (310 chunks) after `2 ASM_Data`, their count in 94. -fn region_data(doc: &model::Document<'_>) -> HashMap> { - let records = doc.entities.iter().chain(doc.blocks.iter().flat_map(|b| &b.entities)); - let wanted: HashSet = records.filter(|e| e.kind == "REGION").filter_map(|e| e.record().handle()).collect(); - let mut out = HashMap::new(); - if wanted.is_empty() { - return out; - } - for section in doc.other_sections.iter().filter(|s| s.name.eq_ignore_ascii_case("ACDSDATA")) { - for r in model::records(section.tags).into_iter().filter(|r| r.kind == "ACDSRECORD") { - let Some(handle) = r.tags.iter().find(|t| t.code == 320).and_then(|t| model::parse_handle(&t.str())) else { continue }; - if !wanted.contains(&handle) || out.contains_key(&handle) { - continue; - } - let Some(at) = r.tags.iter().position(|t| t.code == 2 && t.str_ref().is_some_and(|s| s.trim() == "ASM_Data")) else { continue }; - let data = r.tags.get(at + 1..).unwrap_or_default(); - let size = data.iter().find(|t| t.code == 94).and_then(|t| usize::try_from(t.i64()).ok()); - let mut bytes = Vec::new(); - let mut whole = true; - for t in data.iter().filter(|t| t.code == 310) { - whole = hex_bytes(t.str_ref().unwrap_or_default().trim(), &mut bytes); - if !whole || bytes.len() > super::acis::MAX_BYTES { - break; - } - } - if !whole { - continue; - } - if let Some(bytes) = sized_region(bytes, size, super::acis::MAX_BYTES) { - out.insert(handle, bytes); - } - } - } - out -} - -/// A region's `bytes` cut to its declared `size`, or `None` when the record declares more bytes -/// than it holds (the data was cut short or damaged) or the data is longer than `limit`. -pub(super) fn sized_region(mut bytes: Vec, size: Option, limit: usize) -> Option> { - match size { - Some(n) if n <= bytes.len() => bytes.truncate(n), - Some(_) => return None, - None => {} - } - (bytes.len() <= limit).then_some(bytes) -} - -/// Hex digits' bytes, two digits each, onto `out`. False when `hex` has a character that is not -/// a hex digit or an odd number of digits. -pub(super) fn hex_bytes(hex: &str, out: &mut Vec) -> bool { - let digit = |c: u8| (c as char).to_digit(16).and_then(|d| u8::try_from(d).ok()); - let (pairs, rest) = hex.as_bytes().as_chunks::<2>(); - if !rest.is_empty() { - return false; - } - for pair in pairs { - let (Some(hi), Some(lo)) = (digit(pair[0]), digit(pair[1])) else { return false }; - out.push(hi << 4 | lo); - } - true -} - pub(crate) fn point(p: model::Point) -> Point { Point::new(p[0], p[1]) } diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 2731979702..097cdd375c 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -1445,6 +1445,1222 @@ fn by_block_colours_make_a_symbol_per_look() { assert_eq!(doc.symbols.len(), 1); } +/// The dash pattern and weight of the stroke of `n` (a path) or its first loop (a compound path). +fn dash_and_weight(n: &Node) -> (Vec, f64) { + let n = match &n.kind { + NodeKind::Path { .. } => n, + _ => n.children().and_then(|c| c.first()).map(|c| &**c).unwrap_or_else(|| panic!("no path: {:?}", n.kind)), + }; + let s = n.appearance.stroke().unwrap_or_else(|| panic!("no stroke: {:?}", n.appearance)); + (s.dash.as_ref().map(|d| d.pattern.clone()).unwrap_or_default(), s.width) +} + +/// The strokes of `inst`'s symbol's art (and of the symbols it places): each path's dash +/// pattern and weight, in paint order. +fn instance_strokes(doc: &Document, inst: &Node) -> Vec<(Vec, f64)> { + let NodeKind::SymbolInstance { symbol, .. } = &inst.kind else { panic!("{:?}", inst.kind) }; + let art = &doc.symbols.iter().find(|s| &s.name == symbol).unwrap().art; + let mut out = vec![]; + let mut walk = vec![art.clone()]; + while let Some(n) = walk.pop() { + match &n.kind { + NodeKind::Path { .. } => out.push(dash_and_weight(&n)), + NodeKind::SymbolInstance { .. } => out.extend(instance_strokes(doc, &n)), + _ => walk.extend(n.children().into_iter().flatten().rev().cloned()), + } + } + out +} + +#[test] +fn scaled_inserts_scale_their_blocks_dashes_and_polyline_widths() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "Mark": a dashed line with a 0.5 mm lineweight and a polyline 2 units wide. "Pair" places + // "Mark" at scale 1, so the scale of an insert of "Pair" reaches it. + let blocks = [ + (0, "BLOCK"), + (8, "0"), + (2, "Mark"), + (70, "0"), + (10, "0"), + (20, "0"), + (0, "LINE"), + (8, "0"), + (6, "DASHED"), + (370, "50"), + (10, "0"), + (20, "0"), + (11, "100"), + (21, "0"), + (0, "LWPOLYLINE"), + (8, "0"), + (90, "2"), + (70, "0"), + (43, "2"), + (10, "0"), + (20, "10"), + (10, "100"), + (20, "10"), + (0, "ENDBLK"), + (0, "BLOCK"), + (8, "0"), + (2, "Pair"), + (70, "0"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (8, "0"), + (2, "Mark"), + (10, "0"), + (20, "0"), + (0, "ENDBLK"), + ]; + let inserts = [ + (0, "INSERT"), + (2, "Mark"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (2, "Mark"), + (10, "0"), + (20, "100"), + (41, "10"), + (42, "10"), + (0, "INSERT"), + (2, "Pair"), + (10, "0"), + (20, "300"), + (41, "10"), + (42, "10"), + (0, "INSERT"), + (2, "Mark"), + (10, "0"), + (20, "500"), + (41, "10"), + (42, "10"), + ]; + let doc = open(&drawing(&[], &tables, &blocks, &inserts), &points()).document; + let insts = leaves(&doc); + let [one, ten, nested, ten_again] = &insts[..] else { panic!("{insts:?}") }; + let at_one = instance_strokes(&doc, one); + let [(dash, lw), (no_dash, width)] = &at_one[..] else { panic!("{at_one:?}") }; + assert!(dash.len() >= 2 && no_dash.is_empty() && *width > 0.0, "{at_one:?}"); + // Instances leave the strokes in their art as they are, so the art carries the insert's scale. + let tenfold: Vec = dash.iter().map(|v| v * 10.0).collect(); + for inst in [ten, nested] { + let got = instance_strokes(&doc, inst); + let [(d, w_lw), (_, w)] = &got[..] else { panic!("{got:?}") }; + assert_eq!(d.len(), tenfold.len()); + assert!(d.iter().zip(&tenfold).all(|(a, b)| (a - b).abs() < 1e-9), "dashes {d:?}, want {tenfold:?}"); + assert!((w - width * 10.0).abs() < 1e-9, "polyline width {w}, want {}", width * 10.0); + assert!((w_lw - lw).abs() < 1e-12, "a lineweight is a physical width: {w_lw}, want {lw}"); + } + // The copies still land where their inserts put them. + let NodeKind::SymbolInstance { symbol, xf } = &ten.kind else { panic!() }; + let art = &doc.symbols.iter().find(|s| &s.name == symbol).unwrap().art; + let line = art.children().and_then(|c| c.first()).unwrap(); + let end = *xf * *path_points(line).last().unwrap(); + assert!(end.distance(Point::new(1000.0, height(&doc) - 100.0)) < 1e-6, "{end:?}"); + // Inserts at one scale share a symbol. + let symbol_of = |n: &Node| if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { symbol.clone() } else { panic!() }; + assert_eq!(symbol_of(ten), symbol_of(ten_again)); + assert_ne!(symbol_of(one), symbol_of(ten)); +} + +#[test] +fn dashes_on_a_hidden_layer_leave_a_block_one_symbol_for_every_scale() { + let tables = [ + (0, "TABLE"), + (2, "LTYPE"), + (0, "LTYPE"), + (2, "DASHED"), + (73, "2"), + (40, "15"), + (49, "10"), + (49, "-5"), + (0, "ENDTAB"), + (0, "TABLE"), + (2, "LAYER"), + (0, "LAYER"), + (2, "Off"), + (70, "0"), + (62, "-1"), + (0, "ENDTAB"), + ]; + // "Mark": a solid line, and a dashed line on a hidden layer, which is not drawn. + let blocks = [ + (0, "BLOCK"), + (8, "0"), + (2, "Mark"), + (70, "0"), + (10, "0"), + (20, "0"), + (0, "LINE"), + (8, "0"), + (10, "0"), + (20, "0"), + (11, "100"), + (21, "0"), + (0, "LINE"), + (8, "Off"), + (6, "DASHED"), + (10, "0"), + (20, "10"), + (11, "100"), + (21, "10"), + (0, "ENDBLK"), + ]; + let inserts = [(0, "INSERT"), (2, "Mark"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Mark"), (10, "0"), (20, "100"), (41, "10"), (42, "10")]; + let doc = open(&drawing(&[], &tables, &blocks, &inserts), &points()).document; + assert_eq!(leaves(&doc).len(), 2); + assert_eq!(doc.symbols.len(), 1, "{:?}", doc.symbols.iter().map(|s| &s.name).collect::>()); +} + +#[test] +fn a_dashed_pattern_hatch_leaves_a_block_one_symbol_for_every_scale() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "Mark": a pattern hatch in a dashed linetype, whose lines are drawn without it. + let mut blocks = vec![(0, "BLOCK"), (8, "0"), (2, "Mark"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([ + (0, "HATCH"), + (8, "0"), + (6, "DASHED"), + (10, "0"), + (20, "0"), + (30, "0"), + (2, "ANSI31"), + (70, "0"), + (71, "0"), + (91, "1"), + (92, "2"), + (72, "0"), + (73, "1"), + (93, "4"), + (10, "0"), + (20, "0"), + (10, "100"), + (20, "0"), + (10, "100"), + (20, "50"), + (10, "0"), + (20, "50"), + (97, "0"), + (75, "0"), + (76, "1"), + (78, "1"), + (53, "0"), + (43, "0"), + (44, "5"), + (45, "0"), + (46, "10"), + (79, "0"), + (98, "0"), + (0, "ENDBLK"), + ]); + let inserts = [(0, "INSERT"), (2, "Mark"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Mark"), (10, "0"), (20, "100"), (41, "10"), (42, "10")]; + let doc = open(&drawing(&[], &tables, &blocks, &inserts), &points()).document; + assert_eq!(leaves(&doc).len(), 2); + assert_eq!(doc.symbols.len(), 1, "{:?}", doc.symbols.iter().map(|s| &s.name).collect::>()); +} + +#[test] +fn a_block_first_seen_at_the_nesting_limit_still_scales_its_dashes_when_placed_shallow() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "Root" first places the anonymous block "*P" through a chain of anonymous blocks + // *C1 > *C2 > ... deep enough that the scale check reaches "*P" but not "*D" inside it, then + // places "*P" directly. "*P" has a solid line and places "*D", a dashed line. Anonymous + // blocks are drawn as groups, so the direct placement draws "*D". + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "*D"), (70, "1"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "*P"), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "10"), (11, "100"), (21, "10")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*D"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let chain = 6; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*C{i}").into_boxed_str()); + let next: &'static str = if i == chain { "*P" } else { Box::leak(format!("*C{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "Root"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*C1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*P"), (10, "0"), (20, "200"), (0, "ENDBLK")]); + let dashes = |scale: &'static str| { + let top = [(0, "INSERT"), (2, "Root"), (10, "0"), (20, "0"), (41, scale), (42, scale)]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let [root] = &leaves(&doc)[..] else { panic!("{:?}", leaves(&doc)) }; + instance_strokes(&doc, root).into_iter().map(|(d, _)| d).filter(|d| !d.is_empty()).collect::>() + }; + let (at_one, at_ten) = (dashes("1"), dashes("10")); + assert!(!at_one.is_empty(), "the direct placement of Inner draws Dash"); + assert_eq!(at_one.len(), at_ten.len()); + for (one, ten) in at_one.iter().zip(&at_ten) { + let want: Vec = one.iter().map(|v| v * 10.0).collect(); + assert_eq!(ten.len(), want.len()); + assert!(ten.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-9), "dashes {ten:?}, want {want:?}"); + } +} + +#[test] +fn repeated_inserts_of_a_block_past_the_nesting_limit_are_scale_checked_once() { + // "Deep" nests a solid line ten blocks down, past the nesting limit, and the drawing places + // it 1,000 times at one scale. + let mut blocks: Vec<(i32, &'static str)> = vec![]; + for i in 1..=10 { + let name: &'static str = Box::leak(format!("N{i}").into_boxed_str()); + let next: &'static str = Box::leak(format!("N{}", i + 1).into_boxed_str()); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "N11"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0"), (0, "ENDBLK")]); + let mut top: Vec<(i32, &'static str)> = vec![]; + for _ in 0..1000 { + top.extend([(0, "INSERT"), (2, "N1"), (10, "0"), (20, "0"), (41, "2"), (42, "2")]); + } + build::SCALED_LOOK_ITEMS.with(|n| n.set(0)); + let r = open(&drawing(&[], &[], &blocks, &top), &points()); + let looked = build::SCALED_LOOK_ITEMS.with(std::cell::Cell::get); + assert_eq!(leaves(&r.document).len(), 1000); + assert!(looked < 100, "{looked} items looked at"); +} + +#[test] +fn a_block_placed_too_deep_to_draw_its_dashes_shares_one_symbol_across_scales() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "Mark" has a solid line and places a dashed line four blocks down (D1 > D2 > D3 > Dash). + // The drawing places "Mark" directly at scale 2, where its dashes are drawn, then through + // W1 > W2 > W3 > W4 at scales 2 and 3, where the dashes are past the nesting limit, then + // directly again at scale 1. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "Dash"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0"), (0, "ENDBLK")]); + let mut chain = |names: &[&'static str], last: &'static str| { + for (i, name) in names.iter().enumerate() { + let next = names.get(i + 1).copied().unwrap_or(last); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, *name), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + }; + chain(&["D1", "D2", "D3"], "Dash"); + chain(&["W1", "W2", "W3", "W4"], "Mark"); + // Anonymous blocks are drawn into whatever places them, so each placement of "*A1" looks + // "Mark" up again at depth 4. + chain(&["*A1", "*A2", "*A3", "*A4"], "Mark"); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "Mark"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "10"), (11, "100"), (21, "10")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "D1"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let insert = |block: &'static str, scale: &'static str| [(0, "INSERT"), (2, block), (10, "0"), (20, "0"), (41, scale), (42, scale)]; + let top: Vec<(i32, &str)> = [insert("Mark", "2"), insert("W1", "2"), insert("W1", "3"), insert("Mark", "1")].concat(); + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + // The deep placements share one "W4" and one "Mark" whatever their scale; the direct ones + // have a "Mark" each, drawn at their scale. + assert_eq!(names.iter().filter(|n| n.starts_with("W4")).count(), 1, "{names:?}"); + assert_eq!(names.iter().filter(|n| n.starts_with("Mark")).count(), 3, "{names:?}"); + let insts = leaves(&doc); + let [at_two, _, _, at_one] = &insts[..] else { panic!("{insts:?}") }; + for (inst, scale) in [(at_two, 2.0), (at_one, 1.0)] { + let dashes: Vec> = instance_strokes(&doc, inst).into_iter().map(|(d, _)| d).filter(|d| !d.is_empty()).collect(); + assert_eq!(dashes.len(), 1, "the direct placement at scale {scale} draws its dashed line: {dashes:?}"); + } + // Placements that alternate between the two depths look at the blocks once per depth. + let top: Vec<(i32, &str)> = (0..500).flat_map(|_| [insert("Mark", "1"), insert("*A1", "2")]).flatten().collect(); + build::SCALED_LOOK_ITEMS.with(|n| n.set(0)); + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let looked = build::SCALED_LOOK_ITEMS.with(std::cell::Cell::get); + assert_eq!(leaves(&doc).len(), 1000); + assert!(looked < 100, "{looked} items looked at"); +} + +#[test] +fn a_block_cut_off_by_the_nesting_limit_keeps_the_art_a_shallower_placement_draws() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "S" has a solid line and places "D1", which has a solid line and places a dashed line. The + // anonymous chain *B2 > ... > *B8 places "S" one level deeper than *B3 > ... > *B8 does: too + // deep to draw "D1", where the shallower placement draws "D1" but not its dashed line. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "Dash"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "D1"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "20"), (11, "100"), (21, "20")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "Dash"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "S"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "10"), (11, "100"), (21, "10")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "D1"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let chain = 8; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*B{i}").into_boxed_str()); + let next: &'static str = if i == chain { "S" } else { Box::leak(format!("*B{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let insert = |block: &'static str| [(0, "INSERT"), (2, block), (10, "0"), (20, "0")]; + let top: Vec<(i32, &str)> = [insert("*B2"), insert("*B3")].concat(); + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + let insts = leaves(&doc); + let [deep, shallow] = &insts[..] else { panic!("{names:?}: {insts:?}") }; + assert_eq!(instance_strokes(&doc, deep).len(), 1, "{names:?}: the deeper placement draws only the line of S"); + let strokes = instance_strokes(&doc, shallow); + assert_eq!(strokes.len(), 2, "{names:?}: the shallower placement draws the lines of S and D1: {strokes:?}"); +} + +#[test] +fn a_dashed_block_cut_off_by_the_nesting_limit_keeps_its_art_for_a_shallow_placement_at_the_same_scale() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "P" has a dashed line and places "C", which has a solid line. The anonymous chain + // *B1 > ... > *B7 places "P" at scale 10 too deep to draw "C"; the drawing places "P" at + // scale 1, the chain, then "P" at scale 10. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "C"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "10"), (11, "100"), (21, "10"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "C"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let chain = 7; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*B{i}").into_boxed_str()); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + if i == chain { + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (41, "10"), (42, "10"), (0, "ENDBLK")]); + } else { + let next: &'static str = Box::leak(format!("*B{}", i + 1).into_boxed_str()); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + } + let top = [ + (0, "INSERT"), + (2, "P"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (2, "*B1"), + (10, "0"), + (20, "200"), + (0, "INSERT"), + (2, "P"), + (10, "0"), + (20, "400"), + (41, "10"), + (42, "10"), + ]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + let insts = leaves(&doc); + let [first, deep, last] = &insts[..] else { panic!("{names:?}: {insts:?}") }; + assert_eq!(instance_strokes(&doc, first).len(), 2, "{names:?}"); + assert_eq!(instance_strokes(&doc, deep).len(), 1, "{names:?}: the deep placement draws only the dashed line"); + assert_eq!(instance_strokes(&doc, last).len(), 2, "{names:?}: the shallow placement at scale 10 draws the line of C"); +} + +#[test] +fn a_dashed_block_placed_inside_its_own_child_keeps_its_art_for_a_direct_placement_at_the_same_scale() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "P" has a dashed line and places *A, which has a solid line and places "P". The drawing + // places "P" at scale 1, *A at scale 10, then "P" at scale 10. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*A"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "*A"), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "10"), (11, "100"), (21, "10")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let top = [ + (0, "INSERT"), + (2, "P"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (2, "*A"), + (10, "0"), + (20, "200"), + (41, "10"), + (42, "10"), + (0, "INSERT"), + (2, "P"), + (10, "0"), + (20, "400"), + (41, "10"), + (42, "10"), + ]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + let insts = leaves(&doc); + let last = insts.last().unwrap_or_else(|| panic!("{names:?}")); + assert_eq!(instance_strokes(&doc, last).len(), 2, "{names:?}: the direct placement at scale 10 draws the line of *A"); +} + +#[test] +fn a_block_whose_dashes_are_in_an_ancestor_shares_one_symbol_across_its_scales() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "P" has a solid line and places "D"; "D" has a dashed line and places "P". The drawing + // places "P", then "D" at scales 2 and 3, inside which "P" leaves out "D" and its dashes. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "10"), (11, "100"), (21, "10")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "D"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "D"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let top = [ + (0, "INSERT"), + (2, "P"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (2, "D"), + (10, "0"), + (20, "200"), + (41, "2"), + (42, "2"), + (0, "INSERT"), + (2, "D"), + (10, "0"), + (20, "400"), + (41, "3"), + (42, "3"), + ]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + // One "P" placed directly, and one for its solid art inside "D" at either scale. + assert_eq!(names.iter().filter(|n| n.starts_with('P')).count(), 2, "{names:?}"); +} + +#[test] +fn a_block_reaching_dashes_by_two_ancestors_in_turn_is_scale_checked_once_for_each() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "P" has a solid line and places *A1 and *A2, each with a dashed line and an insert of "P". + // Inside *A1, "P" reaches dashes only through *A2, and inside *A2 only through *A1. The drawing + // places *A1 and *A2 in turn. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "10"), (11, "100"), (21, "10")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*A1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*A2"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + for a in ["*A1", "*A2"] { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, a), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let insert = |block: &'static str| [(0, "INSERT"), (2, block), (10, "0"), (20, "0")]; + let top: Vec<(i32, &str)> = (0..500).flat_map(|_| [insert("*A1"), insert("*A2")]).flatten().collect(); + build::SCALED_LOOK_ITEMS.with(|n| n.set(0)); + let r = open(&drawing(&[], &tables, &blocks, &top), &points()); + let looked = build::SCALED_LOOK_ITEMS.with(std::cell::Cell::get); + assert!(looked < 100, "{looked} items looked at"); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +#[test] +fn blocks_placing_each_other_share_one_symbol_shallow_and_near_the_nesting_limit() { + // "A" and "B" each have a solid line and place each other. The drawing places "B", then "A", + // then the anonymous chain *C1 > ... > *C6, which places "A" six levels deep: "A" and "B" + // still draw there, and the copy of "A" inside "B" is left out in both placements. + let mut blocks: Vec<(i32, &'static str)> = vec![]; + for (name, other) in [("A", "B"), ("B", "A")] { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, other), (10, "0"), (20, "10"), (0, "ENDBLK")]); + } + let chain = 6; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*C{i}").into_boxed_str()); + let next: &'static str = if i == chain { "A" } else { Box::leak(format!("*C{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let insert = |block: &'static str| [(0, "INSERT"), (2, block), (10, "0"), (20, "0")]; + let top: Vec<(i32, &str)> = [insert("B"), insert("A"), insert("*C1")].concat(); + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + // One "A" inside "B", which leaves out "B", and one for both placements of "A" itself. + assert_eq!(names.iter().filter(|n| n.starts_with('A')).count(), 2, "{names:?}"); +} + +#[test] +fn a_block_placed_at_the_nesting_limit_first_leaves_its_partner_one_symbol() { + // "A" and "B" each have a solid line and place each other. The anonymous chain *D1 > ... > *D7 + // places "A" seven levels deep, where it draws only its line; *C1 > ... > *C6 places "B" six + // levels deep, where "B" draws "A", which leaves out "B". The drawing places the two chains, + // then "B", which draws the same art. + let mut blocks: Vec<(i32, &'static str)> = vec![]; + for (name, other) in [("A", "B"), ("B", "A")] { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, other), (10, "0"), (20, "10"), (0, "ENDBLK")]); + } + for (prefix, chain, target) in [("D", 7, "A"), ("C", 6, "B")] { + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*{prefix}{i}").into_boxed_str()); + let next: &'static str = if i == chain { target } else { Box::leak(format!("*{prefix}{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + } + let insert = |block: &'static str| [(0, "INSERT"), (2, block), (10, "0"), (20, "0")]; + let top: Vec<(i32, &str)> = [insert("*D1"), insert("*C1"), insert("B")].concat(); + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names.iter().filter(|n| n.starts_with('B')).count(), 1, "{names:?}"); +} + +#[test] +fn a_block_placing_its_anonymous_parent_shares_one_symbol_at_the_nesting_limit() { + // "P" has a solid line and places *A; *A places "P". Inside *A, "P" leaves out *A at any + // depth. The drawing places *A, then the chain *C1 > ... > *C6, which places *A six levels + // deep, so "P" is seven levels deep there. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*A"), (10, "0"), (20, "10"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "*A"), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let chain = 6; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*C{i}").into_boxed_str()); + let next: &'static str = if i == chain { "*A" } else { Box::leak(format!("*C{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let insert = |block: &'static str| [(0, "INSERT"), (2, block), (10, "0"), (20, "0")]; + let top: Vec<(i32, &str)> = [insert("*A"), insert("*C1")].concat(); + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(leaves(&doc).len(), 2, "{names:?}"); + assert_eq!(names, ["P"]); +} + +#[test] +fn a_block_reaching_other_ancestors_only_through_a_left_out_one_shares_one_symbol() { + // "O" places "W1" and "W2", each of which places "P"; "P" has a solid line and places "O". + // Inside either wrapper, "P" leaves out "O", and with it the other wrapper. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "O"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "INSERT"), (8, "0"), (2, "W1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "W2"), (10, "0"), (20, "100"), (0, "ENDBLK")]); + for w in ["W1", "W2"] { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, w), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "O"), (10, "0"), (20, "10"), (0, "ENDBLK")]); + let top = [(0, "INSERT"), (2, "O"), (10, "0"), (20, "0")]; + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names.iter().filter(|n| n.starts_with('P')).count(), 1, "{names:?}"); +} + +#[test] +fn a_block_placing_its_ancestors_only_on_a_hidden_layer_shares_one_symbol_under_each() { + let tables = [(0, "TABLE"), (2, "LAYER"), (0, "LAYER"), (2, "Off"), (70, "0"), (62, "-1"), (0, "ENDTAB")]; + // "P" has a solid line and places "W1" and "W2" on a hidden layer; "W1" and "W2" each place + // "P". The drawing places "W1" and "W2". + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "Off"), (2, "W1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "Off"), (2, "W2"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + for w in ["W1", "W2"] { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, w), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let top = [(0, "INSERT"), (2, "W1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "W2"), (10, "0"), (20, "200")]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names.iter().filter(|n| n.starts_with('P')).count(), 1, "{names:?}"); +} + +#[test] +fn an_anonymous_block_is_scale_checked_with_the_layer_it_is_drawn_on() { + let tables = [ + (0, "TABLE"), + (2, "LTYPE"), + (0, "LTYPE"), + (2, "DASHED"), + (73, "2"), + (40, "15"), + (49, "10"), + (49, "-5"), + (0, "ENDTAB"), + (0, "TABLE"), + (2, "LAYER"), + (0, "LAYER"), + (2, "Dashy"), + (70, "0"), + (62, "7"), + (6, "DASHED"), + (0, "ENDTAB"), + ]; + // *D has a line on layer 0 in the layer's linetype. *P places *D on layer 0 with its own + // color, lineweight and linetype, so *P alone does not look like it follows its insert. + // "N" places *P on "Dashy", whose linetype *D's line takes. "M" places *P too, and the chain + // *B1 > ... > *B6 places "M" where *D is past the nesting limit. The drawing places the + // chain, then "N" at scales 1 and 10. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "*D"), (70, "1"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "*P"), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (6, "CONTINUOUS"), (62, "1"), (370, "25"), (2, "*D"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "N"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "Dashy"), (2, "*P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "M"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let chain = 6; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*B{i}").into_boxed_str()); + let next: &'static str = if i == chain { "M" } else { Box::leak(format!("*B{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let top = [ + (0, "INSERT"), + (2, "*B1"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (2, "N"), + (10, "0"), + (20, "200"), + (0, "INSERT"), + (2, "N"), + (10, "0"), + (20, "400"), + (41, "10"), + (42, "10"), + ]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + let insts = leaves(&doc); + let [.., one, ten] = &insts[..] else { panic!("{names:?}: {insts:?}") }; + let dashes = |n: &Node| instance_strokes(&doc, n).first().map(|s| s.0.clone()).unwrap_or_default(); + let (a, b) = (dashes(one), dashes(ten)); + assert!(!a.is_empty(), "{names:?}: N draws *D's line dashed"); + assert_eq!(b, a.iter().map(|v| v * 10.0).collect::>(), "{names:?}: N at scale 10 scales its dashes"); +} + +#[test] +fn a_block_left_out_inside_itself_does_not_fix_the_scale_of_another_placement() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "D" places "P" and has a dashed line; "P" has a solid line and places "D". Placed from "D", + // the scan of "P" leaves "D" out; placed from "W", "P" draws "D" and its dashes. + let blocks = [ + (0, "BLOCK"), + (8, "0"), + (2, "D"), + (70, "0"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (8, "0"), + (2, "P"), + (10, "0"), + (20, "0"), + (0, "LINE"), + (8, "0"), + (6, "DASHED"), + (10, "0"), + (20, "0"), + (11, "100"), + (21, "0"), + (0, "ENDBLK"), + (0, "BLOCK"), + (8, "0"), + (2, "P"), + (70, "0"), + (10, "0"), + (20, "0"), + (0, "LINE"), + (8, "0"), + (10, "0"), + (20, "10"), + (11, "100"), + (21, "10"), + (0, "INSERT"), + (8, "0"), + (2, "D"), + (10, "0"), + (20, "0"), + (0, "ENDBLK"), + (0, "BLOCK"), + (8, "0"), + (2, "W"), + (70, "0"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (8, "0"), + (2, "P"), + (10, "0"), + (20, "0"), + (0, "ENDBLK"), + ]; + let dashes = |top: &[(i32, &'static str)]| { + let doc = open(&drawing(&[], &tables, &blocks, top), &points()).document; + let insts = leaves(&doc); + let last = insts.last().unwrap_or_else(|| panic!("nothing placed")); + instance_strokes(&doc, last).into_iter().map(|(d, _)| d).filter(|d| !d.is_empty()).collect::>() + }; + let w = |scale: &'static str| [(0, "INSERT"), (2, "W"), (10, "0"), (20, "0"), (41, scale), (42, scale)]; + let d_first = [(0, "INSERT"), (2, "D"), (10, "0"), (20, "500")]; + let at_one = dashes(&w("1")); + let at_ten = dashes(&[&d_first[..], &w("10")[..]].concat()); + assert!(!at_one.is_empty() && at_one.len() == at_ten.len(), "{at_one:?} and {at_ten:?}"); + for (one, ten) in at_one.iter().zip(&at_ten) { + let want: Vec = one.iter().map(|v| v * 10.0).collect(); + assert!(ten.len() == want.len() && ten.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-9), "dashes {ten:?}, want {want:?}"); + } +} + +#[test] +fn repeated_inserts_of_a_block_inside_itself_are_scale_checked_once() { + // "Loop" has 1,000 solid lines and places itself; the drawing places it 1,000 times. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "Loop"), (70, "0"), (10, "0"), (20, "0")]; + for _ in 0..1000 { + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + } + blocks.extend([(0, "INSERT"), (8, "0"), (2, "Loop"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let top: Vec<(i32, &str)> = (0..1000).flat_map(|_| [(0, "INSERT"), (2, "Loop"), (10, "0"), (20, "0")]).collect(); + build::SCALED_LOOK_ITEMS.with(|n| n.set(0)); + let r = open(&drawing(&[], &[], &blocks, &top), &points()); + let looked = build::SCALED_LOOK_ITEMS.with(std::cell::Cell::get); + assert!(looked < 10_000, "{looked} items looked at"); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +#[test] +fn a_block_inside_itself_placed_by_many_anonymous_blocks_is_scale_checked_once() { + // "Loop" has 1,000 solid lines and places itself; 1,000 anonymous blocks each place "Loop", + // and the drawing places each of them. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "Loop"), (70, "0"), (10, "0"), (20, "0")]; + for _ in 0..1000 { + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + } + blocks.extend([(0, "INSERT"), (8, "0"), (2, "Loop"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let mut top: Vec<(i32, &'static str)> = vec![]; + for i in 0..1000 { + let name: &'static str = Box::leak(format!("*H{i}").into_boxed_str()); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "Loop"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + top.extend([(0, "INSERT"), (2, name), (10, "0"), (20, "0")]); + } + build::SCALED_LOOK_ITEMS.with(|n| n.set(0)); + let r = open(&drawing(&[], &[], &blocks, &top), &points()); + let looked = build::SCALED_LOOK_ITEMS.with(std::cell::Cell::get); + assert!(looked < 10_000, "{looked} items looked at"); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +#[test] +fn reusing_the_scale_check_of_a_block_inside_itself_again_and_again_stays_within_the_work_budget() { + // C0 places C1 to C99, and each of them places C0; "P" places C0 20,000 times. Only the first + // reuse of C0's check passes on the 100 blocks it went into. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "C0"), (70, "0"), (10, "0"), (20, "0")]; + let names: Vec<&'static str> = (1..100).map(|i| &*Box::leak(format!("C{i}").into_boxed_str())).collect(); + for name in &names { + blocks.extend([(0, "INSERT"), (8, "0"), (2, *name), (10, "0"), (20, "0")]); + } + blocks.push((0, "ENDBLK")); + for name in &names { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, *name), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "C0"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]); + for _ in 0..20_000 { + blocks.extend([(0, "INSERT"), (8, "0"), (2, "C0"), (10, "0"), (20, "0")]); + } + blocks.push((0, "ENDBLK")); + let r = open(&drawing(&[], &[], &blocks, &[(0, "INSERT"), (2, "P"), (10, "0"), (20, "0")]), &points()); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +#[test] +fn reusing_two_scale_checks_in_turn_stays_within_the_work_budget() { + // A0 places A1 to A99 and B0 places B1 to B99, and each of those places its own 0 block. + // "P" places A0 and B0 in turn, 10,000 times each. + let mut blocks: Vec<(i32, &'static str)> = vec![]; + for family in ["A", "B"] { + let head: &'static str = Box::leak(format!("{family}0").into_boxed_str()); + let names: Vec<&'static str> = (1..100).map(|i| &*Box::leak(format!("{family}{i}").into_boxed_str())).collect(); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, head), (70, "0"), (10, "0"), (20, "0")]); + for name in &names { + blocks.extend([(0, "INSERT"), (8, "0"), (2, *name), (10, "0"), (20, "0")]); + } + blocks.push((0, "ENDBLK")); + for name in &names { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, *name), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, head), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + } + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]); + for _ in 0..10_000 { + blocks.extend([(0, "INSERT"), (8, "0"), (2, "A0"), (10, "0"), (20, "0"), (0, "INSERT"), (8, "0"), (2, "B0"), (10, "0"), (20, "0")]); + } + blocks.push((0, "ENDBLK")); + build::SCAN_TRAIL_MOST.with(|n| n.set(0)); + let r = open(&drawing(&[], &[], &blocks, &[(0, "INSERT"), (2, "P"), (10, "0"), (20, "0")]), &points()); + let most = build::SCAN_TRAIL_MOST.with(std::cell::Cell::get); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); + assert!(most < 1000, "the scan trail held {most} steps"); +} + +#[test] +fn a_block_inside_itself_at_the_nesting_limit_shares_its_symbol() { + // "Loop" has a solid line and places itself. The anonymous chain *Y1 > ... > *Y7 places it + // where its copy inside itself would also be past the nesting limit; the drawing places the + // chain and "Loop" directly. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "Loop"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "10"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "Loop"), (10, "20"), (20, "0"), (0, "ENDBLK")]); + let chain = 7; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*Y{i}").into_boxed_str()); + let next: &'static str = if i == chain { "Loop" } else { Box::leak(format!("*Y{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let top = [(0, "INSERT"), (2, "*Y1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Loop"), (10, "0"), (20, "100")]; + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(leaves(&doc).len(), 2, "{names:?}"); + assert_eq!(names, ["Loop"]); +} + +#[test] +fn reusing_the_scale_check_of_a_block_inside_itself_keeps_one_reference_to_it() { + // C0 places C1 to C99, and each of them places C0; "P" places C0 2,000 times. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "C0"), (70, "0"), (10, "0"), (20, "0")]; + let names: Vec<&'static str> = (1..100).map(|i| &*Box::leak(format!("C{i}").into_boxed_str())).collect(); + for name in &names { + blocks.extend([(0, "INSERT"), (8, "0"), (2, *name), (10, "0"), (20, "0")]); + } + blocks.push((0, "ENDBLK")); + for name in &names { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, *name), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "C0"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]); + for _ in 0..2000 { + blocks.extend([(0, "INSERT"), (8, "0"), (2, "C0"), (10, "0"), (20, "0")]); + } + blocks.push((0, "ENDBLK")); + build::SCAN_TRAIL_MOST.with(|n| n.set(0)); + open(&drawing(&[], &[], &blocks, &[(0, "INSERT"), (2, "P"), (10, "0"), (20, "0")]), &points()); + let most = build::SCAN_TRAIL_MOST.with(std::cell::Cell::get); + assert!(most < 1000, "the scan trail held {most} steps"); +} + +#[test] +fn placing_a_block_inside_itself_many_times_stays_within_the_work_budget() { + // C0 places C1 to C99, and each of them places C0; the drawing places C0 20,000 times. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "C0"), (70, "0"), (10, "0"), (20, "0")]; + let names: Vec<&'static str> = (1..100).map(|i| &*Box::leak(format!("C{i}").into_boxed_str())).collect(); + for name in &names { + blocks.extend([(0, "INSERT"), (8, "0"), (2, *name), (10, "0"), (20, "0")]); + } + blocks.push((0, "ENDBLK")); + for name in &names { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, *name), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "C0"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let top: Vec<(i32, &str)> = (0..20_000).flat_map(|_| [(0, "INSERT"), (2, "C0"), (10, "0"), (20, "0")]).collect(); + let r = open(&drawing(&[], &[], &blocks, &top), &points()); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); + let c0 = r.document.symbols.iter().filter(|s| s.name.starts_with("C0")).count(); + assert_eq!(c0, 1, "every placement of C0 shares one symbol"); +} + +#[test] +fn few_scale_checks_are_kept_for_a_block_inside_itself_under_many_ancestors() { + // "Loop" places K1 to K20, and each of them places "Loop"; the drawing places each K. Under + // each K, the check of "Loop" leaves out a different ancestor. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "Loop"), (70, "0"), (10, "0"), (20, "0")]; + let names: Vec<&'static str> = (1..=20).map(|i| &*Box::leak(format!("K{i}").into_boxed_str())).collect(); + for name in &names { + blocks.extend([(0, "INSERT"), (8, "0"), (2, *name), (10, "0"), (20, "0")]); + } + blocks.push((0, "ENDBLK")); + let mut top: Vec<(i32, &'static str)> = vec![]; + for name in &names { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, *name), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "Loop"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + top.extend([(0, "INSERT"), (2, *name), (10, "0"), (20, "0")]); + } + build::SCANS_HERE_MOST.with(|n| n.set(0)); + open(&drawing(&[], &[], &blocks, &top), &points()); + let most = build::SCANS_HERE_MOST.with(std::cell::Cell::get); + assert!((1..=16).contains(&most), "{most} checks kept for one block and depth"); +} + +#[test] +fn a_block_past_the_nesting_limit_stays_out_after_a_direct_placement() { + // The anonymous chain *Z1 > ... > *Z8 places "S" past the nesting limit. The drawing places + // the chain, then "S" directly, then the chain again. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "S"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "10"), (21, "0"), (0, "ENDBLK")]); + let chain = 8; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*Z{i}").into_boxed_str()); + let next: &'static str = if i == chain { "S" } else { Box::leak(format!("*Z{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let insert = |block: &'static str| [(0, "INSERT"), (2, block), (10, "0"), (20, "0")]; + let top: Vec<(i32, &str)> = [insert("*Z1"), insert("S"), insert("*Z1")].concat(); + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + assert_eq!(leaves(&doc).len(), 1, "only the direct placement draws S: {:?}", leaves(&doc)); +} + +#[test] +fn a_block_inside_itself_placed_again_after_many_others_is_scale_checked_once() { + // "Loop" places the anonymous blocks *W1 to *W20, and each of them places "Loop". The + // drawing places each *W, then *W20 1,000 more times. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "Loop"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + let names: Vec<&'static str> = (1..=20).map(|i| &*Box::leak(format!("*W{i}").into_boxed_str())).collect(); + for name in &names { + blocks.extend([(0, "INSERT"), (8, "0"), (2, *name), (10, "0"), (20, "0")]); + } + blocks.push((0, "ENDBLK")); + let mut top: Vec<(i32, &'static str)> = vec![]; + for name in &names { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, *name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "Loop"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + top.extend([(0, "INSERT"), (2, *name), (10, "0"), (20, "0")]); + } + let first = top.len(); + for _ in 0..1000 { + top.extend([(0, "INSERT"), (2, "*W20"), (10, "0"), (20, "0")]); + } + build::SCALED_LOOK_ITEMS.with(|n| n.set(0)); + open(&drawing(&[], &[], &blocks, &top[..first]), &points()); + let once = build::SCALED_LOOK_ITEMS.with(std::cell::Cell::get); + build::SCALED_LOOK_ITEMS.with(|n| n.set(0)); + open(&drawing(&[], &[], &blocks, &top), &points()); + let again = build::SCALED_LOOK_ITEMS.with(std::cell::Cell::get); + assert!(again < once + 1000, "{again} items looked at, {once} without the repeats"); +} + +#[test] +fn a_block_inside_itself_keeps_its_art_where_another_block_places_it() { + // "Loop" has a solid line and places itself; "W" places "Loop". The drawing places "Loop", + // then "W". + let blocks = [ + (0, "BLOCK"), + (8, "0"), + (2, "Loop"), + (70, "0"), + (10, "0"), + (20, "0"), + (0, "LINE"), + (8, "0"), + (10, "0"), + (20, "0"), + (11, "10"), + (21, "0"), + (0, "INSERT"), + (8, "0"), + (2, "Loop"), + (10, "20"), + (20, "0"), + (0, "ENDBLK"), + (0, "BLOCK"), + (8, "0"), + (2, "W"), + (70, "0"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (8, "0"), + (2, "Loop"), + (10, "0"), + (20, "0"), + (0, "ENDBLK"), + ]; + let top = [(0, "INSERT"), (2, "Loop"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "W"), (10, "0"), (20, "100")]; + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + let insts = leaves(&doc); + let [_, w] = &insts[..] else { panic!("{insts:?}") }; + assert!(!instance_strokes(&doc, w).is_empty(), "W draws the line of Loop"); + // Leaving out the copy of "Loop" inside itself cuts off nothing else, so both placements + // share one symbol. + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names.iter().filter(|n| n.starts_with("Loop")).count(), 1, "{names:?}"); +} + +#[test] +fn a_missing_block_past_the_nesting_limit_leaves_one_symbol_for_every_depth() { + // "Big" has a solid line and places "Ghost", which the drawing does not define. The + // anonymous chain *G1 > ... > *G7 places "Big" so that "Ghost" is past the nesting limit; the + // drawing places the chain, then "Big" directly. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "Big"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "10"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "Ghost"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let chain = 7; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*G{i}").into_boxed_str()); + let next: &'static str = if i == chain { "Big" } else { Box::leak(format!("*G{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let top = [(0, "INSERT"), (2, "*G1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Big"), (10, "0"), (20, "100")]; + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(leaves(&doc).len(), 2, "{names:?}"); + assert_eq!(names, ["Big"]); +} + +#[test] +fn repeated_inserts_of_a_large_block_past_the_nesting_limit_stay_within_the_work_budget() { + // "Big" has 2,000 solid lines; the anonymous chain *E1 > ... > *E8 places it past the nesting + // limit, and the drawing places the chain 1,000 times. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "Big"), (70, "0"), (10, "0"), (20, "0")]; + for _ in 0..2000 { + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + } + blocks.push((0, "ENDBLK")); + let chain = 8; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*E{i}").into_boxed_str()); + let next: &'static str = if i == chain { "Big" } else { Box::leak(format!("*E{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let top: Vec<(i32, &str)> = (0..1000).flat_map(|_| [(0, "INSERT"), (2, "*E1"), (10, "0"), (20, "0")]).collect(); + let r = open(&drawing(&[], &[], &blocks, &top), &points()); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +#[test] +fn the_scale_check_of_blocks_stops_at_the_work_budget() { + // "Outer" places "Leaf" 1,100 times, each in its own color, and "Leaf" has 1,000 solid + // lines that take their insert's color: 1,100,000 items to look at, past the 1,000,000 + // tests import with. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "Leaf"), (70, "0"), (10, "0"), (20, "0")]; + for _ in 0..1000 { + blocks.extend([(0, "LINE"), (8, "0"), (62, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + } + blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (8, "0"), (2, "Outer"), (70, "0"), (10, "0"), (20, "0")]); + for i in 0..1100 { + let color: &'static str = Box::leak((i + 1).to_string().into_boxed_str()); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "Leaf"), (420, color), (10, "0"), (20, "0")]); + } + blocks.push((0, "ENDBLK")); + let top = [(0, "INSERT"), (2, "Outer"), (10, "0"), (20, "0")]; + build::SCALED_LOOK_ITEMS.with(|n| n.set(0)); + let r = open(&drawing(&[], &[], &blocks, &top), &points()); + let looked = build::SCALED_LOOK_ITEMS.with(std::cell::Cell::get); + assert!(looked <= 1_000_000, "{looked} items looked at"); + assert!(r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +#[test] +fn text_in_a_dashed_block_inserted_at_a_tiny_scale_is_kept() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "Inner" draws a dashed line and a label; "Outer" places it at 1e-7, and the drawing places + // "Outer" at 1e-7, so "Inner"'s symbol is drawn at 1e-14. + let blocks = [ + (0, "BLOCK"), + (8, "0"), + (2, "Inner"), + (70, "0"), + (10, "0"), + (20, "0"), + (0, "LINE"), + (8, "0"), + (6, "DASHED"), + (10, "0"), + (20, "0"), + (11, "100"), + (21, "0"), + (0, "TEXT"), + (8, "0"), + (10, "0"), + (20, "10"), + (40, "5"), + (1, "Label"), + (0, "ENDBLK"), + (0, "BLOCK"), + (8, "0"), + (2, "Outer"), + (70, "0"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (8, "0"), + (2, "Inner"), + (10, "0"), + (20, "0"), + (41, "1e-7"), + (42, "1e-7"), + (0, "ENDBLK"), + ]; + let top = [(0, "INSERT"), (2, "Outer"), (10, "0"), (20, "0"), (41, "1e-7"), (42, "1e-7")]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let mut texts = vec![]; + for s in &doc.symbols { + s.art.walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind { + texts.push(t.plain_text()); + } + }); + } + assert_eq!(texts, ["Label"]); +} + +#[test] +fn a_dashed_block_at_a_tiny_scale_in_a_huge_fitted_drawing_keeps_a_finite_instance() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "G0" draws a line 1e12 long and "G1" to "G6" each place the one before at 1e12, so the + // drawing spans about 1e96 and fits at about 6e-94 points per unit. "D0" draws a dashed line, + // "D1" places it at 1e-4 and "D2" to "D5" each place the one before at 1e-12, so "D0" is drawn + // at about 6e-158 points per unit: the square of that is below the smallest normal number. + let mut blocks: Vec<(i32, &'static str)> = vec![]; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "G0"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1e12"), (21, "1e12"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "D0"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0"), (0, "ENDBLK")]); + let names = |p: &str, i: usize| -> &'static str { Box::leak(format!("{p}{i}").into_boxed_str()) }; + for (p, from, to) in [("G", 1, 6), ("D", 1, 5)] { + for i in from..=to { + let scale = match (p, i) { + ("G", _) => "1e12", + (_, 1) => "1e-4", + _ => "1e-12", + }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, names(p, i)), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, names(p, i - 1)), (10, "0"), (20, "0"), (41, scale), (42, scale), (0, "ENDBLK")]); + } + } + let top = [ + (0, "INSERT"), + (2, "G6"), + (10, "0"), + (20, "0"), + (41, "1e12"), + (42, "1e12"), + (0, "INSERT"), + (2, "D5"), + (10, "0"), + (20, "0"), + (41, "1e-12"), + (42, "1e-12"), + ]; + let o = ImportOptions { fit: true, center: false, ..ImportOptions::default() }; + let doc = open(&drawing(&[], &tables, &blocks, &top), &o).document; + let mut instances = vec![]; + let mut collect = |n: &Node| { + if let NodeKind::SymbolInstance { symbol, xf } = &n.kind { + instances.push((symbol.clone(), *xf)); + } + }; + doc.walk(&mut collect); + for s in &doc.symbols { + s.art.walk(&mut collect); + } + assert!(instances.iter().any(|(symbol, _)| symbol == "D0"), "{instances:?}"); + for (symbol, xf) in &instances { + assert!(xf.is_finite(), "{symbol}: {xf:?}"); + } +} + #[test] fn many_by_block_looks_import_in_linear_time() { let by_block: &[(i32, &str)] = &[(0, "LINE"), (8, "0"), (62, "0"), (10, "5"), (20, "5"), (11, "15"), (21, "5")]; diff --git a/crates/cad/src/import/tests_region.rs b/crates/cad/src/import/tests_region.rs index a44e02c84d..05ff83d211 100644 --- a/crates/cad/src/import/tests_region.rs +++ b/crates/cad/src/import/tests_region.rs @@ -327,20 +327,6 @@ fn binary_data_in_the_acdsdata_section_reads_alike() { short[7].1 = (bytes.len() + 1).to_string(); let r = import(&drawing("AC1032", &e, &short), &points()).unwrap(); assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); - // A chunk with an odd number of digits or a character that is not a hex digit fails to read. - let mut out = Vec::new(); - assert!(super::reader::hex_bytes("0aFf", &mut out)); - assert_eq!(out, [0x0A, 0xFF]); - for hex in ["0aF", "0aZZ", "0 aF"] { - assert!(!super::reader::hex_bytes(hex, &mut Vec::new()), "{hex}"); - } - // Data longer than the limit is left out, unless its declared size cuts it within the limit. - let sized = |len: usize, size: Option| super::reader::sized_region(vec![7; len], size, 8).map(|b| b.len()); - assert_eq!(sized(10, None), None); - assert_eq!(sized(10, Some(9)), None); - assert_eq!(sized(10, Some(11)), None); - assert_eq!(sized(10, Some(5)), Some(5)); - assert_eq!(sized(8, None), Some(8)); } /// A drawing the export writes (R2000, millimetres) with a region added to its entities. diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index e4eac1b20c..4e3f65f2d8 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -27,8 +27,6 @@ #![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; diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 45d2fcf234..68beac7f8d 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -15,9 +15,7 @@ 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}; +use craft_dxf::drawing::{Block, Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, STANDARD_STYLE, fixed}; /// Curves are flattened to within this distance (points) where DXF needs straight segments /// (hatch boundaries, R12 polylines). @@ -597,6 +595,7 @@ impl<'a> Scene<'a> { linetypes: self.linetypes, styles: self.styles, images: self.images, + blocks: self.blocks, entities: self.e.into_string(), extents: self.extents.unwrap_or(limits), limits, @@ -604,12 +603,7 @@ impl<'a> Scene<'a> { metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters), next: self.next, }; - DxfOutput { - bytes: crate::blocks_compat::write(drawing, &self.blocks).into_bytes(), - images: self.files, - warnings: self.warnings, - setting_notes: self.setting_notes, - } + DxfOutput { bytes: drawing.write().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 @@ -788,7 +782,7 @@ impl<'a> Scene<'a> { 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.e.insert(insert, self.owner, &self.layer, &name); self.blocks.push(Block { name, record, begin, end, entities }); } diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index ebd2671ae2..bbef9721e6 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -34,6 +34,8 @@ serde_json = { workspace = true } sha2 = { version = "0.10", default-features = false } thiserror = { workspace = true } chrono = { workspace = true } +# Field text in Devanagari, Gujarati and other Unicode digits (`units`). +craft-i18n = { workspace = true } [dev-dependencies] flate2 = { workspace = true } diff --git a/crates/effects/src/stroke/arrow.rs b/crates/doc/src/arrow.rs similarity index 92% rename from crates/effects/src/stroke/arrow.rs rename to crates/doc/src/arrow.rs index bd1511ab8c..7bdbeb2e36 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/doc/src/arrow.rs @@ -6,16 +6,53 @@ //! the inset; with [`ArrowAlign::Extend`] the path keeps its length and the tip sits the inset //! past the end point. Heads added after the first ten are drawn in local units ([`local`]), as are //! custom heads, whose stroke ends at their own stop or else halfway along their length -//! ([`vectorcraft_doc::CustomArrowhead::stop`]). +//! ([`crate::CustomArrowhead::stop`]). use std::borrow::Cow; use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, PI}; use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen, PathSeg, Point, Shape, Vec2}; -use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer}; +use vectorcraft_geom::bez::{segments, subpaths, tangent, unit}; -use super::{ARCLEN_ACCURACY, StrokePieces, cap_extent, push_seg, segments, subpaths, tangent, unit}; +use crate::{ArrowAlign, Arrowhead, LineCap, StrokeLayer}; + +const ARCLEN_ACCURACY: f64 = 1e-6; + +/// The geometry one stroke paints, in the coordinate space of its path. +#[derive(Clone, Debug)] +pub struct StrokePieces<'a> { + /// The centre line to stroke: the path with its ends trimmed under the arrowheads (borrowed + /// when nothing is trimmed). Empty when the heads cover the whole path. + pub line: Cow<'a, BezPath>, + /// The arrowheads, start first. Closed ends get none. + pub heads: Vec, +} + +/// The centre line and arrowheads of stroke `st` along `bp`. +pub fn stroke_pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a> { + if st.start_arrow.is_none() && st.end_arrow.is_none() { + return StrokePieces { line: Cow::Borrowed(bp), heads: vec![] }; + } + pieces(bp, st) +} + +/// How far a cap reaches past the end of a stroke of `width`. +pub fn cap_extent(cap: LineCap, width: f64) -> f64 { + match cap { + LineCap::Butt => 0.0, + LineCap::Round | LineCap::Square => width / 2.0, + } +} + +/// Append `seg` to `out` (which must already have a current point at its start). +pub fn push_seg(out: &mut BezPath, seg: &PathSeg) { + match seg { + PathSeg::Line(l) => out.line_to(l.p1), + PathSeg::Quad(q) => out.quad_to(q.p1, q.p2), + PathSeg::Cubic(c) => out.curve_to(c.p1, c.p2, c.p3), + } +} /// One arrowhead. #[derive(Clone, Debug, PartialEq)] @@ -30,8 +67,8 @@ pub struct Arrow { pub inset: f64, } -/// [`super::stroke_pieces`] for a stroke with at least one arrowhead. -pub(super) fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a> { +/// [`stroke_pieces`] for a stroke with at least one arrowhead. +fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a> { let subs = subpaths(bp); let els = bp.elements(); // Heads go on the start of the first subpath and the end of the last one, when open. @@ -182,10 +219,10 @@ fn bar(hw: f64) -> f64 { /// Where the notch of the (open) arrow sits, as a fraction of the length. const NOTCH: f64 = 0.7; -/// How far [`super::stroke_pieces`] trims the line under each end's head: the head's inset from +/// How far [`stroke_pieces`] trims the line under each end's head: the head's inset from /// the tip, along the path. Both are 0 without a head at that end, and in [`ArrowAlign::Extend`], /// where the stroke keeps its full length. -pub(super) fn trims(st: &StrokeLayer) -> (f64, f64) { +pub fn trims(st: &StrokeLayer) -> (f64, f64) { if st.arrow_align != ArrowAlign::Tip { return (0.0, 0.0); } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5466d2122b..78a73c5da2 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -7,6 +7,7 @@ #![doc(test(attr(forbid(unsafe_code))))] pub mod appearance; +pub mod arrow; pub mod assets; pub mod blend; pub mod cancel; @@ -179,7 +180,7 @@ use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit}; pub use stored_art::{StoredPlace, StoredRoot}; -pub use units::{ColorMode, Unit, arithmetic_signs, decimal_point, finite_in_every_unit, parse_number}; +pub use units::{ColorMode, Unit, arithmetic_signs, ascii_digits, ascii_digits_one_number, decimal_point, finite_in_every_unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Document { diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index 9189302bc0..d08354f8d4 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -25,6 +25,16 @@ fn ends(segs: &[PathSeg]) -> Option<[(Point, Vec2); 2]> { Some([(first.start(), -tangent(first, 0.0)), (last.end(), tangent(last, 1.0))]) } +/// `out` grown to take in the corners of the projecting caps, reaching `side` past each end of the +/// open subpath `segs`. +fn square_corners(mut out: Rect, segs: &[PathSeg], side: f64) -> Rect { + for (at, dir) in ends(segs).into_iter().flatten() { + let n = Vec2::new(-dir.y, dir.x) * side; + out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n); + } + out +} + /// The joints between consecutive segments (and, `closed`, where the subpath closes): the point /// and the unit tangents in and out. fn joints(segs: &[PathSeg], closed: bool) -> impl Iterator + '_ { @@ -249,7 +259,7 @@ impl StrokeLayer { /// caps, and every subpath when the joins are bevels or miters, by [`Self::body_along`] with its /// caps, every other subpath by the box of its segments grown by its reach, with `tips` and, /// when `measure_tips`, the miter spikes the limit keeps, the corners of projecting caps and the - /// reach of the arrowheads round their end points. + /// outlines of the arrowheads. fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option, measure_tips: bool) -> Rect { let els = bp.elements(); let subs = subpaths(bp); @@ -263,6 +273,9 @@ impl StrokeLayer { // box needed. let even_only = !subs.iter().any(|s| self.stops_at_corners(s.1)); let mut even = even_only.then_some(bounds); + // Tip-aligned arrowheads shorten the line, and its caps sit on the shortened ends. + let pieces = crate::arrow::stroke_pieces(bp, self); + let shortened = matches!(pieces.line, std::borrow::Cow::Owned(_)); for (r, closed) in subs { let side = self.side_reach(closed); let butt = self.cap == LineCap::Butt && !closed; @@ -309,23 +322,50 @@ impl StrokeLayer { } else if !even_only { even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b))); } - if square { - for (at, dir) in ends(&segs).into_iter().flatten() { - let n = Vec2::new(-dir.y, dir.x) * side; - out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n); + if square && !shortened { + out = square_corners(out, &segs, side); + } + } + if shortened && self.cap == LineCap::Square { + let line = pieces.line.elements(); + // The renderer aligns the stroke along every subpath by whether the path ends closed. + let side = self.side_reach(matches!(bp.elements().last(), Some(vectorcraft_geom::PathEl::ClosePath))); + for (r, closed) in subpaths(&pieces.line) { + if side <= 0.0 { + continue; + } + if closed { + // A closed subpath with no length, a lone anchor included, paints the dot at the + // whole path's reach when the stroke draws dots. + if !self.draws_dots() || vectorcraft_geom::kurbo::segments(line[r.clone()].iter().copied()).any(|s| has_length(&s)) { + continue; + } + let lone = line[r.start].end_point().map(|p| Rect::from_points(p, p)); + let dot = segments(&line[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)).or(lone); + out = dot.map_or(out, |d| out.union(d.inflate(side, side))); + continue; + } + let segs = drawn(&line[r.clone()]); + if segs.is_empty() { + // A trim that leaves no length still paints the caps' dot. + let dot = segments(&line[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)); + out = dot.map_or(out, |d| out.union(d.inflate(side, side))); + } else { + out = square_corners(out, &segs, side); } } } - for (at, _, end) in head_ends(self, bp) { - let r = self.head_reach(end); - out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r))); + for head in pieces.heads { + if !head.outline.elements().is_empty() { + out = out.union(head.outline.bounding_box()); + } } even.map_or(out, |e| out.union(e.inflate(side_max, side_max))) } /// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown /// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of - /// projecting caps and the reach of the arrowheads round their end points. An open subpath + /// projecting caps and the outlines of the arrowheads. An open subpath /// with butt caps does not reach past its ends, and a bevel does not reach round its corner /// ([`Self::body_along`]). pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect { @@ -681,13 +721,86 @@ mod tests { }) }; let (small, big) = (at(100.0).bounds_on(&l, b), at(300.0).bounds_on(&l, b)); - assert!(big.x1 > small.x1 + 15.0 && big.y1 > small.y1 + 7.0, "{small:?} → {big:?}"); - // A 300% head on a 2 pt stroke is 24 pt long and wide: its tip, past the end, is inside. - assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == 0.0, "{big:?}"); + // The triangle straddles its path end in Extend mode and ends exactly on it in Tip mode. + assert_eq!(small, Rect::new(0.0, -4.0, 104.0, 4.0)); + assert_eq!(big, Rect::new(0.0, -12.0, 112.0, 12.0)); + let mut tip = at(300.0); + tip.arrow_align = ArrowAlign::Tip; + assert_eq!(tip.bounds_on(&l, b), Rect::new(0.0, -12.0, 100.0, 12.0)); // The start has no head. assert_eq!(at(300.0).head_reach(false), 0.0); } + /// An open arrow at the start of a line, its tip on the start point: the box ends where the + /// head's barbs end, with no room left in front of the tip (#10225). + #[test] + fn an_open_tip_aligned_arrowhead_adds_no_room_in_front_of_its_tip() { + let l = line(); + let b = l.bounding_box(); + let st = stroke(1.0, |s| { + s.start_arrow = Some(Arrowhead::ArrowOpen); + s.arrow_align = ArrowAlign::Tip; + s.arrow_scale = (300.0, 100.0); + }); + let bounds = st.bounds_on(&l, b); + // The barbs reach back along the line from the tip, and at most the line's weight past it. + assert!(bounds.x0 <= 0.0 && bounds.x0 >= -st.width, "{bounds:?}"); + assert!(bounds.y0 < -st.width && bounds.y1 > st.width, "the barbs spread wider than the line: {bounds:?}"); + assert_eq!(bounds.x1, b.x1, "the end has no head and a butt cap"); + } + + /// A Tip-aligned arrowhead shortens the line, and the projecting cap sits on the shortened end: + /// the box takes in that cap's corners, and not the corners a cap on the path's own end would have. + #[test] + fn projecting_caps_under_tip_aligned_arrowheads_sit_on_the_shortened_ends() { + let l = line(); + let b = l.bounding_box(); + let st = stroke(10.0, |s| { + s.cap = LineCap::Square; + s.join = LineJoin::Bevel; + s.end_arrow = Some(Arrowhead::Triangle); + s.arrow_align = ArrowAlign::Tip; + }); + let pieces = crate::arrow::stroke_pieces(&l, &st); + let segs = drawn(pieces.line.elements()); + let [_, (at, dir)] = ends(&segs).unwrap_or_else(|| panic!("the arrowhead covers the whole line")); + assert!(at.x < 95.0 && (dir.x - 1.0).abs() < 1e-9, "{at:?} {dir:?}"); + let bounds = st.bounds_on(&l, b); + let n = Vec2::new(-dir.y, dir.x) * 5.0; + for corner in [at + dir * 5.0 + n, at + dir * 5.0 - n] { + assert!(bounds.inflate(1e-9, 1e-9).contains(corner), "{corner:?} outside {bounds:?}"); + } + // Nothing is painted right of the head's tip at x = 100; a cap on the path's own end would + // reach to x = 105. + let head = pieces.heads.iter().map(|h| h.outline.bounding_box()).reduce(|a, h| a.union(h)); + assert_eq!(head.map(|h| h.x1), Some(100.0)); + assert_eq!(bounds.x1, 100.0, "{bounds:?}"); + // The start has no head, and its cap projects 5 in front of it. + assert_eq!(bounds.x0, -5.0, "{bounds:?}"); + } + + /// A closed lone anchor in a path that ends open is painted as a dot at the whole path's reach, + /// so the box takes it in when a Tip-aligned arrowhead moves the start cap off that anchor. + #[test] + fn closed_lone_anchors_keep_their_dot_under_tip_aligned_arrowheads() { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((100.0, 0.0)); + p.move_to((0.0, 0.0)); + p.close_path(); + p.move_to((110.0, 0.0)); + p.line_to((120.0, 0.0)); + let st = stroke(10.0, |s| { + s.cap = LineCap::Square; + s.join = LineJoin::Bevel; + s.align = StrokeAlign::Inside; + s.start_arrow = Some(Arrowhead::Triangle); + s.arrow_align = ArrowAlign::Tip; + }); + let bounds = st.bounds_on(&p, p.bounding_box()); + assert_eq!(bounds.x0, -5.0, "the lone anchor's square dot reaches 5 left of it: {bounds:?}"); + } + #[test] fn rectangles_keep_exact_bounds_and_sharp_corners_spike_up_to_the_limit() { let sq = square(); diff --git a/crates/doc/src/tests/units.rs b/crates/doc/src/tests/units.rs index 0258179979..b024bf9008 100644 --- a/crates/doc/src/tests/units.rs +++ b/crates/doc/src/tests/units.rs @@ -303,3 +303,43 @@ fn format_area_formats_and_trims_cleanly() { assert_eq!(Unit::Points.format_area(f64::NAN), "0 pt²"); assert_eq!(Unit::Points.format_area(f64::INFINITY), "0 pt²"); } + +/// Typed in Devanagari or Gujarati digits, a field value reads as its ASCII spelling does: +/// plain numbers, units, picas, arithmetic, percentages and a decimal comma. +#[test] +fn hindi_and_gujarati_digits_read_as_ascii_digits_do() { + let ascii = ["12", "12.5 mm", "-3in", "2p6", "45*2", "10x2 mm", "100pt+25%", "1080/2 px", "13q"]; + let hindi = ["१२", "१२.५ mm", "-३in", "२p६", "४५*२", "१०x२ mm", "१००pt+२५%", "१०८०/२ px", "१३q"]; + let gujarati = ["૧૨", "૧૨.૫ mm", "-૩in", "૨p૬", "૪૫*૨", "૧૦x૨ mm", "૧૦૦pt+૨૫%", "૧૦૮૦/૨ px", "૧૩q"]; + for ((a, h), g) in ascii.iter().zip(hindi).zip(gujarati) { + let want = Unit::Millimeters.parse(a); + assert!(want.is_some(), "`{a}` should read"); + assert_eq!(Unit::Millimeters.parse(h), want, "`{h}` vs `{a}`"); + assert_eq!(Unit::Millimeters.parse(g), want, "`{g}` vs `{a}`"); + } + assert_eq!(crate::parse_number("४५*२"), crate::parse_number("45*2")); + assert_eq!(crate::parse_number("૪૫x૨"), crate::parse_number("45x2")); + assert_eq!(Unit::Millimeters.parse_with_decimal_comma("०,५ mm"), Unit::Millimeters.parse("0.5 mm")); + assert_eq!(Unit::Millimeters.parse_with_decimal_comma("૦,૫"), Unit::Millimeters.parse("0.5")); +} + +/// A grouped thousand is refused in any digits, as `1,000` is, rather than read as 1. +#[test] +fn a_native_digit_thousand_is_refused_like_an_ascii_one() { + assert_eq!(Unit::Millimeters.parse_with_decimal_comma("1,000 mm"), None); + assert_eq!(Unit::Millimeters.parse_with_decimal_comma("१,००० mm"), None); + assert_eq!(Unit::Millimeters.parse_with_decimal_comma("૧,૦૦૦"), None); + assert_eq!(crate::decimal_point("१,०००"), crate::decimal_point("1,000")); +} + +/// One number mixing digit sets is refused, as craft-i18n's `parse_number` refuses it; separate +/// numbers of a sum may each use their own. +#[test] +fn a_number_mixing_digit_sets_reads_as_nothing() { + for text in ["1२", "૧२", "१.5", "૧२.૫ mm", "1,२"] { + assert_eq!(Unit::Points.parse(text), None, "`{text}`"); + assert_eq!(Unit::Points.parse_with_decimal_comma(text), None, "`{text}`"); + assert_eq!(crate::parse_number(text), None, "`{text}`"); + } + assert_eq!(Unit::Points.parse("१२+3"), Unit::Points.parse("12+3")); +} diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index d62c367f25..1ef44c0413 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -1,3 +1,5 @@ +use std::borrow::Cow; + use super::{Deserialize, Serialize}; /// Measurement units (display only; the model is always in points). @@ -203,20 +205,24 @@ impl Unit { /// /// Text with more than 128 `+ - * /` signs ([`arithmetic_signs`], a multiplication sign counted /// as `*`) reads as nothing. + /// + /// Digits may be any Unicode 16 decimal digits ([`ascii_digits`]): `१२ mm` is `12 mm`, `૪૫*૨` is `45*2`. pub fn parse(self, s: &str) -> Option { if arithmetic_signs(s) > MAX_MEASURE_OPERATORS { return None; } - parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite()) + let s = ascii_digits(s)?; + parse_measure(×_as_asterisks(&s), self).filter(|v| v.is_finite()) } /// Parse a measurement with decimal points or commas and no input locale. Refuse a /// number that looks like a grouped integer, even when it is part of an expression. pub fn parse_with_decimal_comma(self, text: &str) -> Option { - if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) { + let text = ascii_digits(text)?; + if text.contains(',') && times_as_asterisks(&text).split(['+', '-', '*', '/']).any(thousands_operand) { return None; } - self.parse(&decimal_point(text)) + self.parse(&decimal_point(&text)) } /// The value naming this unit in the Units preferences (`points`, `millimeters`, /// `feetInches`). @@ -414,9 +420,26 @@ fn percent(s: &str) -> Option { /// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed /// after the value the field shows) is 100 mm (#5684). A number written with both separators has /// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a -/// number that reads as thousands ([`thousands`]). -pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { - if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } +/// number that reads as thousands ([`thousands`]). Digits in other scripts come back as ASCII +/// ([`ascii_digits`]), so `१,०००` is refused as `1,000` is; text mixing digit sets in one number +/// comes back as it is, for the parser to refuse. +pub fn decimal_point(text: &str) -> Cow<'_, str> { + let Some(text) = ascii_digits(text) else { return text.into() }; + if text.contains(',') && !thousands(&text) { text.replace(',', ".").into() } else { text } +} + +/// `text` with every Unicode 16 decimal digit (Devanagari `०-९`, Gujarati `૦-૯`, Bengali, +/// Arabic-Indic, full-width, …) written as its ASCII digit, so `१२.५ mm` reads as `12.5 mm`. A +/// number here is a run of digits, `.` and `,`, and must use one digit set: `1२` and `૧२` are +/// `None`. Operators, unit suffixes and other characters are left as they are. +pub fn ascii_digits(text: &str) -> Option> { + craft_i18n::ascii_digits(text, |c| matches!(c, '.' | ',')).ok() +} + +/// [`ascii_digits`] for text that holds a single number, exponent and unit included: every digit +/// must come from one set, so `१e२` is `1e2` and `१e2` is `None`. +pub fn ascii_digits_one_number(text: &str) -> Option> { + craft_i18n::ascii_digits(text, |_| true).ok() } /// Does the operand contain a thousands comma? Check both parts of a compact pica value and @@ -455,9 +478,10 @@ pub fn finite_in_every_unit(pt: f64) -> bool { } /// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as -/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`); text other than digits, `.` and operators reads as -/// nothing. +/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`, `४५*२`); text other than digits, `.` and operators +/// reads as nothing. pub fn parse_number(s: &str) -> Option { + let s = ascii_digits(s)?; if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/xX×".contains(c)) { return None; } diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 00c0043a78..a6dd12e4cc 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -241,28 +241,28 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; 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, for a gradient, pattern or graphics, or when a later geometry effect reshapes paths but leaves images unchanged; a solid below 100% opacity or in a blending mode other than Normal draws its own image in that opacity and blending mode (Revolve on a group draws the shaded faces instead); 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.", + "{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, for a gradient, pattern or graphics, or when a later geometry effect reshapes paths but leaves images unchanged; a solid below 100% opacity or in a blending mode other than Normal draws its own image in that opacity and blending mode (Revolve on a group draws the shaded faces instead); 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), colorModel: document|grayscale|bitmap (document: RGB pixels in every document, which a CMYK document's PDF export converts as it converts raster effect images; grayscale: the Rec. 709 luma of each pixel; bitmap: two pixel values, black and white with background white, or black and transparent with background transparent, where a dark pixel at least half covered is black; applied after the background; grayscale and bitmap images are stored as 8-bit gray PNGs, with alpha unless every pixel is opaque); 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; 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).", + "{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, background and colorModel, 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; 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).", + "{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, background and colorModel, 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; 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.", + "{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, background and colorModel, 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( diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 1b6bd49c85..ab837e9066 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -102,9 +102,9 @@ pub use revolve::{ 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, 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, + MeshGraphics, RENDER, RENDER_BACKGROUNDS, RENDER_COLOR_MODELS, 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, diff --git a/crates/effects/src/pixel.rs b/crates/effects/src/pixel.rs index f6c33079c0..116b1ea20b 100644 --- a/crates/effects/src/pixel.rs +++ b/crates/effects/src/pixel.rs @@ -717,7 +717,6 @@ impl PixelFx { PixelFx::Charcoal { thickness, detail, .. } => Some(sketch_ink::charcoal_reach(thickness, detail)), PixelFx::Photocopy { detail, .. } => Some(sketch_ink::copy_reach(detail)), PixelFx::Stamp { smoothness, .. } => Some(sketch_ink::stamp_reach(smoothness)), - PixelFx::GlowingEdges { width, smoothness, .. } => Some(width.max(smoothness * 3.0)), // The cells around the pixel's, and the cells around theirs. // (Without a usable grid there are no dots: see `pixelate::color_halftone`.) PixelFx::ColorHalftone { max_radius, .. } => { @@ -740,8 +739,9 @@ impl PixelFx { PixelFx::WaterPaper { fiber_length, .. } => { Some(sketch::water_paper_shift(fiber_length) + 3.0 * (0.06 * fiber_length.clamp(3.0, 50.0)).max(0.35)) } - // Cutout's palette and Torn Edges' peak-normalised edges come from the whole object. - PixelFx::Cutout { .. } | PixelFx::TornEdges { .. } => None, + // Cutout's palette and the peak-normalized edges of Torn Edges and Glowing Edges come + // from the whole object. + PixelFx::Cutout { .. } | PixelFx::TornEdges { .. } | PixelFx::GlowingEdges { .. } => None, // The softened tones around the pixel. PixelFx::NeonGlow { size, .. } => Some(3.0 * artistic::glow_spread(size)), PixelFx::PlasticWrap { smoothness, .. } => Some(artistic::plastic_reach(smoothness)), diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 8865de9cee..ae2acd792b 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -42,8 +42,8 @@ pub(crate) mod shadow; pub(crate) mod wireframe; pub use wireframe::{ - RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, RenderSettings, render_settings, renders_image, renders_wireframe, - three_d_wireframe_in, + RENDER, RENDER_BACKGROUNDS, RENDER_COLOR_MODELS, RENDER_MODES, RENDER_QUALITIES, RenderSettings, render_settings, renders_image, + renders_wireframe, three_d_wireframe_in, }; pub mod rendered; diff --git a/crates/effects/src/solids/rendered.rs b/crates/effects/src/solids/rendered.rs index 890d5176da..ccab12ffff 100644 --- a/crates/effects/src/solids/rendered.rs +++ b/crates/effects/src/solids/rendered.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use craft_raster3d::{Limits, Scene, Vertex, srgb_to_linear, try_encode, try_render_cpu, try_shadow_maps}; use vectorcraft_doc::color::{Color, Paint}; -use vectorcraft_doc::{Appearance, ImageBlob, ImageObject, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Appearance, ImageBlob, ImageObject, Node, NodeId, NodeKind, RasterColorModel}; use vectorcraft_geom::{Affine, Rect}; use vectorcraft_three_d::{Light, MeshProjection}; @@ -160,7 +160,8 @@ pub(crate) fn with_receiver( } /// A rendered image: `cols` × `rows` straight-alpha sRGB RGBA8 pixels covering `rect` on the page, -/// made with `samples` × `samples` samples a pixel. +/// made with `samples` × `samples` samples a pixel. `gray` when the color model is Grayscale or +/// Bitmap: every pixel's red, green and blue are equal, and the image is stored as a gray PNG. #[derive(Clone, Debug, PartialEq)] pub struct Rendered { pub rect: Rect, @@ -168,6 +169,7 @@ pub struct Rendered { pub rows: u32, pub samples: u32, pub pixels: Vec, + pub gray: bool, } /// The margin, as a share of the depth range, the solids' nearest and farthest points keep from the @@ -222,12 +224,33 @@ fn render_layer( .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) + color_model_pixel(p, settings.color_model, settings.white) }) .collect(); - Ok(Rendered { rect, cols, rows, samples: k, pixels }) + Ok(Rendered { rect, cols, rows, samples: k, pixels, gray: settings.color_model != RasterColorModel::Document }) +} + +/// Premultiplied sRGB float pixel `p` as a straight RGBA8 pixel in color model `model`, `white` +/// when `p` is already on the white background. Grayscale and Bitmap map the straight color before +/// the coverage is rounded, so an edge pixel takes the gray or the black or white of the surface it +/// covers. Bitmap on a transparent background is black and transparent: a dark pixel at least half +/// covered is opaque black, and every other pixel is transparent. +fn color_model_pixel(p: [f32; 4], model: RasterColorModel, white: bool) -> [u8; 4] { + 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 }; + if model == RasterColorModel::Document { + return [straight(p[0]), straight(p[1]), straight(p[2]), a].map(|c| (c * 255.0).round() as u8); + } + let alpha = (a * 255.0).round() as u8; + if alpha == 0 { + return [0; 4]; + } + let luma = 0.2126 * straight(p[0]) + 0.7152 * straight(p[1]) + 0.0722 * straight(p[2]); + if model == RasterColorModel::Bitmap && !white { + return if alpha >= 128 && luma < 0.5 { [0, 0, 0, 255] } else { [0; 4] }; + } + let gray = if model == RasterColorModel::Bitmap { if luma < 0.5 { 0 } else { 255 } } else { (luma * 255.0).round() as u8 }; + [gray, gray, gray, alpha] } #[cfg(test)] @@ -630,11 +653,23 @@ pub fn image_node(id: NodeId, image: &Rendered) -> Option> { 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. +/// `image` as an image object holding its pixels as a PNG: RGBA, or for a [`Rendered::gray`] image +/// gray, with alpha unless every pixel is opaque. `None` when it can't be encoded. fn image_object(image: &Rendered) -> Option { - 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 mut out = Cursor::new(&mut png); + if image.gray { + let pixels = image.pixels.as_chunks::<4>().0; + if pixels.iter().all(|p| p[3] == 255) { + let levels = pixels.iter().map(|p| p[0]).collect(); + image::GrayImage::from_raw(image.cols, image.rows, levels)?.write_to(&mut out, image::ImageFormat::Png).ok()?; + } else { + let gray_alpha = pixels.iter().flat_map(|p| [p[0], p[3]]).collect(); + image::GrayAlphaImage::from_raw(image.cols, image.rows, gray_alpha)?.write_to(&mut out, image::ImageFormat::Png).ok()?; + } + } else { + image::RgbaImage::from_raw(image.cols, image.rows, image.pixels.clone())?.write_to(&mut out, image::ImageFormat::Png).ok()?; + } let blob = ImageBlob::png(png); let cell = image.rect.width() / f64::from(image.cols); Some(ImageObject { @@ -927,6 +962,7 @@ fn image_key(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings .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); + settings.color_model.id().hash(&mut h); for m in meshes { m.mesh.triangles.hash(&mut h); } diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs index a15b80fa12..2cc6f7ec9e 100644 --- a/crates/effects/src/solids/rendered/tests.rs +++ b/crates/effects/src/solids/rendered/tests.rs @@ -62,7 +62,8 @@ fn scene_of(n: &Node) -> (Vec, Lighting) { (crate::three_d_meshes(n).unwrap(), lighting(&fx.id, &p)) } -const MEDIUM: RenderSettings = RenderSettings { quality: 1, resolution: None, white: false }; +const MEDIUM: RenderSettings = + RenderSettings { quality: 1, resolution: None, white: false, color_model: vectorcraft_doc::RasterColorModel::Document }; const FOUR: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::INFLATE, super::super::ROTATE]; @@ -448,6 +449,127 @@ fn the_background_is_white_or_clear() { assert!(corners(&white).contains(&[255; 4]), "{:?}", corners(&white)); } +#[test] +fn color_model_maps_straight_color_before_rounding_coverage() { + let dark = 127.0 / 255.0; + let edge = [dark * 0.25, dark * 0.25, dark * 0.25, 0.25]; + assert_eq!(color_model_pixel(edge, RasterColorModel::Grayscale, false), [127, 127, 127, 64]); + // Over white, every pixel is opaque, so Bitmap needs no rounding of the coverage. + for (model, white) in [(RasterColorModel::Grayscale, false), (RasterColorModel::Grayscale, true), (RasterColorModel::Bitmap, true)] { + assert_eq!(color_model_pixel([0.0; 4], model, white), [0; 4]); + for rgb in [[127, 127, 127], [128, 128, 128], [255, 0, 0], [0, 255, 0], [0, 0, 255]] { + let mut expected = [rgb[0], rgb[1], rgb[2], 255]; + vectorcraft_doc::RasterEffectsSettings { color_model: model, ..Default::default() }.finish_pixels(&mut expected); + let p = [f32::from(rgb[0]) / 255.0, f32::from(rgb[1]) / 255.0, f32::from(rgb[2]) / 255.0, 1.0]; + assert_eq!(color_model_pixel(p, model, white), expected, "{model:?}, white {white}: {rgb:?}"); + } + } +} + +/// Bitmap on a transparent background makes a black and transparent image: a dark pixel at least +/// half covered is opaque black, and a light pixel or one less than half covered is transparent. +#[test] +fn bitmap_on_a_transparent_background_is_black_and_transparent() { + let bitmap = |p| color_model_pixel(p, RasterColorModel::Bitmap, false); + assert_eq!(bitmap([1.0, 1.0, 1.0, 1.0]), [0; 4], "white is transparent"); + assert_eq!(bitmap([0.0, 0.0, 0.0, 1.0]), [0, 0, 0, 255]); + assert_eq!(bitmap([1.0, 0.0, 0.0, 1.0]), [0, 0, 0, 255], "red is dark"); + assert_eq!(bitmap([0.0, 1.0, 0.0, 1.0]), [0; 4], "green is light"); + assert_eq!(bitmap([0.0, 0.0, 0.0, 0.5]), [0, 0, 0, 255], "a half-covered black pixel is opaque black"); + let dark = 127.0 / 255.0; + assert_eq!(bitmap([dark * 0.25, dark * 0.25, dark * 0.25, 0.25]), [0; 4], "a dark pixel a quarter covered is transparent"); + assert_eq!(bitmap([0.5, 0.5, 0.5, 0.5]), [0; 4], "a half-covered white pixel is transparent"); + assert_eq!(bitmap([0.0; 4]), [0; 4]); + // A pale solid's light pixels are transparent and its dark ones black. + let pale = solid_square(super::super::EXTRUDE, Color::rgb(0.9, 0.9, 0.7), json!({})); + let (meshes, lighting) = scene_of(&pale); + let at = |color_model| render(&meshes, &lighting, RenderSettings { color_model, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap().pixels; + let (color, bitmap) = (at(RasterColorModel::Document), at(RasterColorModel::Bitmap)); + let mut clear = 0; + for (c, b) in color.chunks(4).zip(bitmap.chunks(4)) { + assert!(b == [0, 0, 0, 255] || b == [0; 4], "bitmap pixel {b:?} is black or transparent"); + let luma = 0.2126 * f64::from(c[0]) + 0.7152 * f64::from(c[1]) + 0.0722 * f64::from(c[2]); + if c[3] == 255 && luma > 130.0 { + assert_eq!(b, [0; 4], "a light pixel {c:?} is transparent"); + clear += 1; + } else if c[3] == 255 && luma < 125.0 { + assert_eq!(b, [0, 0, 0, 255], "a dark pixel {c:?} is black"); + } + } + assert!(clear > 0, "the pale solid has light pixels"); +} + +/// Grayscale gives each pixel the Rec. 709 luma of the pixel the document's color mode gives, and +/// Bitmap makes each pixel black or white over a white background and black or transparent on a +/// transparent one. The effect's `colorModel` sets the model, and a new model makes a new image. +#[test] +fn the_color_model_makes_gray_or_black_and_white_pixels() { + use vectorcraft_doc::RasterColorModel; + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (meshes, lighting) = scene_of(&n); + let at = |color_model, white| { + render(&meshes, &lighting, RenderSettings { color_model, white, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap().pixels + }; + for white in [false, true] { + let (color, gray, bitmap) = + (at(RasterColorModel::Document, white), at(RasterColorModel::Grayscale, white), at(RasterColorModel::Bitmap, white)); + assert_eq!((color.len(), gray.len(), bitmap.len()), (color.len(), color.len(), color.len())); + let (mut colored, mut blacks, mut whites) = (0, 0, 0); + for ((c, g), b) in color.chunks(4).zip(gray.chunks(4)).zip(bitmap.chunks(4)) { + assert_eq!(g[3], c[3], "white {white}: grayscale keeps each pixel's coverage"); + assert!(g[0] == g[1] && g[1] == g[2], "white {white}: grayscale pixel {g:?}"); + if white { + assert_eq!(b[3], c[3], "white {white}: bitmap keeps each pixel's coverage"); + } else { + assert!(b == [0, 0, 0, 255] || b == [0; 4], "on a transparent background bitmap pixel {b:?} is black or transparent"); + } + if c[3] == 255 { + let luma = 0.2126 * f64::from(c[0]) + 0.7152 * f64::from(c[1]) + 0.0722 * f64::from(c[2]); + assert!((f64::from(g[0]) - luma).abs() <= 1.0, "white {white}: gray {g:?} for {c:?}, luma {luma}"); + assert!(b[..3] == [0; 3] || b[..3] == [255; 3], "white {white}: bitmap pixel {b:?}"); + blacks += usize::from(b == [0, 0, 0, 255]); + whites += usize::from(b == [255; 4]); + } + colored += usize::from(c[0] != c[1] || c[1] != c[2]); + } + assert!(colored > 0, "white {white}: the document's color mode keeps the paint's color"); + // Over white, the background is white and the blue solid has dark pixels. On a transparent + // background nothing is white. + assert!(blacks > 0 && (whites > 0) == white, "white {white}: bitmap gives {blacks} black and {whites} white pixels"); + } + // Grayscale and Bitmap images are stored as gray PNGs, and the document's color mode as RGBA. + for (color_model, kinds) in [ + (RasterColorModel::Document, [image::ColorType::Rgba8, image::ColorType::Rgba8]), + (RasterColorModel::Grayscale, [image::ColorType::La8, image::ColorType::L8]), + (RasterColorModel::Bitmap, [image::ColorType::La8, image::ColorType::L8]), + ] { + for (white, kind) in [false, true].into_iter().zip(kinds) { + let image = render(&meshes, &lighting, RenderSettings { color_model, white, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap(); + let object = image_object(&image).unwrap(); + let blob = object.pixels.unwrap(); + let decoded = image::load_from_memory(&blob.bytes).unwrap(); + assert_eq!(decoded.color(), kind, "{color_model:?}, white {white}"); + assert_eq!(decoded.to_rgba8().into_raw(), image.pixels, "{color_model:?}, white {white}: the PNG holds the pixels"); + } + } + let settings = |model: &str| crate::render_settings(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "colorModel": model}})); + assert_eq!(settings("bitmap").map(|s| s.color_model), Some(RasterColorModel::Bitmap)); + assert_eq!(settings("grayscale").map(|s| s.color_model), Some(RasterColorModel::Grayscale)); + assert_eq!(settings("document").map(|s| s.color_model), Some(RasterColorModel::Document)); + let default = crate::render_settings(super::super::EXTRUDE, &json!({"render": {"mode": "rendered"}})); + assert_eq!(default.map(|s| s.color_model), Some(RasterColorModel::Document), "the document's color mode is the default"); + assert_eq!(settings("rgb"), None, "a model outside the three draws shaded"); + let count = || RASTERIZATIONS.with(|count| count.get()); + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let mut lit = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}})); + let draw = |n: &Node| images(&super::super::solid_art_drawn_in(Some(&doc), n).unwrap()).len(); + assert_eq!(draw(&lit), 1); + let start = count(); + lit.appearance.effects[0].params["render"]["colorModel"] = json!("grayscale"); + assert_eq!(draw(&lit), 1); + assert_eq!(count(), start + 1, "a new color model makes a new image"); +} + /// A mesh without a projection, or meshes with different ones, can't be placed: the image is refused. #[test] fn meshes_without_one_projection_are_refused() { @@ -857,7 +979,7 @@ fn drawn_images_share_the_pixel_limit() { let doc = vectorcraft_doc::Document::new(400.0, 400.0); let pixels = |resolution: f64| { let (meshes, lighting) = scene_of(&rotated_square(200.0, resolution)); - let settings = RenderSettings { quality: 0, resolution: Some(resolution), white: false }; + let settings = RenderSettings { quality: 0, resolution: Some(resolution), ..MEDIUM }; let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); u64::from(m.cols) * u64::from(m.rows) }; @@ -1009,7 +1131,7 @@ fn check_counts_raster_work_only_for_drawn_triangles() { assert!(lighting.lights.iter().any(|l| lighting.casts(l))); let two = vec![meshes[0].clone(), meshes[0].clone()]; // At 600 ppi the image's raster work outweighs the draft shadow maps' work. - let settings = RenderSettings { quality: 0, resolution: Some(600.0), white: false }; + let settings = RenderSettings { quality: 0, resolution: Some(600.0), ..MEDIUM }; let limits = |max_work| { let mut limits = Limits::default(); limits.max_work = max_work; @@ -1650,7 +1772,7 @@ fn a_medium_render_stays_within_its_work_bound() { let mut n = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); n.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "resolution": 300}})).unwrap()); let (meshes, lighting) = scene_of(&n); - let settings = RenderSettings { quality: 1, resolution: Some(300.0), white: false }; + let settings = RenderSettings { quality: 1, resolution: Some(300.0), ..MEDIUM }; let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); assert_eq!(m.samples, 2); let samples = u64::from(m.cols) * u64::from(m.rows) * 4; @@ -1692,7 +1814,7 @@ fn edge_values_render_or_are_refused() { meshes[0].mesh.triangles.push([first[0], first[0], first[1]]); assert!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).is_ok(), "zero-area triangle"); for resolution in [1.0, 2400.0] { - let settings = RenderSettings { quality: 0, resolution: Some(resolution), white: false }; + let settings = RenderSettings { quality: 0, resolution: Some(resolution), ..MEDIUM }; let image = render(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); assert!(image.cols >= 1 && image.rows >= 1, "{resolution} ppi"); } diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index 9ad0597c5c..833bcb7f11 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, RasterColorModel, StrokeLayer}; use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath}; use vectorcraft_three_d::Facet; @@ -21,8 +21,8 @@ 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`], with the rendered image's `quality` ([`RENDER_QUALITIES`]), `resolution` and -/// `background` ([`RENDER_BACKGROUNDS`]). +/// [`RENDER_MODES`], with the rendered image's `quality` ([`RENDER_QUALITIES`]), `resolution`, +/// `background` ([`RENDER_BACKGROUNDS`]) and `colorModel` ([`RENDER_COLOR_MODELS`]). pub const RENDER: &str = "render"; /// The render modes of a 3D effect: `shaded` draws the lit faces, `wireframe` the edges of every @@ -37,6 +37,11 @@ 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 color models of the rendered image, the ids of [`RasterColorModel`]: RGB pixels in every +/// document, grayscale, or two pixel values, black and white on a white background and black and +/// transparent on a transparent one. +pub const RENDER_COLOR_MODELS: [&str; 3] = ["document", "grayscale", "bitmap"]; + /// The index in [`RENDER_QUALITIES`] of the quality a `render` without one takes (VectorCraft's own /// default). const DEFAULT_QUALITY: usize = 1; @@ -51,6 +56,8 @@ pub struct RenderSettings { /// A white background, which makes the image opaque; otherwise it is transparent where no /// surface or shadow is. pub white: bool, + /// The image's color model, applied after the background. + pub color_model: RasterColorModel, } impl RenderSettings { @@ -73,6 +80,11 @@ pub fn render_settings(id: &str, p: &Value) -> Option { 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"), + color_model: render + .get("colorModel") + .and_then(Value::as_str) + .and_then(|m| RasterColorModel::ALL.into_iter().find(|c| c.id() == m)) + .unwrap_or_default(), }) } @@ -83,7 +95,8 @@ pub fn renders_image(fx: &Effect) -> bool { /// 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)"; + resolution (null or a number from 1 to 2400), background (transparent or white) and colorModel \ + (document, grayscale or bitmap)"; /// Check one `render` value against [`RENDER_RULES`]. fn check_render(render: &Value) -> Result<(), String> { @@ -93,6 +106,7 @@ fn check_render(render: &Value) -> Result<(), String> { "mode" => one_of(value, &RENDER_MODES), "quality" => one_of(value, &RENDER_QUALITIES), "background" => one_of(value, &RENDER_BACKGROUNDS), + "colorModel" => one_of(value, &RENDER_COLOR_MODELS), "resolution" => value.is_null() || value.as_f64().is_some_and(|r| (1.0..=2400.0).contains(&r)), _ => false, }) @@ -124,8 +138,9 @@ 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`]), /// `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) +/// per inch), `background` (one of [`RENDER_BACKGROUNDS`]) and `colorModel` (one of +/// [`RENDER_COLOR_MODELS`]). A key left out takes its default: `shaded`, `medium`, the document's +/// raster effects resolution, `transparent` and `document`. 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(()) }; diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs index f99be96a94..31238b08b8 100644 --- a/crates/effects/src/solids/wireframe/tests.rs +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -419,8 +419,9 @@ fn expanding_a_revolve_in_wireframe_mode_gives_the_edges() { } /// `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. +/// rendered), `quality` (low, medium or high), `resolution` (null or 1 to 2400), `background` +/// (transparent or white) and `colorModel` (document, grayscale or bitmap), and only on the panel's +/// four effects. #[test] fn render_settings_are_validated() { for id in WIRE { @@ -434,6 +435,9 @@ fn render_settings_are_validated() { json!({"render": {"mode": "rendered", "quality": "low", "resolution": null, "background": "transparent"}}), json!({"render": {"resolution": 1}}), json!({"render": {"resolution": 2400}}), + json!({"render": {"mode": "rendered", "colorModel": "document"}}), + json!({"render": {"mode": "rendered", "colorModel": "grayscale"}}), + json!({"render": {"colorModel": "bitmap"}}), ] { assert_eq!(crate::validate_three_d_params(id, &good), Ok(()), "{id} {good}"); } @@ -448,12 +452,16 @@ fn render_settings_are_validated() { json!({"render": {"mode": "rendered", "resolution": "300"}}), json!({"render": {"mode": "rendered", "background": "black"}}), json!({"render": {"mode": "rendered", "samples": 4}}), + json!({"render": {"mode": "rendered", "colorModel": "rgb"}}), + json!({"render": {"mode": "rendered", "colorModel": "Grayscale"}}), + json!({"render": {"mode": "rendered", "colorModel": null}}), + json!({"render": {"mode": "rendered", "colorModel": 1}}), ] { let e = crate::validate_three_d_params(id, &bad).unwrap_err(); 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)", + or a number from 1 to 2400), background (transparent or white) and colorModel (document, grayscale or bitmap)", "{id} {bad}" ); } diff --git a/crates/effects/src/stroke.rs b/crates/effects/src/stroke.rs index 6dfcacce2f..4845057236 100644 --- a/crates/effects/src/stroke.rs +++ b/crates/effects/src/stroke.rs @@ -11,19 +11,18 @@ //! - [`for_writer`] and [`outline_region`]: strokes for the SVG/PDF writers and Outline Stroke; //! - [`gradient_slices`] and [`gradient_meshes`]: gradients laid along or across a stroke. -mod arrow; mod dash; mod gradient; mod outline; mod width; -use std::borrow::Cow; - use kurbo::{BezPath, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Rect, Shape}; +use vectorcraft_doc::arrow; use vectorcraft_doc::{LineCap, LineJoin, StrokeAlign, StrokeLayer}; pub(crate) use vectorcraft_geom::bez::{kink, segments, subpaths, tangent, unit}; -pub use arrow::Arrow; +pub(crate) use arrow::push_seg; +pub use arrow::{Arrow, StrokePieces, cap_extent, stroke_pieces}; pub use dash::{Dashed, Dot, dash, dash_kept, dot_outline}; pub use gradient::{Slice, WrittenSlices, gradient_meshes, gradient_slices, written_slices}; pub use outline::{OUTLINE_TOL, Written, WrittenShape, for_writer, is_plain, outline_region}; @@ -32,24 +31,6 @@ pub use width::width_outline; /// Arc-length accuracy for dashing and trimming (document points). const ARCLEN_ACCURACY: f64 = 1e-6; -/// The geometry one stroke paints, in the coordinate space of its path. -#[derive(Clone, Debug)] -pub struct StrokePieces<'a> { - /// The centre line to stroke: the path with its ends trimmed under the arrowheads (borrowed - /// when nothing is trimmed). Empty when the heads cover the whole path. - pub line: Cow<'a, BezPath>, - /// The arrowheads, start first. Closed ends get none. - pub heads: Vec, -} - -/// The centre line and arrowheads of stroke `st` along `bp`. -pub fn stroke_pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a> { - if st.start_arrow.is_none() && st.end_arrow.is_none() { - return StrokePieces { line: Cow::Borrowed(bp), heads: vec![] }; - } - arrow::pieces(bp, st) -} - /// Does `bp` end with a `ClosePath`? pub fn is_closed(bp: &BezPath) -> bool { bp.elements().last().is_some_and(|e| matches!(e, PathEl::ClosePath)) @@ -64,14 +45,6 @@ pub fn aligned_width(st: &StrokeLayer, closed: bool) -> f64 { } } -/// How far a cap reaches past the end of a stroke of `width`. -pub fn cap_extent(cap: LineCap, width: f64) -> f64 { - match cap { - LineCap::Butt => 0.0, - LineCap::Round | LineCap::Square => width / 2.0, - } -} - /// The stroke style (cap, join, miter limit) of `st` at `width`, without dashes. pub fn style(st: &StrokeLayer, width: f64) -> kurbo::Stroke { kurbo::Stroke::new(width) @@ -221,15 +194,6 @@ fn reaches_edge(contour: &[PathEl], path: &BezPath, reach: f64) -> bool { kurbo::segments(contour.iter().copied()).any(|s| far(s.eval(0.0)) || far(s.eval(0.5))) } -/// Append `seg` to `out` (which must already have a current point at its start). -pub(crate) fn push_seg(out: &mut BezPath, seg: &PathSeg) { - match seg { - PathSeg::Line(l) => out.line_to(l.p1), - PathSeg::Quad(q) => out.quad_to(q.p1, q.p2), - PathSeg::Cubic(c) => out.curve_to(c.p1, c.p2, c.p3), - } -} - #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index aa4ea8dc9f..4a50131a7d 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -1,3 +1,5 @@ +use std::borrow::Cow; + use kurbo::{BezPath, PathEl, Point, Rect, Shape, Vec2}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{ArrowAlign, Arrowhead, Dash, LineCap, StrokeLayer, WidthProfile}; diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a06b163888..2487dcd01d 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -17,11 +17,6 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"] # feature still recognizes the files and refuses them with a message. The apps list it beside # `bundled-fonts`. heif = ["dep:heic-rs", "dep:rayon"] -# Binary CGM files open and place. Off until the craft-metafile CGM reader (craft-libs#5410) merges -# and the workspace pins it; the build fails with this feature on before then. Without it, `.cgm` -# is not listed as readable or placeable anywhere. Turning it on also needs `cgm` in -# `UNASSOCIATED_EXTS` (`src/cmd/fileio/formats.rs`). -cgm = ["vectorcraft-metafile/cgm"] [dependencies] craft-codepage = { workspace = true } diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index d777e31a45..d62f427068 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -184,6 +184,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails }, BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams }, BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media }, + BuiltinBrushLibrary { id: "impact-bursts", name: "Impact Bursts", make: impact_bursts }, BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit }, BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving }, BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows }, @@ -1216,6 +1217,70 @@ pub(crate) fn dry_media() -> BrushLibrary { built("Dry Media", Document::new(100.0, 100.0), brushes) } +/// Impact Bursts: art brushes for hit sparks, shocks and crack strokes (original game VFX art). +fn impact_bursts() -> BrushLibrary { + let star = group(vec![ + black(polygon(&[(0.0, 0.0), (100.0, -8.0), (88.0, 0.0), (100.0, 8.0)])), + black(polygon(&[(12.0, 0.0), (70.0, -14.0), (62.0, 0.0), (70.0, 14.0)])), + black(polygon(&[(20.0, 0.0), (48.0, -18.0), (42.0, 0.0), (48.0, 18.0)])), + black(polygon(&[(28.0, 0.0), (40.0, -10.0), (36.0, 0.0), (40.0, 10.0)])), + ]); + let ring_shock = + group(vec![ring(Point::new(50.0, 0.0), 18.0, 14.0), ring(Point::new(50.0, 0.0), 28.0, 25.0), ring(Point::new(50.0, 0.0), 38.0, 36.0)]); + let slash = { + let n = 40; + let half = |x: f64| { + let t = x / 100.0; + let arch = 10.0 * (t * std::f64::consts::PI).sin(); + 1.4 + 2.2 * (1.0 - (t - 0.5).abs() * 2.0).max(0.0) + arch * 0.05 + }; + let mid = |x: f64| 8.0 * ((x / 100.0) * std::f64::consts::PI).sin() - 4.0; + let xs = |i: usize| 100.0 * i as f64 / n as f64; + let mut pts: Vec = (0..=n).map(xs).map(|x| Point::new(x, mid(x) - half(x))).collect(); + pts.extend((0..n).rev().map(xs).map(|x| Point::new(x, mid(x) + half(x)))); + PathData::single(SubPath::polyline(&pts, true)) + }; + let spark_fan = group(vec![ + black(polygon(&[(0.0, 0.0), (55.0, -16.0), (48.0, -12.0)])), + black(polygon(&[(0.0, 0.0), (70.0, -6.0), (62.0, -2.0)])), + black(polygon(&[(0.0, 0.0), (100.0, 0.0), (90.0, 2.0)])), + black(polygon(&[(0.0, 0.0), (70.0, 6.0), (62.0, 2.0)])), + black(polygon(&[(0.0, 0.0), (55.0, 16.0), (48.0, 12.0)])), + black(polygon(&[(0.0, 0.0), (35.0, -10.0), (30.0, -6.0)])), + black(polygon(&[(0.0, 0.0), (35.0, 10.0), (30.0, 6.0)])), + ]); + let debris = group(vec![ + black(shapes::rectangle(Rect::new(4.0, -3.0, 12.0, 1.0))), + black(polygon(&[(18.0, 2.0), (28.0, -2.0), (30.0, 4.0)])), + black(shapes::rectangle(Rect::new(36.0, -4.0, 44.0, -1.0))), + black(polygon(&[(50.0, 1.0), (58.0, 5.0), (62.0, -2.0)])), + black(shapes::rectangle(Rect::new(68.0, -2.0, 78.0, 2.0))), + black(polygon(&[(82.0, -4.0), (90.0, -1.0), (88.0, 3.0)])), + black(shapes::rectangle(Rect::new(92.0, 0.0, 100.0, 3.0))), + ]); + let crack = band(100.0, 1.4, 48, |x| { + let t = (x / 8.0).floor(); + let local = (x / 8.0) - t; + let amp = if (t as i32) % 3 == 0 { + 5.0 + } else if (t as i32) % 3 == 1 { + -3.5 + } else { + 2.0 + }; + if (t as i32) % 2 == 0 { amp * local } else { amp * (1.0 - local) } + }); + let brushes = vec![ + art("Star Burst", star, Colorization::Tints), + art("Ring Shock", ring_shock, Colorization::Tints), + art("Slash Arc", black(slash), Colorization::Tints), + art("Spark Fan", spark_fan, Colorization::Tints), + art("Debris Spray", debris, Colorization::Tints), + art("Crack Line", black(crack), Colorization::Tints), + ]; + built("Impact Bursts", Document::new(100.0, 100.0), brushes) +} + // ---------- commands ---------- fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo { diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index edffa17055..5dfce8eb8e 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -63,6 +63,7 @@ pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> R store_grid(Arc::make_mut(&mut st.doc), &g); if let Some(it) = &mut st.interaction { store_grid(Arc::make_mut(&mut it.doc), &g); + it.revision = st.revision + 1; } st.revision += 1; Ok(g) @@ -745,6 +746,7 @@ pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) { } if let Some(it) = &mut st.interaction { clear(&mut it.doc); + it.revision = st.revision + 1; } st.revision += 1; } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index dc0bf5c730..ce8da61e05 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -835,6 +835,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { let doc = std::mem::replace(&mut st.doc, e.doc); keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); + st.selections = st.selections.wrapping_add(1); let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; @@ -873,6 +874,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { let doc = std::mem::replace(&mut st.doc, e.doc); keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); + st.selections = st.selections.wrapping_add(1); let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 47218dd6a1..de276328e2 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -247,8 +247,7 @@ mod tests_svgimport; #[cfg(test)] mod tests_eps; -// The CGM reader waits on craft-libs#5410 (the `cgm` feature). -#[cfg(all(test, feature = "cgm"))] +#[cfg(test)] mod tests_cgm; #[cfg(test)] mod tests_dwgimport; diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index dd7d0ce71e..4576e81024 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -573,6 +573,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def | "dwg" | "emf" | "wmf" + | "pict" | "hpgl" | "ai" ) diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs index 04aef3563a..148942b386 100644 --- a/crates/engine/src/cmd/fileio/cdr.rs +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -112,7 +112,9 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec)> { why => err(format!("this CDR drawing can't be read ({why})")), })?; let (doc, mut warnings) = build(&d, note, PAGES_CUT); - if d.version >= FRAMES_FROM && d.warnings.iter().any(|w| matches!(w, Warning::UnsupportedObjects | Warning::TooDeep)) { + // Objects the reader or the mapping left out (bitmaps are read but not placed), or content past the reader's limits. + let left_out = warnings.iter().any(|w| w == UNSUPPORTED_OBJECTS) || d.warnings.contains(&Warning::TooDeep); + if d.version >= FRAMES_FROM && left_out { warnings.push(EMPTY_FRAMES.to_string()); } Ok((doc, warnings)) @@ -423,6 +425,8 @@ fn copy_cost(objects: &[cd::Object]) -> usize { match o { cd::Object::Group { objects: kids, .. } => stack.extend(kids), cd::Object::Shape(s) => n = n.saturating_add(shape_cost(s)), + // A bitmap or text is not placed, so it takes nothing past the object itself. + cd::Object::Image(_) | cd::Object::Text(_) => {} cd::Object::Clip { container, objects } => { // A container whose outline is behind its fill is built twice, as that outline // and as the clipping path, inside a group of their own. diff --git a/crates/engine/src/cmd/fileio/cdr/shapes.rs b/crates/engine/src/cmd/fileio/cdr/shapes.rs index 320fda877c..9d0f9cdc91 100644 --- a/crates/engine/src/cmd/fileio/cdr/shapes.rs +++ b/crates/engine/src/cmd/fileio/cdr/shapes.rs @@ -74,6 +74,8 @@ impl Builder { self.learn_spot(c); } } + // Bitmaps and text are not placed, so their colors add no swatch. + cd::Object::Image(_) | cd::Object::Text(_) => {} cd::Object::Group { objects: kids, .. } => stack.extend(kids), cd::Object::Clip { container, objects } => { for c in container.fill.iter().chain(container.outline.iter().map(|o| &o.color)) { @@ -123,6 +125,8 @@ impl Builder { for o in objects.iter().rev() { match o { cd::Object::Shape(s) => out.extend(self.shape(s, to_doc, false).map(|n| with_flags(n, s.flags))), + // Bitmaps and text are left out, and the warnings name them with the other objects not read. + cd::Object::Image(_) | cd::Object::Text(_) => self.note(Warning::UnsupportedObjects), cd::Object::Group { objects: kids, flags } => { let children = self.objects_at(kids, to_doc, depth + 1); if !children.is_empty() { @@ -452,6 +456,7 @@ mod tests { master: vec![], guides: vec![], warnings: vec![], + left_out: Default::default(), }; let doc = Builder::new().document(&d); let swatch = doc.swatches.iter().find(|s| s.name == "Red ink").unwrap(); @@ -494,6 +499,7 @@ mod tests { master: vec![], guides: vec![], warnings: vec![], + left_out: Default::default(), }; assert!(Document::new(612.0, 792.0).swatches.iter().any(|s| s.name == "Black" && !s.spot)); let doc = Builder::new().document(&d); @@ -535,6 +541,7 @@ mod tests { master: vec![master], guides: vec![], warnings: vec![], + left_out: Default::default(), }; let mut b = Builder::new(); b.copies_left = 1000; @@ -571,6 +578,7 @@ mod tests { master: vec![master], guides: vec![], warnings: vec![], + left_out: Default::default(), }; let mut b = Builder::new(); b.copies_left = 1000; @@ -644,6 +652,7 @@ mod tests { master: vec![], guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 90.0, hidden }], warnings: vec![], + left_out: Default::default(), }; let doc = Builder::new().document(&d); doc.layers @@ -671,6 +680,7 @@ mod tests { master: vec![], guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 45.0, hidden: false }], warnings: vec![], + left_out: Default::default(), }; let mut b = Builder::new(); let doc = b.document(&d); @@ -744,6 +754,7 @@ mod tests { master: vec![], guides: vec![], warnings: vec![], + left_out: Default::default(), }; let doc = Builder::new().document(&drawing(vec![vec![layer(cd::Flags::default(), objects)]])); let kids = doc.layers[0].children().unwrap(); diff --git a/crates/engine/src/cmd/fileio/cmx.rs b/crates/engine/src/cmd/fileio/cmx.rs index 29e8a22696..454ceaf168 100644 --- a/crates/engine/src/cmd/fileio/cmx.rs +++ b/crates/engine/src/cmd/fileio/cmx.rs @@ -103,7 +103,15 @@ pub(super) fn encode(doc: &Document, f: &super::Format, p: &Value, use_artboards .collect(); pages.push(cd::Page { size: Some((r.width().abs(), r.height().abs())), layers }); } - let drawing = cd::Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: Vec::new() }; + let drawing = cd::Drawing { + version: 0, + page_size: None, + pages, + master: Vec::new(), + guides: Vec::new(), + warnings: Vec::new(), + left_out: Default::default(), + }; // The limits `document.open` reads `.cmx` files with, so the file opens whole again. let written = craft_cdr::write_cmx(&drawing, Limits::default()).map_err(|e| bad(C, e.to_string()))?; for (set, w) in [ diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index d025da9f89..98eed35e58 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Serialize Document", [], None, - "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)", + "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|pict|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)", has_doc, export::serialize ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|pict|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …pict writes a QuickDraw version 2 picture (.pct) of the artboard as emf and wmf do (up to 16 device units a point; at most 32,767 points on a side; fills as polygons, strokes as their filled outlines and images over white; what it leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Export Selection…", ["File"], None, - "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|cmx|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})", + "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|pict|hpgl|cmx|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})", has_selection, export::export_selection ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 1c0fc50e7c..23c096c2d3 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1094,7 +1094,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result { } // Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so // themselves: SVG only when it outlines or embeds fonts). - if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl" | "cmx")) + if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "pict" | "hpgl" | "cmx")) && let Some(w) = crate::cmd::fonts::substitution_warning(doc) { enc.warnings.push(w); @@ -1136,7 +1136,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { let n = doc.artboards.len(); // SVG reads its own `useArtboards` (an SVG option). let use_artboards = - if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "dwg" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None }; + if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "dwg" | "emf" | "wmf" | "pict" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None }; // `rect`: that area of the page, as if it were the only artboard (the document is not changed). if let Some(rect) = page_rect(f, p)? { let mut q = super::export::without_artboards(p); @@ -1181,6 +1181,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { "eps" => return super::eps::encode(doc, p), "emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf), "wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf), + "pict" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Pict), "hpgl" => return super::hpgl::encode(doc, p, use_artboards), "cmx" => return super::cmx::encode(doc, f, p, use_artboards), "ai" => return super::save::encode_ai(C, f, doc, p), diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index b01b4cf8fd..0fab10d8af 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -575,11 +575,20 @@ pub const FORMATS: &[Format] = &[ // `.cmx` exchange files with 32-bit coordinates, read and written by `craft-cdr`: a page for // each chosen artboard, with the art's fills and strokes in their colors. Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS }, - // QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images. - reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false), + // QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images, + // and written by `vectorcraft_metafile::export` as version 2 pictures (`.pct`). + Format { + id: "pict", + label: "PICT", + extensions: &["pct", "pic", "pict"], + mime: "image/x-pict", + read: true, + write: true, + raster: false, + options: metafile::OPTIONS, + }, // Binary Computer Graphics Metafiles, read by `vectorcraft_metafile::import_cgm` into paths, - // type and images. Behind the `cgm` feature until craft-libs#5410 merges. - #[cfg(feature = "cgm")] + // type and images. reader("cgm", "CGM", &["cgm"], "image/cgm", false), // Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size // composite, the layers combined, or the preview with a note. Exports don't write them. @@ -654,7 +663,6 @@ pub const OPEN_EXTS: &[&str] = &[ "pct", "pic", "pict", - #[cfg(feature = "cgm")] "cgm", "plt", "hpgl", @@ -681,12 +689,11 @@ pub const OPEN_EXTS: &[&str] = &[ /// names of PNG, BMP and JPEG files (File › Open and Place still read them all). On Linux the desktop /// entry's EPS and JPEG types (shared-mime-info's) also cover `.epsf` and `.jpe`, so file managers /// offer VectorCraft for them. -/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft` -/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either. CGM files are added here -/// when the `cgm` feature is turned on (craft-libs#5410). +/// The packaging declares no type for HP-GL plot files, PICT pictures, CGM files, layered raster +/// `.pcraft` documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "jpe", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", - "jpc", "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt", + "jpc", "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "cgm", "pcraft", "dwg", "dws", "dwt", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -773,7 +780,6 @@ pub const PLACE_EXTS: &[&str] = &[ "pct", "pic", "pict", - #[cfg(feature = "cgm")] "cgm", "plt", "hpgl", diff --git a/crates/engine/src/cmd/fileio/metafile.rs b/crates/engine/src/cmd/fileio/metafile.rs index 23d4978218..95c6bdfb9f 100644 --- a/crates/engine/src/cmd/fileio/metafile.rs +++ b/crates/engine/src/cmd/fileio/metafile.rs @@ -2,8 +2,8 @@ //! `document.export {format: emf|wmf}` and Export As (one picture of an artboard, or one per //! artboard with Use Artboards; raster effects as images, rendered at the document's raster //! effects resolution), `document.open` and File → Place (one artboard, the picture's frame). -//! QuickDraw pictures (PICT) and binary Computer Graphics Metafiles (CGM) open and place the same -//! way; they are never written. +//! QuickDraw pictures (PICT) are written (`format: pict`) and open and place the same way. Binary +//! Computer Graphics Metafiles (CGM) open and place the same way; they are never written. use serde_json::Value; use vectorcraft_doc::Document; @@ -14,7 +14,7 @@ use super::{ArtboardPick, Encoded, FormatOption}; const C: &str = "document.export"; -/// The options `document.formats` lists for EMF and WMF. +/// The options `document.formats` lists for EMF, WMF and PICT. pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, super::RANGE, super::USE_ARTBOARDS]; /// Encode `doc` as `kind`: the chosen artboard (default the first), or with `use_artboards` one @@ -46,7 +46,7 @@ pub(super) fn encode_flattening( .iter() .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) .collect::>>()?; - vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?; + vectorcraft_metafile::check_regions_for(&rects, kind).map_err(|e| bad(C, e))?; // Raster effects (shadows, glows, blurs) as images, as PDF export does. let flat = flatten(doc); let src = flat.as_ref().unwrap_or(doc); diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index 41649366f1..b116399d98 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -26,8 +26,8 @@ pub const OPTIONS: &[FormatOption] = &[ FormatOption { name: "version", ty: "integer", - default: "4", - description: "the format version to write: 4 (current), or 3, 2 or 1 for older VectorCraft versions (1 and 2 are never compressed; newer features they don't know are lost there)", + default: "5", + description: "the format version to write: 5 (current), or 4, 3, 2 or 1 for older VectorCraft versions (1 and 2 are never compressed; newer features they don't know are lost there)", }, FormatOption { name: "preview", @@ -202,7 +202,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: impl std::io::Write) -> Result<()> { let (mut so, extras) = save_options(cmd, f, doc, p)?; // Include Linked Files keeps placed documents' files; older versions get their art. - let full = if so.include_linked || so.version < vectorcraft_format::VERSION { + let full = if so.include_linked || so.version < vectorcraft_format::PLACED_SINCE { crate::cmd::place::document::full_documents(doc).0 } else { std::borrow::Cow::Borrowed(doc) @@ -223,7 +223,7 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp } drop(drawn); let native = match full { - Cow::Owned(full) if so.include_linked && so.version >= vectorcraft_format::VERSION => { + Cow::Owned(full) if so.include_linked && so.version >= vectorcraft_format::PLACED_SINCE => { // Include available bytes without replacing missing, relinkable placed objects. let mut original = doc.clone(); original.images = full.images; @@ -242,7 +242,7 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp /// groups of their art for older versions. fn rounded(doc: &Document, version: u32, decimals: u8) -> Document { let mut d = doc.clone(); - if version < vectorcraft_format::VERSION { + if version < vectorcraft_format::PLACED_SINCE { vectorcraft_format::placed_as_groups(&mut d); } d.round_geometry(decimals.min(vectorcraft_format::MAX_PRECISION)); diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 7de7c5cf8c..5e3a9d7ff7 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -46,9 +46,10 @@ impl ScreenSize { /// `2x` (or `2`), `100w`, `100h` or `72ppi`, in any case; positive numbers only. pub fn parse(s: &str) -> Option { let s = s.trim().to_ascii_lowercase(); - // Digits and `.` only: `str::parse` would also take `+2`, `1e2`, `inf` and `nan`. + // Digits and `.` only: `str::parse` would also take `+2`, `1e2`, `inf` and `nan`. Digits of + // other scripts read as ASCII digits do (`"२x"` is `2x`), as number fields read them. let num = |t: &str| { - let t = t.trim(); + let t = vectorcraft_doc::ascii_digits(t.trim())?; if !t.bytes().all(|b| b.is_ascii_digit() || b == b'.') { return None; } @@ -196,7 +197,7 @@ pub(super) fn name_without_device(name: &str) -> String { pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"]; /// The writable formats a format row can't name. -pub(crate) const UNWRITTEN_FORMATS: [&str; 8] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx", "dwg"]; +pub(crate) const UNWRITTEN_FORMATS: [&str; 9] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx", "dwg", "pict"]; /// One format row: what to write, at which size, with which suffix, into which sub-folder. struct Row { diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 7200c7e43b..ab785f23e1 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -535,6 +535,7 @@ fn export_extensions_name_every_writable_format() { "tga", "psd", "cmx", + "pct", "dwg" ] ); @@ -573,6 +574,7 @@ fn formats_query_lists_readers_writers_and_options() { "tga", "psd", "cmx", + "pict", "dwg" ] ); diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 2e4d82822b..4728c56065 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -537,7 +537,7 @@ fn containers_open_as_clipping_groups() { assert!(children[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. }))); } -/// A container whose clipped group holds only objects the reader leaves out (a bitmap here), or +/// A container whose clipped group holds only objects the reader leaves out (text here), or /// whose group holds a container of that same group, opens as a plain shape, and the warnings /// say that such frames opened empty. #[test] @@ -554,7 +554,7 @@ fn containers_whose_contents_were_left_out_are_named_in_the_warnings() { super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap() }; let frames = "PowerClip frames whose contents were left out opened empty"; - let (doc, warnings) = open(vec![synth::object(v, 5, &[(30, v.rect(10.0, 10.0, 0.0))], None)]); + let (doc, warnings) = open(vec![synth::object(v, 4, &[(30, v.rect(10.0, 10.0, 0.0))], None)]); let p = paths(&doc); let [frame] = p.as_slice() else { panic!("{p:?}") }; assert!(matches!(frame.kind, NodeKind::Path { clipping: false, .. }), "{:?}", frame.kind); @@ -566,6 +566,41 @@ fn containers_whose_contents_were_left_out_are_named_in_the_warnings() { assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}"); } +/// A bitmap the reader decodes is not placed: the drawing opens without it, and the warnings name +/// the bitmaps left out. A container that clips only a bitmap opens with its clipping path alone, +/// and the warnings say that such frames opened empty. +#[test] +fn bitmaps_are_left_out_and_named_in_the_warnings() { + let v = V(1300); + let gray = synth::Bitmap { model: 5, bpp: 8, width: 3, height: 2, palette: vec![], rows: vec![vec![0; 3], vec![0; 3]] }; + let open = |bitmaps: Vec, objects: Vec| { + let body = vec![ + chunk(b"vrsn", 1300u16.to_le_bytes().to_vec()), + list(b"bmpt", bitmaps), + synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", objects)]), + ]; + super::cdr::import(&synth::riff(1300, &body)).unwrap() + }; + let rect = || synth::object(v, 1, &[(30, v.rect(40.0, 40.0, 0.0))], None); + let frames = "PowerClip frames whose contents were left out opened empty"; + + let (doc, warnings) = open(vec![synth::bmp(v, 1, &gray, None)], vec![synth::bitmap_object(v, 1, (0.0, 2.0), (3.0, 0.0), None), rect()]); + let p = paths(&doc); + let [shape] = p.as_slice() else { panic!("{p:?}") }; + assert!(matches!(shape.kind, NodeKind::Path { clipping: false, .. }), "{:?}", shape.kind); + assert!(warnings.iter().any(|w| w.contains("text, bitmaps")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}"); + + let clipped = synth::clpt(vec![(0x77, vec![synth::bitmap_object(v, 1, (0.0, 2.0), (3.0, 0.0), None)])]); + let container = synth::object(v, 1, &[(30, v.rect(40.0, 40.0, 0.0)), synth::container(0x77)], None); + let (doc, warnings) = open(vec![synth::bmp(v, 1, &gray, None), clipped], vec![container]); + let p = paths(&doc); + let [frame] = p.as_slice() else { panic!("{p:?}") }; + assert!(matches!(frame.kind, NodeKind::Path { clipping: true, .. }), "{:?}", frame.kind); + assert!(warnings.iter().any(|w| w.contains("text, bitmaps")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}"); +} + /// An object with a lens or transparency opens opaque, and the warnings say so. #[test] fn lenses_and_transparency_are_named_in_the_warnings() { diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 14f7462495..3b2825f162 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -322,9 +322,9 @@ fn formats_list_dxf_and_what_can_not_be_written() { #[test] fn pict_and_pagemaker_say_what_to_use_instead() { let mut s = two_boards(); - // PICT opens; it isn't written. - let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string(); - assert!(e.contains("PICT files can be opened but not written"), "{e}"); + // PCX opens; it isn't written. + let e = s.execute("document.export", &json!({"format": "pcx"})).unwrap_err().to_string(); + assert!(e.contains("PCX files can be opened but not written"), "{e}"); let e = s .execute("document.open", &json!({"name": "old.pct", "dataBase64": vectorcraft_format::base64_encode(&[0u8; 600])})) .unwrap_err() diff --git a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs index 2541225a79..633f0558c0 100644 --- a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs +++ b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs @@ -476,7 +476,7 @@ fn placed_carried_fonts_survive_break_link_and_older_version_save() { assert_eq!(embedded["embedded"], json!([id.0]), "{embedded}"); assert_eq!(glyphs(&s).1, 1); } - let version = if break_link { vectorcraft_format::VERSION } else { vectorcraft_format::VERSION - 1 }; + let version = if break_link { vectorcraft_format::VERSION } else { vectorcraft_format::PLACED_SINCE - 1 }; let saved = s.execute("document.serialize", &json!({"format": "vectorcraft", "version": version, "preview": false})).unwrap(); let reopened = s.execute("document.open", &json!({"name": "placed-font.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap(); assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}"); diff --git a/crates/engine/src/cmd/fileio/tests_pict.rs b/crates/engine/src/cmd/fileio/tests_pict.rs index 513adffbef..b0e7c58670 100644 --- a/crates/engine/src/cmd/fileio/tests_pict.rs +++ b/crates/engine/src/cmd/fileio/tests_pict.rs @@ -1,6 +1,6 @@ //! PICT pictures through the commands: `document.open` by extension or by content, File › Place as -//! one group clipped to the picture's frame, the dialogs' filters and the format list, and files -//! that aren't pictures, or a PICT export, refused with a message. +//! one group clipped to the picture's frame, `document.export` of one artboard or each, the dialogs' +//! filters and the format list, and files that aren't pictures refused with a message. use serde_json::json; use vectorcraft_doc::NodeKind; @@ -83,8 +83,47 @@ fn files_that_are_not_pictures_are_refused() { let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); png.extend(&picture()[8..]); assert!(detect("x.png", &png).is_none_or(|f| f.id != "pict")); - let e = s.execute("document.export", &json!({"format": "pict"})).expect_err("refused").to_string(); - assert!(e.contains("PICT files can be opened but not written"), "{e}"); +} + +fn data(r: &serde_json::Value) -> Vec { + vectorcraft_format::base64_decode(r["dataBase64"].as_str().expect("dataBase64")).unwrap() +} + +#[test] +fn document_export_writes_a_picture_that_opens_again() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap(); + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 5, "width": 20, "height": 10})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap(); + let r = s.execute("document.export", &json!({"format": "pict"})).unwrap(); + assert_eq!((r["format"].as_str(), &r["warnings"]), (Some("pict"), &json!([])), "{r}"); + let bytes = data(&r); + assert_eq!(detect("x.bin", &bytes).map(|f| f.id), Some("pict")); + assert_eq!(writable_format(None, Some("x/logo.pct")).unwrap().id, "pict"); + // The first artboard: its red rectangle, in place. + let mut back = Session::new(); + back.execute("document.open", &json!({"name": "logo.pct", "dataBase64": b64(&bytes)})).unwrap(); + let doc = &back.doc().unwrap().doc; + assert_eq!(doc.artboards[0].rect.size(), (100.0, 100.0).into()); + let mut paths = vec![]; + doc.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + paths.push(n.clone()); + } + }); + assert_eq!(paths.len(), 1); + let b = paths[0].geometric_bounds().unwrap(); + let want = vectorcraft_geom::Rect::new(10.0, 20.0, 40.0, 60.0); + assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 0.07), "{b:?}"); + assert_eq!(paths[0].appearance.fill().and_then(|f| f.paint.color()).map(|c| c.to_rgba8(1.0)), Some([255, 0, 0, 255])); + // Use Artboards: one picture each. + let r = s.execute("document.export", &json!({"format": "pict", "useArtboards": true})).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 2); + assert!(files[1]["name"].as_str().unwrap().ends_with("-Artboard-2.pct"), "{files:?}"); } #[test] @@ -98,7 +137,6 @@ fn the_dialogs_and_the_format_list_name_pict() { assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter)); let r = Session::new().execute("document.formats", &json!({})).unwrap(); let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pict").unwrap().clone(); - assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)), "{f}"); + assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(true), Some(false)), "{f}"); assert_eq!(f["mime"], "image/x-pict"); - assert!(writable_format(None, Some("x/logo.pct")).is_err()); } diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index 93c4d7e6b1..491fca372e 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -72,6 +72,17 @@ fn sizes_parse_as_factor_width_height_or_resolution() { ); } +#[test] +fn sizes_read_digits_of_other_scripts() { + assert_eq!(ScreenSize::parse("२x"), Some(ScreenSize::Scale(2.0))); + assert_eq!(ScreenSize::parse("૧૦૦W"), Some(ScreenSize::Width(100.0))); + assert_eq!(ScreenSize::parse("१४४ppi"), Some(ScreenSize::Ppi(144.0))); + // One digit set per number, and the same grammar as ASCII digits. + for bad in ["1२x", "१.5x", "-२x", "०w"] { + assert_eq!(ScreenSize::parse(bad), None, "{bad}"); + } +} + #[test] fn a_width_or_height_row_gives_that_many_pixels() { let mut s = session(1); diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index ef37bd7d99..303ea9d424 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -461,6 +461,7 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { crate::cmd::distortcmds::finish_edit_text(st, inner); st.isolation = Some(layer); st.selection.set([left]); + st.selections = st.selections.wrapping_add(1); st.revision += 1; return ok(); } @@ -498,6 +499,7 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { crate::cmd::distortcmds::finish_edit_text(st, i); let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left); st.selection.set([target]); + st.selections = st.selections.wrapping_add(1); // A guide path isolated while Lock Guides is on isn't selected (#1534). crate::deselect_hidden(&menu, &st.doc, &mut st.selection); // The art on a locked artboard can't be selected. diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index 97dd890457..1447532743 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -71,7 +71,11 @@ fn resolution(v: &Value) -> Result { "screen" => 72.0, "medium" => 150.0, "high" => 300.0, - other => other.trim_end_matches("ppi").trim().parse::().map_err(|_| bad(C, format!("unknown resolution `{v}`")))?, + // Digits of other scripts read as ASCII digits do (`"३००"` is 300), as number fields read them, + // with one digit set for the whole value, exponent included (`"१e2"` is refused). + other => vectorcraft_doc::ascii_digits_one_number(other.trim_end_matches("ppi").trim()) + .and_then(|n| n.parse::().ok()) + .ok_or_else(|| bad(C, format!("unknown resolution `{v}`")))?, }, v => v.as_f64().ok_or_else(|| bad(C, "resolution must be a number or screen|medium|high"))?, }; diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 4ee4f01c10..9978cfab91 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -12,7 +12,7 @@ use vectorcraft_tools::builder::is_live_paint; use super::appearance::{ItemTarget, edit_items, item_target}; use super::paint::{live_paint_parts_skipped, painted}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index_opt, ok, str_param}; use crate::DocState; use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer}; @@ -77,10 +77,19 @@ pub fn specs() -> Vec { "Reset Profiles", [], None, - "{} remove every saved profile, leaving the built-ins → {removed: count}", - has_saved_profiles, + "{} remove every saved profile, leaving the built-ins in their first order → {removed: count}", + can_reset_profiles, profile_reset ), + cmd!( + "stroke.widthProfile.move", + "Move Width Profile", + [], + None, + "{name: a profile's id or label (stroke.widthProfile.list; not Uniform, which stays first), to: its new place among the profiles after Uniform (0 = right after Uniform)} reorder the Profile list (kept with the preferences) → {order: the ids after Uniform}", + always, + profile_move + ), cmd!( query "stroke.widthProfile.list", "Width Profiles", @@ -710,12 +719,23 @@ impl ProfileEntry<'_> { } impl Session { - /// The Profile list: the built-in profiles, then the saved ones. + /// The Profile list: Uniform, then the other built-in profiles and the saved ones in + /// [`Prefs::width_profile_order`](crate::Prefs::width_profile_order) (by default the built-ins, then the saved + /// ones). A profile the order doesn't name follows the ones it does, in the default order. pub fn profile_entries(&self) -> impl Iterator> { - let built_in = WidthProfile::PRESETS.iter().map(|p| ProfileEntry { id: p.id, label: p.label, points: p.points, built_in: true }); - let saved = - self.prefs.width_profiles.iter().map(|p| ProfileEntry { id: &p.name, label: &p.name, points: &p.profile.points, built_in: false }); - built_in.chain(saved) + let uniform = std::iter::once(WidthProfile::PRESETS[0]).map(|p| ProfileEntry { id: p.id, label: p.label, points: p.points, built_in: true }); + let mut rest: Vec> = WidthProfile::PRESETS[1..] + .iter() + .map(|p| ProfileEntry { id: p.id, label: p.label, points: p.points, built_in: true }) + .chain(self.prefs.width_profiles.iter().map(|p| ProfileEntry { id: &p.name, label: &p.name, points: &p.profile.points, built_in: false })) + .collect(); + let order = &self.prefs.width_profile_order; + if !order.is_empty() { + let place: std::collections::HashMap<&str, usize> = order.iter().enumerate().rev().map(|(at, id)| (id.as_str(), at)).collect(); + // A stable sort keeps the default order among the profiles the order doesn't name. + rest.sort_by_key(|e| place.get(e.id).copied().unwrap_or(usize::MAX)); + } + uniform.chain(rest) } /// The Profile list row showing `p` (`None`: the plain stroke), if it is listed. @@ -759,6 +779,21 @@ fn has_saved_profiles(s: &Session) -> std::result::Result<(), String> { if s.prefs.width_profiles.is_empty() { Err("no saved profiles".into()) } else { Ok(()) } } +fn can_reset_profiles(s: &Session) -> std::result::Result<(), String> { + if s.prefs.width_profiles.is_empty() && s.prefs.width_profile_order.is_empty() { + Err("no saved profiles, and the list is in its first order".into()) + } else { + Ok(()) + } +} + +/// Keeps `order` (the ids after Uniform) as the Profile list's order, storing none when it is the default one. +fn set_profile_order(s: &mut Session, order: Vec) { + let default: Vec<&str> = WidthProfile::PRESETS[1..].iter().map(|p| p.id).chain(s.prefs.width_profiles.iter().map(|p| p.name.as_str())).collect(); + let is_default = order.len() == default.len() && order.iter().zip(&default).all(|(a, b)| a == b); + s.prefs.width_profile_order = if is_default { vec![] } else { order }; +} + fn profile_add(s: &mut Session, p: &Value) -> Result { const C: &str = "stroke.widthProfile.add"; let profile = s.profile_to_add().map_err(|e| bad(C, e))?; @@ -787,14 +822,50 @@ fn profile_delete(s: &mut Session, p: &Value) -> Result { } let i = s.prefs.width_profiles.iter().position(|sp| sp.name == name).ok_or_else(|| bad(C, format!("no saved profile called {name}")))?; s.prefs.width_profiles.remove(i); + // A profile saved later under the same name goes to the end of the list, not to this one's place. + if !s.prefs.width_profile_order.is_empty() { + // The whole list as it now shows, so an order that matches the default is no longer stored. + let order = s.profile_entries().skip(1).map(|e| e.id.to_string()).collect(); + set_profile_order(s, order); + } Ok(json!({ "deleted": name })) } fn profile_reset(s: &mut Session, _: &Value) -> Result { let removed = std::mem::take(&mut s.prefs.width_profiles).len(); + s.prefs.width_profile_order.clear(); Ok(json!({ "removed": removed })) } +fn profile_move(s: &mut Session, p: &Value) -> Result { + const C: &str = "stroke.widthProfile.move"; + let name = match p.get("name") { + None | Some(Value::Null) => return Err(bad(C, "missing `name`")), + Some(v) => v.as_str().ok_or_else(|| bad(C, "`name` must be a profile's id or label"))?, + }; + let to = index_opt(p, "to", C)?.ok_or_else(|| bad(C, "missing `to`"))?; + let mut entries = s.profile_entries(); + let uniform = entries.next().map(|e| (e.id, e.label)); + if uniform.is_some_and(|(id, label)| id == name || label == name) { + return Err(bad(C, "Uniform stays first in the Profile list")); + } + let mut order: Vec = entries.map(|e| e.id.to_string()).collect(); + let from = s + .profile_entries() + .skip(1) + .position(|e| e.id == name || e.label == name) + .ok_or_else(|| bad(C, format!("no width profile called {name} (see stroke.widthProfile.list)")))?; + if to >= order.len() { + return Err(bad(C, format!("`to` must be less than {}, the number of profiles after Uniform", order.len()))); + } + if from != to { + let id = order.remove(from); + order.insert(to, id); + set_profile_order(s, order.clone()); + } + Ok(json!({ "order": order })) +} + fn profile_list(s: &mut Session, _: &Value) -> Result { let profiles: Vec = s .profile_entries() diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index c1da77255b..c94ee35c33 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -51,6 +51,9 @@ pub struct DocState { /// Increments on every change (also selection and view-only changes); UIs re-render when it /// moves. Not a dirty flag: see [`DocState::is_dirty`]. pub revision: u64, + /// Increments each time the selection is set through [`crate::Session::select`] and the other + /// selection entries, even when it ends as it was. Not saved, not undoable. + pub selections: u64, /// The document as last saved (or opened). Structural sharing makes "unchanged" a pointer /// comparison, and undoing back to the saved state counts as clean. pub(crate) saved_doc: Arc, @@ -544,6 +547,7 @@ impl DocState { history: History { limit: 500, ..Default::default() }, path, revision: 1, + selections: 0, active_layer, layer_rows: vec![], layers_reveal: None, diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 323d5d0918..ea28d8675e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -7,6 +7,11 @@ use vectorcraft_geom::Rect; use crate::Session; +/// The new-art paint state before the running preview, or its current value without a preview. +pub fn new_art_paint_before_preview(s: &Session) -> &vectorcraft_tools::PaintDefaults { + s.active().and_then(|st| st.interaction.as_ref()).map_or(&s.paint, |it| &it.paint) +} + pub(crate) fn rect_json(r: Option) -> Value { match r { Some(r) => json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }), diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 825fd4c986..34d5eb0bbc 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -11,8 +11,8 @@ pub struct Interaction { /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, pub(crate) active_appearance_item: Option, - /// The document's [`crate::DocState::revision`] when the interaction began. The previews change the document's - /// revision, and this value stays the same until the interaction ends. + /// The baseline document's [`crate::DocState::revision`]. Previews keep this value; replacing or changing the + /// baseline advances it to the document's next revision. pub revision: u64, pub preview: Option<(String, Value)>, /// The active tool began it (a drag): a command from outside the tool runs as a step of its diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e48cc79425..5fb106a303 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -108,6 +108,8 @@ pub struct Session { /// ([`Session::painting_tool`]); None for a stop of the selection's paint. A pick armed for /// such a stop samples only into a stop selected on that gradient, and otherwise ends. pub(crate) stop_pick: Option, + /// The point and document revision the Eyedropper was armed for. + freeform_point_pick: Option, /// Pointer and key input that came while the tool computed an edit on another thread, each with /// its number and view, made in order once the edit is applied. held_input: std::collections::VecDeque<(u64, tooling::HeldInput, ViewInfo)>, diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 4a85763667..eda96e8c5d 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -68,6 +68,53 @@ type Recipient = (String, String, u64); #[cfg(test)] std::thread_local! { pub(crate) static RECIPIENT_IDENTITIES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many [`EventPluginsHeld`] this thread holds. + static EVENT_PLUGINS_HELD: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The thread whose test has events plug-ins installed in the process-wide registry, if any. +#[cfg(test)] +static EVENT_PLUGINS_OWNER: std::sync::Mutex> = std::sync::Mutex::new(None); +#[cfg(test)] +static EVENT_PLUGINS_FREED: std::sync::Condvar = std::sync::Condvar::new(); + +/// Held by a test that installs events plug-ins in the process-wide registry. Every such plug-in +/// reacts to every session's changes and spends handlers of every session's frame budget +/// ([`MAX_FRAME_HANDLERS`]), so when tests run as threads of one process, another test's plug-ins +/// would take the handlers a test counts on. A thread waits while another thread holds one; the +/// guards one thread holds count as one, until the last of them is dropped. +#[cfg(test)] +pub(crate) struct EventPluginsHeld { + /// Dropped on the thread that made it. + _thread: std::marker::PhantomData<*const ()>, +} + +#[cfg(test)] +pub(crate) fn hold_event_plugins() -> EventPluginsHeld { + if EVENT_PLUGINS_HELD.with(std::cell::Cell::get) == 0 { + let me = std::thread::current().id(); + let mut owner = EVENT_PLUGINS_OWNER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + while owner.is_some_and(|t| t != me) { + owner = EVENT_PLUGINS_FREED.wait(owner).unwrap_or_else(std::sync::PoisonError::into_inner); + } + *owner = Some(me); + } + EVENT_PLUGINS_HELD.with(|n| n.set(n.get() + 1)); + EventPluginsHeld { _thread: std::marker::PhantomData } +} + +#[cfg(test)] +impl Drop for EventPluginsHeld { + fn drop(&mut self) { + let last = EVENT_PLUGINS_HELD.with(|n| { + n.set(n.get() - 1); + n.get() == 0 + }); + if last { + *EVENT_PLUGINS_OWNER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = None; + EVENT_PLUGINS_FREED.notify_all(); + } + } } /// The recipient `p` is. @@ -836,6 +883,7 @@ mod tests { use serde_json::json; use vectorcraft_plugins::wat as tpl; let id = "test.events.nested"; + let _held = hold_event_plugins(); let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.allow_plugin_grants_from_requests(); diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 0cb1cf613f..46faf6e3d5 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -373,6 +373,11 @@ pub struct Prefs { /// Preferences dialog field, so it has no [`cmd::prefscmds::PREF_SPECS`] row. #[serde(skip_serializing_if = "Vec::is_empty")] pub width_profiles: Vec, + /// The order of the Profile list's rows after Uniform (`stroke.widthProfile.move`): built-in ids and saved + /// profile names. Empty is the default order, the built-ins and then the saved profiles. Not a Preferences + /// dialog field, so resetting the preferences keeps it; Reset Profiles clears it. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub width_profile_order: Vec, /// General → Use Japanese Crop Marks: the style of Create Trim Marks and Effect → Crop Marks. pub japanese_crop_marks: bool, /// Appearance panel → New Art Has Basic Appearance (on): new art takes one fill and stroke; @@ -732,6 +737,7 @@ impl Default for Prefs { trace_presets: vec![], gradient_presets: vec![], width_profiles: vec![], + width_profile_order: vec![], japanese_crop_marks: false, new_art_basic: true, color_themes: vec![], diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1b94c0d5d4..cccecfb816 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -64,6 +64,7 @@ impl Session { lender: None, back_to_painter: None, stop_pick: None, + freeform_point_pick: None, held_input: Default::default(), input_count: 0, edit_started_by: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index dd31393158..7cfa4187cb 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -252,8 +252,64 @@ impl Session { fn select_unwatched(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> { self.active_appearance_item = None; + let uid = self.doc()?.uid; + self.select_document_unwatched(uid, f) + } + + /// Change the selection in an open document without switching the active document. + pub fn select_in_document(&mut self, uid: u64, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> { + if self.active().is_some_and(|st| st.uid == uid) { + return self.select(f); + } + self.select_document_unwatched(uid, f) + } + + /// Give document `uid` back a selection it had, new art included, through the selection + /// filters as they are now: guides locked since, hidden or locked slices and art on a locked + /// artboard that is not new art are left out. In the active document, outside a command and an + /// interaction, the journal records the selection that comes back, with the current layer kept, + /// in the open undo groups too, and the paints for new art load from it as `select.set` loads + /// them (with New Art Has Basic Appearance on, a symbol part or an Objects on Path member does + /// not load its paints, as `symbol.instance.selectPart` and + /// `object.objectsOnPath.selectMember` do not), so a recorded action replays as it ran. + pub fn restore_selection(&mut self, uid: u64, selection: Selection) -> Result<()> { + let active = self.active().is_some_and(|st| st.uid == uid && st.interaction.is_none()) && self.depth == 0; + let st = self.document_mut(uid).ok_or(EngineError::NoDocument)?; + let (made, layer) = (st.selection.clone(), st.active_layer); + st.selection_record = None; + st.selection = selection; + self.select_in_document(uid, |_, _| {})?; + if !active { + return Ok(()); + } + let Some(st) = self.document_mut(uid) else { return Ok(()) }; + if st.selection == made { + return Ok(()); + } + let steps = selection_steps(&st.selection, &made, &st.doc, layer, &st.highlighted_rows()); + // Only the selection commands load paints on replay: a symbol part comes back through + // `symbol.instance.selectPart` and an Objects on Path member through + // `object.objectsOnPath.selectMember`, which load none. + let loads = steps.iter().any(|(id, _)| id.starts_with("select.") || id == "layer.target"); + let (from, grouped) = (self.journal.len(), self.undo_group_docs()); + for step in steps { + self.journal.push(step); + } + self.journal_in_undo_groups(Some(uid), &grouped, from); + // As `Session::execute` does after a selection command, which starts without the marker + // of a defaults-only paint that ran before it. + self.defaults_only_ran = None; + self.inherit_new_art(); + if loads { + self.load_selection_paints(); + } + Ok(()) + } + + /// Apply the selection filters and update the editing state of document `uid`. + fn select_document_unwatched(&mut self, uid: u64, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> { let menu = self.menu.clone(); - let st = self.doc_mut()?; + let st = self.document_mut(uid).ok_or(EngineError::NoDocument)?; let before = st.selection.objects.clone(); let new_art = st.selection.new_art.clone(); let record = if st.selection_record().is_some() { st.selection_record.take() } else { None }; @@ -294,6 +350,7 @@ impl Session { st.layer_rows.clear(); } st.revision += 1; + st.selections = st.selections.wrapping_add(1); // Puppet Warp pins belong to the art they were placed on: another selection starts afresh. if st.doc.puppet.as_ref().is_some_and(|p| p.ids != st.selection.objects) { cmd::distortcmds::drop_puppet_pins(st); @@ -522,6 +579,8 @@ impl Session { return; } let began = std::mem::replace(&mut it.doc, st.doc.clone()); + st.revision += 1; + it.revision = st.revision; // The drag acts on the objects it began with: a selection the command made (a paste, a // duplicate, Select All) does not change what the drag moves. A dialog's preview acts on // the selection the command left, and its dialog previews again on its next pass, from the diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 88db34c705..1dd8e38a1d 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -24,6 +24,16 @@ fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value { r } +/// What [`Session::execute`] compares to tell that a command changed the selection: the counts of +/// what is selected and the first and last object, guide and slice, read in constant time. +type SelectionSummary = ([usize; 5], [Option; 6], bool); + +fn selection_summary(s: &Selection) -> SelectionSummary { + let counts = [s.objects.len(), s.anchors.len(), s.segments.len(), s.guides.len(), s.slices.len()]; + let ends = [s.objects.first(), s.objects.last(), s.guides.first(), s.guides.last(), s.slices.first(), s.slices.last()].map(|id| id.copied()); + (counts, ends, s.symbol_part.is_some()) +} + impl Session { /// Run a command callback and keep warnings from every preview it settles or restores. pub(crate) fn command_with_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> Result) -> Result { @@ -72,7 +82,19 @@ impl Session { if self.plugins_loading() && crate::waits_for_plugin_loads(id) { self.finish_plugin_loads(); } - self.revealing(|s| s.execute_unwatched(id, params)) + // A command, a step of a batch included, that leaves the active document with another + // selection counts as a selection change ([`crate::DocState::selections`]), whichever way + // it wrote the selection. The selections are compared by a summary that takes constant time. + let before = self.active().map(|st| (st.uid, st.selections, selection_summary(&st.selection))); + let r = self.revealing(|s| s.execute_unwatched(id, params)); + if let Some((uid, selections, summary)) = before + && let Some(st) = self.document_mut(uid) + && st.selections == selections + && selection_summary(&st.selection) != summary + { + st.selections = st.selections.wrapping_add(1); + } + r } /// Run `f`, a top-level entry that changes the active document's rows, current layer or @@ -230,7 +252,7 @@ impl Session { params.get("ids").filter(|v| !v.is_null()).cloned().or_else(|| given.map(|ids| ids.iter().map(|i| i.0).collect::>().into())) }) .flatten(); - let selected_before = select_first.as_ref().and(self.active()).map(|d| (d.uid, d.selection.clone(), d.active_layer)); + let selected_before = select_first.as_ref().and(self.active()).map(|d| (d.uid, d.selection.clone(), d.active_layer, d.selections)); // Only a selection command that changes the selection loads its paints for new art: other // commands, and clicking what is already selected, keep a sampled paint in the proxies. let selection_was = (id.starts_with("select.") || id == "layer.target").then(|| self.active().map(|d| d.selection.clone())).flatten(); @@ -240,11 +262,12 @@ impl Session { } let r = cmd::run_spec(s, spec, run_params); if r.is_err() - && let Some((uid, selection, layer)) = selected_before + && let Some((uid, selection, layer, selections)) = selected_before && let Some(st) = s.docs.iter_mut().find(|d| d.uid == uid) { st.selection = selection; st.active_layer = layer; + st.selections = selections; st.revision += 1; } r diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index 910fbda9f9..3d1f40f36d 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -118,6 +118,7 @@ impl Session { } let undone = std::mem::replace(&mut st.doc, e.doc); st.selection = Arc::unwrap_or_clone(e.selection); + st.selections = st.selections.wrapping_add(1); deselect_hidden(&self.menu, &st.doc, &mut st.selection); st.restore_isolation(g.isolation, &undone); st.sync_new_art(); @@ -276,6 +277,7 @@ impl Session { } let undone = std::mem::replace(&mut st.doc, doc); st.selection = selection; + st.selections = st.selections.wrapping_add(1); st.restore_isolation(scope.isolation, &undone); cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 2e809eaed9..d5397479b4 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -121,6 +121,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "game-trails", "energy-beams", "dry-media", + "impact-bursts", "tech-circuit", "engraving", "arrows", @@ -171,6 +172,12 @@ fn the_builtin_libraries_list_their_brush_names_and_counts() { [("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")] ); assert_eq!((entry("dry-media")["name"].as_str(), entry("dry-media")["count"].as_u64()), (Some("Dry Media"), Some(4))); + let impact = run(&mut s, "brush.library", json!({"library": "impact-bursts"})); + assert_eq!( + impact["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), + ["Star Burst", "Ring Shock", "Slash Arc", "Spark Fan", "Debris Spray", "Crack Line"] + ); + assert_eq!((libs[14]["name"].as_str(), libs[14]["count"].as_u64()), (Some("Impact Bursts"), Some(6))); let arrows = run(&mut s, "brush.library", json!({"library": "Arrows"})); assert_eq!( arrows["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::>(), @@ -204,6 +211,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() { ("game-trails", "art"), ("energy-beams", "art"), ("dry-media", "art"), + ("impact-bursts", "art"), ("arrows", "art"), ("image-brush", "scatter"), ("artistic", "art"), diff --git a/crates/engine/src/tests/effectedit.rs b/crates/engine/src/tests/effectedit.rs index 23f703af6a..b3ed23ee3e 100644 --- a/crates/engine/src/tests/effectedit.rs +++ b/crates/engine/src/tests/effectedit.rs @@ -284,6 +284,67 @@ fn image_widths(bytes: &[u8]) -> Vec { out } +/// `render.colorModel` outside document, grayscale and bitmap is refused before the document +/// changes. A valid one is saved with the effect and read back, and Grayscale gives the image +/// Expand Appearance leaves gray pixels, stored as a gray PNG. +#[test] +fn a_rendered_3d_color_model_is_checked_saved_and_drawn() { + let mut s = rendered_square(&[]); + let object = |s: &Session| { + let mut found = None; + for l in &s.doc().unwrap().doc.layers { + l.walk(&mut |n| { + if n.appearance.effects.iter().any(|e| e.id == "threeD.extrude") { + found = Some(n.clone()); + } + }); + } + found.unwrap() + }; + let before = object(&s); + let undo = s.doc().unwrap().history.undo.len(); + for bad in [json!("sepia"), json!("rgb"), json!(null), json!(2)] { + let params = json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered", "colorModel": bad}}}); + let e = s.execute("effect.setParams", ¶ms).unwrap_err().to_string(); + assert!(e.contains("colorModel (document, grayscale or bitmap)"), "{bad}: {e}"); + } + assert_eq!(object(&s), before, "a refused color model leaves the object unchanged"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + run( + &mut s, + "effect.setParams", + json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered", "quality": "low", "colorModel": "grayscale"}}}), + ); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let mut models = vec![]; + for l in &back.layers { + l.walk(&mut |n| { + for e in n.appearance.effects.iter().filter(|e| e.id == "threeD.extrude") { + models.push(vectorcraft_render::effects::render_settings(&e.id, &e.params).map(|r| r.color_model)); + } + }); + } + assert_eq!(models, vec![Some(vectorcraft_doc::RasterColorModel::Grayscale)], "the saved file keeps the color model"); + run(&mut s, "effect.expandAppearance", json!({})); + let doc = &s.doc().unwrap().doc; + let mut keys = vec![]; + for l in &doc.layers { + l.walk(&mut |n| { + if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { + keys.push(im.key.clone()); + } + }); + } + assert_eq!(keys.len(), 1, "{keys:?}"); + let decoded = image::load_from_memory(&doc.images[&keys[0]].bytes).unwrap(); + assert!(matches!(decoded.color(), image::ColorType::L8 | image::ColorType::La8), "a gray image is stored gray: {:?}", decoded.color()); + let pixels = decoded.to_rgba8(); + let opaque = pixels.pixels().filter(|p| p[3] == 255).count(); + assert!(opaque > 0, "the image covers the solid"); + let colored: Vec<_> = pixels.pixels().filter(|p| p[3] > 0 && !(p[0] == p[1] && p[1] == p[2])).take(4).collect(); + assert!(colored.is_empty(), "pixels with color in a grayscale image: {colored:?}"); +} + /// PDF and SVG export write one image for a rendered 3D object, and Expand Appearance leaves one /// embedded image of the same size in pixels that covers the object. #[test] diff --git a/crates/engine/src/tests/interaction_commands.rs b/crates/engine/src/tests/interaction_commands.rs index 00588ecf0c..4eefe43bc3 100644 --- a/crates/engine/src/tests/interaction_commands.rs +++ b/crates/engine/src/tests/interaction_commands.rs @@ -846,3 +846,58 @@ fn a_command_during_a_quick_pen_press_runs_inside_it() { assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{at}: no step of its own during the press"); } } + +#[test] +fn a_rebased_drag_advances_its_baseline_revision() { + for real_time in [true, false] { + let (mut s, _, other) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 140.0, 130.0); + let revision = s.doc().unwrap().interaction.as_ref().unwrap().revision; + pointer(&mut s, PointerKind::Drag, 150.0, 140.0); + assert_eq!(s.doc().unwrap().interaction.as_ref().unwrap().revision, revision, "previews keep the baseline revision"); + s.execute("appearance.setItem", &json!({"ids": [other.0], "index": 1, "weight": 3})).unwrap(); + let rebased = s.doc().unwrap().interaction.as_ref().unwrap().revision; + assert!(rebased > revision, "an outside document edit advances the baseline revision"); + pointer(&mut s, PointerKind::Drag, 160.0, 150.0); + assert_eq!(s.doc().unwrap().interaction.as_ref().unwrap().revision, rebased, "later previews keep the rebased revision"); + s.cancel_interaction().unwrap(); + assert_eq!(s.doc().unwrap().doc.node(other).unwrap().appearance.stroke().unwrap().width, 3.0); + } +} + +#[test] +fn a_grid_change_during_an_interaction_advances_its_baseline_revision() { + let (mut s, _) = session(true); + s.begin_interaction("Grid").unwrap(); + let revision = s.doc().unwrap().interaction.as_ref().unwrap().revision; + crate::cmd::distortcmds::silent(&mut s, |grid| grid.visible = !grid.visible).unwrap(); + let st = s.doc().unwrap(); + let it = st.interaction.as_ref().unwrap(); + assert!(it.revision > revision, "a direct baseline change advances its revision"); + assert_eq!(crate::cmd::distortcmds::grid_of(&it.doc).visible, crate::cmd::distortcmds::grid_of(&st.doc).visible); +} + +#[test] +fn leaving_perspective_type_editing_during_an_interaction_advances_its_baseline_revision() { + let (mut s, _) = crate::tests_persp_select::persp_session(); + let r = s.execute("text.create", &json!({"x": 430, "y": 400, "text": "HELLO", "size": 48})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("perspective.attach", &json!({"ids": [id.0], "plane": "right"})).unwrap(); + s.execute("perspective.editText", &json!({"id": id.0})).unwrap(); + s.begin_interaction("Edit").unwrap(); + let it = s.doc().unwrap().interaction.as_ref().unwrap(); + let revision = it.revision; + let text = it.doc.node(id).unwrap(); + assert!(text.extras().perspective.as_deref().unwrap().editing, "the baseline starts in Edit Text mode"); + assert!(text.projection().is_none(), "the baseline text is flat while editing"); + crate::cmd::distortcmds::finish_edit_text(s.doc_mut().unwrap(), id); + let st = s.doc().unwrap(); + let it = st.interaction.as_ref().unwrap(); + let text = it.doc.node(id).unwrap(); + assert!(!text.extras().perspective.as_deref().unwrap().editing, "the baseline leaves Edit Text mode"); + assert!(text.projection().is_some(), "the baseline text is projected again"); + assert!(it.revision > revision, "leaving Edit Text advances the baseline revision"); + assert_eq!(it.revision, st.revision, "the baseline revision is the document's new revision"); +} diff --git a/crates/engine/src/tests/objects_on_path.rs b/crates/engine/src/tests/objects_on_path.rs index d9e76f85bf..fc1066a8e1 100644 --- a/crates/engine/src/tests/objects_on_path.rs +++ b/crates/engine/src/tests/objects_on_path.rs @@ -875,3 +875,30 @@ fn objects_moved_out_together_in_the_layers_panel_all_leave_the_path() { let (layer, at) = place_of(&s, g); assert_eq!((place_of(&s, left), place_of(&s, middle)), ((layer, at + 1), (layer, at + 2)), "above the group, in their order"); } + +/// A restored Objects on Path member keeps the paints for new art as they are, as the journal +/// entry that records it (`object.objectsOnPath.selectMember`) does when it is replayed. +#[test] +fn a_restored_member_leaves_the_same_paints_live_and_on_replay() { + let mut s = session(); + let (g, [a, b, c], _) = three_on_a_line(&mut s); + s.execute("paint.setFill", &json!({"ids": [a.0, b.0, c.0, g.0], "color": "#ff0000"})).unwrap(); + s.execute("object.objectsOnPath.selectMember", &json!({"member": b.0})).unwrap(); + let saved = s.doc().unwrap().selection.clone(); + let blue = rect(&mut s, 400.0, 0.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [blue.0], "color": "#0000ff"})).unwrap(); + select(&mut s, &[blue]); + let before = s.paint.clone(); + let (uid, from) = (s.doc().unwrap().uid, s.journal.len()); + s.restore_selection(uid, saved.clone()).unwrap(); + assert_eq!(s.doc().unwrap().selection, saved); + assert_eq!(s.paint, before, "selecting a member keeps the paints for new art"); + let steps = s.journal.since(from).to_vec(); + assert_eq!(steps.iter().map(|(c, _)| c.as_str()).collect::>(), ["object.objectsOnPath.selectMember"]); + select(&mut s, &[blue]); + for (cmd, p) in steps { + s.execute(&cmd, &p).unwrap(); + } + assert_eq!(s.doc().unwrap().selection, saved); + assert_eq!(s.paint, before, "the replay leaves the same paints"); +} diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 5166c820c4..73a4a1a21b 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -1507,7 +1507,7 @@ fn saved_for_older_apps_placed_documents_in_brush_art_become_their_art() { n }; let prefix = vectorcraft_doc::placed_document::RESOURCE_PREFIX; - let older = vectorcraft_format::VERSION - 1; + let older = vectorcraft_format::PLACED_SINCE - 1; let old = vectorcraft_format::load(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "version": older})).unwrap())).unwrap(); assert_eq!(placed_in_brushes(&old), 0, "{}", old.unknown[vectorcraft_brush::DOC_KEY]); @@ -1519,6 +1519,8 @@ fn saved_for_older_apps_placed_documents_in_brush_art_become_their_art() { let current = vectorcraft_format::load(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap())).unwrap(); assert_eq!(placed_in_brushes(¤t), 2, "the current version keeps them placed"); assert!(current.symbols.iter().all(|s| !s.name.starts_with(prefix))); + let v4 = vectorcraft_format::load(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "version": 4})).unwrap())).unwrap(); + assert_eq!(placed_in_brushes(&v4), 2, "version 4 keeps them placed too"); // With a precision, the preview shows the brushes' art as the file holds it, rounded. let file = decode(&s.execute("file.saveCopy", &json!({"version": older, "precision": 0, "preview": true})).unwrap()); let saved = vectorcraft_format::load(&file).unwrap(); diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index f7ac63e770..0b0a4ba4ee 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -12,12 +12,33 @@ fn run(s: &mut Session, cmd: &str, p: Value) -> Value { s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) } -/// A session with a 400 × 200 document that takes `grant` from requests. -fn session() -> Session { +/// A session that holds [`crate::plugin_events::hold_event_plugins`] while it lives. +struct Held { + s: Session, + _held: crate::plugin_events::EventPluginsHeld, +} + +impl std::ops::Deref for Held { + type Target = Session; + fn deref(&self) -> &Session { + &self.s + } +} + +impl std::ops::DerefMut for Held { + fn deref_mut(&mut self) -> &mut Session { + &mut self.s + } +} + +/// A session with a 400 × 200 document that takes `grant` from requests. The plug-ins its test +/// installs are the only events plug-ins installed while it lives. +fn session() -> Held { + let held = crate::plugin_events::hold_event_plugins(); let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); s.allow_plugin_grants_from_requests(); - s + Held { s, _held: held } } fn rect(s: &mut Session, x: f64) -> NodeId { diff --git a/crates/engine/src/tests/rastersettings.rs b/crates/engine/src/tests/rastersettings.rs index 6e3ef16476..d918113114 100644 --- a/crates/engine/src/tests/rastersettings.rs +++ b/crates/engine/src/tests/rastersettings.rs @@ -91,6 +91,21 @@ fn settings_report_change_in_one_step_and_reject_junk() { assert_eq!(s.execute(C, &json!({"colorModel": "cmyk"})).unwrap()["colorModel"], "cmyk"); } +#[test] +fn a_resolution_given_as_text_reads_digits_of_other_scripts() { + let mut s = session(); + let r = s.execute(C, &json!({"resolution": "३०० ppi"})).unwrap(); + assert_eq!(r["resolution"].as_f64(), Some(300.0)); + assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 300.0); + // One digit set per number, exponent included, and the same 1 to 2400 ppi range as ASCII digits. + for bad in ["1५0", "५०००", "१e2", "1e२", "१e+2"] { + assert!(s.execute(C, &json!({"resolution": bad})).is_err(), "{bad}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + let r = s.execute(C, &json!({"resolution": "१e२"})).unwrap(); + assert_eq!(r["resolution"].as_f64(), Some(100.0)); +} + #[test] fn a_white_background_makes_effect_images_opaque() { let mut s = session(); diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 8fc2876981..da4411eb94 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -802,7 +802,7 @@ fn a_placed_items_file_binds_the_exact_id_of_the_image_placed() { /// it became is named by a fresh wrapper. #[test] fn a_stale_placed_item_is_refused_as_the_relative_object_of_move() { - let base = folder("stale-relative"); + let base = folder("stale-relative-move"); let a = base.join("main/a.png"); std::fs::write(&a, gray_png(4, 4)).unwrap(); let mut s = session(); diff --git a/crates/engine/src/tests/strokereach.rs b/crates/engine/src/tests/strokereach.rs index 87a9b64917..765613e5b5 100644 --- a/crates/engine/src/tests/strokereach.rs +++ b/crates/engine/src/tests/strokereach.rs @@ -40,9 +40,10 @@ fn a_300_percent_arrowhead_grows_the_visual_bounds() { let plain = fitted(&mut s); s.execute("stroke.setAdvanced", &json!({"arrowScale": [100, 300]})).unwrap(); let big = fitted(&mut s); - // The 24 pt head reaches past the end and 12 pt to each side of the line. - assert!(big.x1 > plain.x1 + 15.0 && big.y1 >= 212.0 && big.y0 <= 188.0, "{plain:?} → {big:?}"); - assert_eq!(big.x0, plain.x0, "the start has no head"); + // Extend places half of the solid triangle past the line end. Its 8 pt and + // 24 pt heads therefore project 4 pt and 12 pt, with the same half-width. + assert_eq!(plain, vectorcraft_geom::Rect::new(100.0, 196.0, 304.0, 204.0)); + assert_eq!(big, vectorcraft_geom::Rect::new(100.0, 188.0, 312.0, 212.0)); } #[test] diff --git a/crates/engine/src/tests/widthprofiles.rs b/crates/engine/src/tests/widthprofiles.rs index fe041dae43..3c39c96a64 100644 --- a/crates/engine/src/tests/widthprofiles.rs +++ b/crates/engine/src/tests/widthprofiles.rs @@ -127,6 +127,134 @@ fn saved_profiles_round_trip_with_the_preferences() { assert!(fresh.resolve_profile("Mine").is_some_and(|p| p == Some(custom()))); } +fn listed(s: &mut Session) -> Vec { + ids(&s.execute("stroke.widthProfile.list", &json!({})).unwrap()).into_iter().map(str::to_owned).collect() +} + +/// A line with two saved profiles, "Alpha" and "Beta", after the built-ins. +fn session_with_saved() -> Session { + let (mut s, id) = session_with_line(); + set_profile(&mut s, id, custom()); + s.execute("stroke.widthProfile.add", &json!({"name": "Alpha"})).unwrap(); + set_profile(&mut s, id, WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 0.0, 1.0)] }); + s.execute("stroke.widthProfile.add", &json!({"name": "Beta"})).unwrap(); + s +} + +#[test] +fn move_reorders_built_in_and_saved_profiles_below_uniform() { + let mut s = session_with_saved(); + let undo_depth = s.doc().unwrap().history.undo.len(); + // A built-in named by its label, and a saved profile by its name. + assert_eq!(s.execute("stroke.widthProfile.move", &json!({"name": "Wave", "to": 0})).unwrap()["order"][0], "wave"); + s.execute("stroke.widthProfile.move", &json!({"name": "Beta", "to": 1})).unwrap(); + s.execute("stroke.widthProfile.move", &json!({"name": "taperEnd", "to": 7})).unwrap(); + assert_eq!(listed(&mut s), ["uniform", "wave", "Beta", "lens", "taperStart", "pinch", "teardrop", "Alpha", "taperEnd"]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_depth, "the order is kept with the preferences, not the document"); + // The Stroke panel's rows follow it, and a moved profile still applies by its id. + assert_eq!(s.profile_entries().nth(2).map(|e| e.id), Some("Beta")); + s.execute("stroke.set", &json!({"profile": "wave"})).unwrap(); + assert_eq!(s.execute("stroke.widthProfile.list", &json!({})).unwrap()["current"], "wave"); + + // Moving a profile to the place it has leaves the list as it is. + let before = s.prefs.width_profile_order.clone(); + assert_eq!(s.execute("stroke.widthProfile.move", &json!({"name": "Beta", "to": 1})).unwrap()["order"][1], "Beta"); + assert_eq!(s.prefs.width_profile_order, before); + + // Moved back into the first order, the list stores no order. + s.execute("stroke.widthProfile.move", &json!({"name": "wave", "to": 5})).unwrap(); + s.execute("stroke.widthProfile.move", &json!({"name": "taperEnd", "to": 3})).unwrap(); + s.execute("stroke.widthProfile.move", &json!({"name": "Beta", "to": 7})).unwrap(); + assert_eq!(listed(&mut s), ["uniform", "lens", "taperStart", "taperEnd", "pinch", "teardrop", "wave", "Alpha", "Beta"]); + assert!(s.prefs.width_profile_order.is_empty()); +} + +#[test] +fn move_keeps_uniform_first_and_refuses_bad_params() { + let mut s = session_with_saved(); + for p in [ + json!({"name": "uniform", "to": 1}), + json!({"name": "Uniform", "to": 0}), + json!({"name": "Nope", "to": 0}), + json!({"name": "Alpha", "to": 8}), + json!({"name": "Alpha", "to": -1}), + json!({"name": "Alpha", "to": 1.5}), + json!({"name": "Alpha", "to": "1"}), + json!({"name": "Alpha"}), + json!({"name": 3, "to": 0}), + json!({"to": 0}), + ] { + assert!(s.execute("stroke.widthProfile.move", &p).is_err(), "{p}"); + } + let past_the_end = s.execute("stroke.widthProfile.move", &json!({"name": "Alpha", "to": 8})).unwrap_err().to_string(); + assert!(past_the_end.contains("must be less than 8"), "{past_the_end}"); + assert!(s.prefs.width_profile_order.is_empty(), "a refused move changes nothing"); + assert_eq!(listed(&mut s)[0], "uniform"); + // The last place is the last row. + s.execute("stroke.widthProfile.move", &json!({"name": "lens", "to": 7})).unwrap(); + assert_eq!(listed(&mut s).last().map(String::as_str), Some("lens")); +} + +#[test] +fn the_order_survives_the_preferences_and_resets_with_the_profiles() { + let mut s = session_with_saved(); + assert_eq!(s.execute("stroke.widthProfile.reset", &json!({})).unwrap()["removed"], 2); + // With only built-ins, a changed order is still something Reset Profiles puts back. + assert!(s.execute("stroke.widthProfile.reset", &json!({})).is_err()); + s.execute("stroke.widthProfile.move", &json!({"name": "pinch", "to": 0})).unwrap(); + let order = listed(&mut s); + assert_eq!(order[1], "pinch"); + + // It is written with the preferences, read back by a new session, and kept by Reset Preferences. + let json = s.prefs.to_json(); + assert_eq!(json["widthProfileOrder"][0], "pinch"); + let mut fresh = Session::new(); + fresh.apply_prefs(serde_json::from_value(json).unwrap()); + assert_eq!(listed(&mut fresh), order); + s.execute("prefs.reset", &json!({})).unwrap(); + assert_eq!(listed(&mut s), order); + assert!(Prefs::default().to_json().get("widthProfileOrder").is_none()); + + assert_eq!(s.execute("stroke.widthProfile.reset", &json!({})).unwrap()["removed"], 0); + assert_eq!(listed(&mut s), WidthProfile::PRESETS.iter().map(|p| p.id).collect::>()); +} + +#[test] +fn a_deleted_profile_leaves_the_order_and_a_new_one_goes_last() { + let (mut s, id) = session_with_line(); + set_profile(&mut s, id, custom()); + s.execute("stroke.widthProfile.add", &json!({"name": "Mine"})).unwrap(); + s.execute("stroke.widthProfile.move", &json!({"name": "Mine", "to": 0})).unwrap(); + s.execute("stroke.widthProfile.move", &json!({"name": "wave", "to": 1})).unwrap(); + s.execute("stroke.widthProfile.delete", &json!({"name": "Mine"})).unwrap(); + assert!(!s.prefs.width_profile_order.iter().any(|id| id == "Mine")); + // Saved again under the same name, it goes to the end instead of back to the top. + s.execute("stroke.widthProfile.add", &json!({"name": "Mine"})).unwrap(); + assert_eq!(listed(&mut s), ["uniform", "wave", "lens", "taperStart", "taperEnd", "pinch", "teardrop", "Mine"]); +} + +#[test] +fn deleting_the_only_moved_profile_clears_the_stored_order() { + let (mut s, id) = session_with_line(); + set_profile(&mut s, id, custom()); + s.execute("stroke.widthProfile.add", &json!({"name": "Alpha"})).unwrap(); + s.execute("stroke.widthProfile.move", &json!({"name": "Alpha", "to": 0})).unwrap(); + // Beta is saved after the move, so the stored order does not name it. + set_profile(&mut s, id, WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 0.0, 1.0)] }); + s.execute("stroke.widthProfile.add", &json!({"name": "Beta"})).unwrap(); + s.execute("stroke.widthProfile.delete", &json!({"name": "Alpha"})).unwrap(); + assert!(s.prefs.width_profile_order.is_empty(), "{:?}", s.prefs.width_profile_order); + assert_eq!(listed(&mut s).last().map(String::as_str), Some("Beta")); + + // A real custom order is kept after a delete. + s.execute("stroke.widthProfile.move", &json!({"name": "Beta", "to": 0})).unwrap(); + set_profile(&mut s, id, WidthProfile { points: vec![(0.0, 0.5, 0.5), (1.0, 1.0, 1.0)] }); + s.execute("stroke.widthProfile.add", &json!({"name": "Gamma"})).unwrap(); + s.execute("stroke.widthProfile.delete", &json!({"name": "Gamma"})).unwrap(); + assert_eq!(listed(&mut s)[1], "Beta"); + assert!(!s.prefs.width_profile_order.is_empty()); +} + #[test] fn every_built_in_applies_and_the_params_doc_names_them() { let (mut s, id) = session_with_line(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 4655bbaa61..ced5f4aee7 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -10,6 +10,11 @@ use vectorcraft_tools::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind use crate::{EngineError, Prefs, Result, Session}; +pub(crate) struct FreeformPointPick { + document: (u64, u64, u64), + index: usize, +} + /// What a hover's lend decision holds for ([`Session::hover_tool_at`]). #[derive(Clone, Copy, PartialEq)] pub(crate) struct HoverKey { @@ -229,6 +234,7 @@ impl Session { self.tool = self.make_tool(id); // A pick is armed for a stop after its tool is chosen (`note_stop_pick`). self.stop_pick = None; + self.freeform_point_pick = None; if let Some(selection) = text_selection { self.tool.set_option("textSelection", &selection); } @@ -633,7 +639,7 @@ impl Session { appearance_item: self.appearance_item(), constrain_angle: self.prefs.constrain_angle, keyboard_increment: self.prefs.keyboard_increment, - freeform_point: self.selected_freeform_point(), + freeform_point: if self.tool.id() == "eyedropper" { self.pick_freeform_point() } else { self.selected_freeform_point() }, raster_sample: self.prefs.eyedropper.sample_size, preview_bounds: self.prefs.use_preview_bounds, scale_strokes: self.prefs.scale_strokes, @@ -1637,6 +1643,9 @@ impl Session { let sets_pressed = self.press_taken_by(self.tool.id()); self.tool.set_option(key, v); self.note_stop_pick(key, self.tool.id() == "eyedropper"); + if key == "freeformPoint" && self.tool.id() == "eyedropper" { + self.note_freeform_point_pick(v); + } self.tool_set_since_reset = true; self.keep_tool_settings(); self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed); @@ -1733,9 +1742,14 @@ impl Session { }; self.keep_press_set(before_press, |k| values.contains_key(k) && (sets_pressed || shared.contains(&k)), sets_pressed); // The Eyedropper waiting for a Cmd-drag it lent a selection tool to is armed as the active one. - if (active || lender) && values.contains_key("stop") { + if active || lender { let eyedropper = id.unwrap_or(self.tool.id()) == "eyedropper"; - self.note_stop_pick("stop", eyedropper); + if values.contains_key("stop") { + self.note_stop_pick("stop", eyedropper); + } + if eyedropper && let Some(v) = values.get("freeformPoint") { + self.note_freeform_point_pick(v); + } } out } @@ -1761,6 +1775,24 @@ impl Session { } } + fn note_freeform_point_pick(&mut self, option: &Value) { + self.freeform_point_pick = None; + if option.is_string() + && let Some(doc) = self.active() + && let Some(index) = self.selected_freeform_point() + && self.proxy_freeform(!self.fill_active).is_some_and(|(f, _)| index < f.points.len()) + { + self.freeform_point_pick = Some(FreeformPointPick { document: (doc.uid, doc.revision, doc.reverts), index }); + } + } + + /// An index can outlive its point after a deletion or another paint is applied. + fn pick_freeform_point(&self) -> Option { + let pick = self.freeform_point_pick.as_ref()?; + let doc = self.active()?; + self.selected_freeform_point().filter(|&index| index == pick.index && pick.document == (doc.uid, doc.revision, doc.reverts)) + } + /// The tool that took the press under way: the active tool, or the tool that lent a selection /// tool for it (a Cmd-drag), which the dropped press gives its options back to. fn pressed_tool(&self) -> Option<&dyn Tool> { diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index edc89b319b..3dd3c406ac 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -4161,10 +4161,7 @@ proptest! { // ---------- Binary CGM files: opened and placed ---------- -// The CGM reader waits on craft-libs#5410: everything here is behind the `cgm` feature. - /// One CGM element, in the long form past 30 bytes, padded to an even length. -#[cfg(feature = "cgm")] fn cgm_el(class: u16, id: u16, data: &[u8]) -> Vec { let mut b = Vec::new(); if data.len() < 31 { @@ -4181,7 +4178,6 @@ fn cgm_el(class: u16, id: u16, data: &[u8]) -> Vec { } /// A metafile of one picture holding `body`. -#[cfg(feature = "cgm")] fn cgm_of(body: &[(u16, u16, Vec)]) -> Vec { let mut b = cgm_el(0, 1, b"\x01x"); b.extend(cgm_el(1, 1, &be16(&[3]))); @@ -4198,7 +4194,6 @@ fn cgm_of(body: &[(u16, u16, Vec)]) -> Vec { } /// A picture with lines, shapes, arcs, a figure, markers, text, a cell array and a clip. -#[cfg(feature = "cgm")] fn cgm_sample() -> Vec { cgm_of(&[ (5, 34, vec![8, 10, 20, 30, 40, 50, 60]), @@ -4232,7 +4227,6 @@ fn cgm_sample() -> Vec { } /// The sample the mutations start from opens with art, type and an image. -#[cfg(feature = "cgm")] #[test] fn the_cgm_sample_opens() { let l = vectorcraft_engine::cmd::fileio::load("x.cgm", &cgm_sample()).unwrap(); @@ -4249,14 +4243,12 @@ fn the_cgm_sample_opens() { /// CGM elements VectorCraft reads, and some it skips: the class in the high byte, the id in the /// low one. -#[cfg(feature = "cgm")] const CGM_ELEMENTS: [u16; 44] = [ 0x0008, 0x0009, 0x0103, 0x0104, 0x0105, 0x0107, 0x010A, 0x010C, 0x010D, 0x0113, 0x0201, 0x0202, 0x0203, 0x0207, 0x0301, 0x0302, 0x0305, 0x0306, 0x030A, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040B, 0x040C, 0x040D, 0x040F, 0x0411, 0x0412, 0x0414, 0x0418, 0x041A, 0x0503, 0x0504, 0x050F, 0x0510, 0x0512, 0x0522, 0x0801, ]; -#[cfg(feature = "cgm")] proptest! { #![proptest_config(config())] diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 82ed02f1f8..a952fbac6c 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -181,7 +181,7 @@ //! (gradients that dither are written without dither's noise, Perceptual gradients and gradients //! mixed around the hue wheel as the stops on their curve in process colors, at most 256, and //! gradient stops linked to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past -//! the tile or is painted with patterns, and pattern fills in symbols, as their tiles cut +//! the tile or is painted with patterns, and pattern fills in large-canvas symbols, as their tiles cut //! to the shape, clipping groups and clipping layers whose clipping object isn't a path, //! and the clipping groups inside them, as their art cut to that object (its fill cut too, its //! stroke not; an image in a clipping group of the region it is cut to), images that can't be @@ -225,7 +225,7 @@ use vectorcraft_pdf::PrivateData; use crate::ps; mod writer; -pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode}; +pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, PATTERN_SPACE_KEY, hex_decode}; use writer::Writer; diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index d4c7e1e449..5d7b429a39 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -6682,12 +6682,12 @@ fn instances_the_data_cant_hold_are_written_as_their_art() { } /// Symbols whose art paints with a pattern, directly, through a nested symbol, in an opacity mask -/// and through an inline graphic: their definitions hold the pattern fills as tiles cut to the shape (the reader keeps no -/// symbol whose art paints with a pattern), and their instances are written as their art, whose +/// and through an inline graphic: their definitions retain native pattern resources, and their +/// instances are written as their art, whose /// pattern fills keep the document's placement as the canvas draws them, each with a warning. An /// instance of a symbol without pattern paint stays an instance. #[test] -fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() { +fn symbols_with_pattern_fills_keep_resources_and_place_as_art() { let mut doc = Document::new(200.0, 100.0); // Tiles that cover the shape, so its tiles cut to it draw its box. let dot = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 8.0, 8.0), Color::BLACK)); @@ -6722,12 +6722,17 @@ fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() { let filled = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(150.0, 10.0, 182.0, 42.0)), fill()); doc.insert(Some(layer), usize::MAX, filled).unwrap(); let out = export_ai_editing(&doc, &opts()).unwrap(); - assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART) && out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::PATTERNS), "grid resources must not become tiles: {:?}", out.warnings); let back = read_back(&doc); let names: Vec<&str> = back.symbols.iter().map(|s| s.name.as_str()).collect(); assert_eq!(names, ["Patch", "Outer", "Masked", "Plain", "Typed"]); let patch = &back.symbols[0].art; - assert!(matches!(patch.kind, NodeKind::Group { .. }), "the symbol's art is its tiles: {:?}", patch.kind); + assert!( + matches!(patch.kind, NodeKind::Path { .. }) && vectorcraft_doc::pattern::uses_pattern(patch, Some("Dots")), + "the symbol must retain its original pattern-filled path: {:?}", + patch.kind + ); assert_eq!(instances(&back.symbols[1].art), 0, "the nested instance is its art"); let kids = back.layers[0].children().unwrap(); let kinds: Vec = kids.iter().map(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).collect(); @@ -6757,8 +6762,164 @@ fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() { same_lines(&boxes(&back), &boxes(&doc)); } +/// Original ruled tile shared by symbol art and an ordinary canvas object. The symbol's pattern +/// and geometry are scaled together, as editing its art with Transform Pattern Tiles does. +fn ruled_pattern_symbol(strokes: bool, tile_type: vectorcraft_doc::TileType, extent: f64) -> Document { + let mut doc = Document::new(240.0, 140.0); + let line = + Node::path(doc.alloc_id(), shapes::line((1.0, 5.0).into(), (9.0, 5.0).into()), Appearance::basic(Paint::None, solid(Color::BLACK), 2.0)); + let mut tile = vectorcraft_doc::PatternDef::new("Rules", vec![Arc::new(line)]); + tile.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + tile.tile_type = tile_type; + doc.patterns.push(tile); + let fill = || Appearance::basic(Paint::Pattern { pattern: "Rules".into(), xf: Affine::IDENTITY }, Paint::None, 0.0); + let mut art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, extent, extent)), fill()); + art.transform(Affine::scale(0.2), vectorcraft_doc::Scaling { strokes, patterns: true, ..Default::default() }); + doc.symbols.push(Symbol { name: "Scaled".into(), art: Arc::new(art), dynamic: false }); + let layer = doc.layers[0].id; + let one = instance(&mut doc, "Scaled", Affine::translate((20.0, 20.0))); + doc.insert(Some(layer), usize::MAX, one).unwrap(); + let shared = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(125.0, 5.0, 225.0, 105.0)), fill()); + doc.insert(Some(layer), usize::MAX, shared).unwrap(); + doc +} + +#[test] +fn scaled_pattern_symbol_keeps_native_pattern_resources_in_editing_data() { + let small = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0); + let large = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 200.0); + let (a, b) = (program(&small), program(&large)); + eprintln!("pattern symbol editing bytes: {} -> {} for four times the tile area", a.len(), b.len()); + let back = read_back(&small); + let art = &back.symbols.iter().find(|s| s.name == "Scaled").unwrap().art; + assert!(vectorcraft_doc::pattern::uses_pattern(art, Some("Rules")), "the symbol must retain pattern paint rather than one object per tile"); + assert_eq!(a.matches("%AI3_BeginPattern: (Rules)").count(), 1); + assert!(b.len() < a.len() * 2, "editing data must not grow with every covered tile: {} -> {}", a.len(), b.len()); + let tile = back.pattern("Rules").unwrap(); + assert_eq!(tile.tile, small.patterns[0].tile); + assert_eq!(tile.art[0].geometric_bounds().unwrap().width(), 8.0); + let strokes: Vec<_> = + tile.art[0].appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(stroke) = i { Some(stroke.width) } else { None }).collect(); + assert_eq!(strokes, [2.0], "the shared tile keeps its original stroke"); +} + +// Four editing-stream round trips and native raster probes cover the flag and fallback cases. +#[test] +fn scaled_pattern_symbol_new_instances_match_native_tile_stroke_weight() { + for strokes in [true, false] { + for tile_type in [vectorcraft_doc::TileType::Grid, vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }] { + let doc = ruled_pattern_symbol(strokes, tile_type, 100.0); + // Native rendering scales a 2pt pattern stroke to 0.4pt with its pattern affine, + // under either flag. The flag controls the selected object's own stroke separately. + let native = vectorcraft_testkit::raster::render_region(&doc, Rect::new(20.0, 20.0, 22.0, 22.0), 20.0); + let native_weight = (0..native.height).filter(|y| native.pixel(20, *y)[0] < 64).count(); + assert!((6..=10).contains(&native_weight), "native weight={native_weight}, strokes={strokes}, {tile_type:?}"); + let mut back = read_back(&doc); + // Place afresh from the editing stream's symbol definition, rather than measuring + // the already-expanded canvas instance or the file's native payload. + back.layers.clear(); + let layer = back.add_layer(Some("New instance")); + let one = instance(&mut back, "Scaled", Affine::translate((20.0, 20.0))); + back.insert(Some(layer), usize::MAX, one).unwrap(); + let placed = vectorcraft_testkit::raster::render_region(&back, Rect::new(20.0, 20.0, 22.0, 22.0), 20.0); + let weight = (0..placed.height).filter(|y| placed.pixel(20, *y)[0] < 64).count(); + assert!((6..=10).contains(&weight), "editing symbol weight={weight}, native={native_weight}, strokes={strokes}, {tile_type:?}"); + } + } +} + +// Each case goes through the real editing stream and renderer: the mask stroke has to be +// transformed as geometry even when writing its dictionary temporarily clears the tile clip. +#[test] +fn pattern_tile_fallback_preserves_affine_mask_stroke_weight() { + for matrix in + [Affine::scale(0.2), Affine::scale_non_uniform(0.2, 0.4), Affine::new([0.2, 0.0, 0.1, 0.2, 0.0, 0.0]), Affine::scale_non_uniform(-0.2, 0.2)] + { + let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, 100.0); + let white_line = + Node::path(doc.alloc_id(), shapes::line((1.0, 5.0).into(), (9.0, 5.0).into()), Appearance::basic(Paint::None, solid(Color::WHITE), 2.0)); + let mut tile = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::BLACK); + tile.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(white_line), clip: true, invert: false, disabled: false, linked: true })); + doc.patterns[0].art = vec![Arc::new(tile)]; + Arc::make_mut(&mut doc.symbols[0].art) + .transform(matrix * Affine::scale(5.0), vectorcraft_doc::Scaling { patterns: true, ..Default::default() }); + // This fallback bakes the unsupported brick phase. Place on whole super-tile periods + // so the probe isolates stroke geometry, rather than that existing placement limitation. + doc.layers.clear(); + let native_layer = doc.add_layer(Some("Native instance")); + let native_one = instance(&mut doc, "Scaled", Affine::translate((60.0, 40.0))); + doc.insert(Some(native_layer), usize::MAX, native_one).unwrap(); + let bounds = doc.symbols[0].art.geometric_bounds().unwrap() + vectorcraft_geom::Vec2::new(60.0, 40.0); + let period_y = 10.0 * matrix.as_coeffs()[3].abs(); + let region = Rect::new(bounds.x0, bounds.y0, bounds.x0 + 2.0, bounds.y0 + period_y); + let native = vectorcraft_testkit::raster::render_region(&doc, region, 20.0); + // Brick rows shift the line horizontally; select a visible native column and compare + // that same column after the editing-stream round trip. + let (column, native_weight) = (0..native.width) + .map(|x| (x, (0..native.height).filter(|y| native.pixel(x, *y)[0] < 64).count())) + .max_by_key(|(_, weight)| *weight) + .unwrap(); + assert!(native_weight > 0 && native_weight < native.height as usize, "native mask stroke: {matrix:?}, {native_weight}"); + let mut back = read_back(&doc); + back.layers.clear(); + let layer = back.add_layer(Some("New instance")); + let one = instance(&mut back, "Scaled", Affine::translate((60.0, 40.0))); + back.insert(Some(layer), usize::MAX, one).unwrap(); + let placed = vectorcraft_testkit::raster::render_region(&back, region, 20.0); + let weight = (0..placed.height).filter(|y| placed.pixel(column, *y)[0] < 64).count(); + assert!(weight.abs_diff(native_weight) <= 2, "mask stroke {matrix:?}: editing={weight}, native={native_weight}"); + } +} + +#[test] +fn pattern_definition_dictionary_is_scoped_away_from_its_symbol() { + let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0); + // Definitions can hold freshly generated id-less art. Its dictionary must not consume the + // surrounding symbol's root entries just because these independent art scopes share id 0. + Arc::make_mut(&mut doc.patterns[0].art[0]).id = vectorcraft_doc::NodeId(0); + let art = (*doc.symbols[0].art).clone(); + let other = square(&mut doc, Rect::new(25.0, 0.0, 30.0, 5.0), Color::BLACK); + let mut root = group(&mut doc, vec![art, other], false); + root.id = vectorcraft_doc::NodeId(0); + doc.symbols[0].art = Arc::new(root); + let back = read_back(&doc); + let symbol = back.symbols.iter().find(|s| s.name == "Scaled").expect("pattern art must not steal its symbol's declaration"); + let mut uses = false; + vectorcraft_doc::swatches::walk_with_masks(&symbol.art, &mut |n| uses |= vectorcraft_doc::pattern::uses_pattern(n, Some("Rules"))); + assert!(uses); +} + +#[test] +fn symbol_pattern_matrices_stay_readable_or_use_the_bounded_fallback() { + for scale in [0.00001, 0.0, 1e-9] { + let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0); + let art = Arc::make_mut(&mut doc.symbols[0].art); + for item in art.appearance.items.iter_mut() { + if let Paint::Pattern { xf, .. } = item.paint_mut() { + *xf = Affine::scale(scale); + } + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + let back = read_back(&doc); + let symbol = back.symbols.iter().find(|s| s.name == "Scaled").expect("a bad paint matrix must not discard its symbol"); + let mut paints = vec![]; + vectorcraft_doc::swatches::walk_with_masks(&symbol.art, &mut |n| { + for item in &n.appearance.items { + if let Paint::Pattern { xf, .. } = item.paint() { + paints.push(*xf); + } + } + }); + if scale == 0.00001 { + assert_eq!(paints, [Affine::scale(scale)], "a small invertible affine must survive serialization"); + } else { + assert!(paints.is_empty() && out.warnings.iter().any(|w| w == writer::PATTERN_PLACEMENT), "{:?}", out.warnings); + } + } +} + /// A symbol whose art paints with a pattern only through a brushed stroke, whose brush's art is -/// filled with a pattern: the definition holds the tiles, and its instance is written as its art. +/// filled with a pattern: the definition keeps that resource, and its instance is written as art. #[test] fn symbols_painting_patterns_through_brush_art_are_placed_as_art() { let mut doc = Document::new(200.0, 100.0); @@ -6786,9 +6947,13 @@ fn symbols_painting_patterns_through_brush_art_are_placed_as_art() { doc.insert(Some(layer), usize::MAX, one).unwrap(); let out = export_ai_editing(&doc, &opts()).unwrap(); assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings); let back = read_back(&doc); assert_eq!(back.symbols.iter().map(|s| s.name.as_str()).collect::>(), ["Brushed"]); assert_eq!(instances(&back.layers[0]), 0, "the instance is its art"); + let mut pattern = false; + vectorcraft_doc::swatches::walk_with_masks(&back.symbols[0].art, &mut |n| pattern |= vectorcraft_doc::pattern::uses_pattern(n, Some("Dots"))); + assert!(pattern, "indirect brush paint retains its pattern resource in the definition"); } /// A symbol first defined from the drawn look of a group with a style, through a member's scatter diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index eee71cf6d2..be6f4ae0d9 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -48,7 +48,7 @@ pub(super) use paints::{ GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name, }; -pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode}; +pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, PATTERN_SPACE_KEY, hex_decode}; #[cfg(test)] pub(super) use symbols::{MISSING_SYMBOL, OVERRIDE_SERIALIZATIONS, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS}; #[cfg(test)] @@ -62,8 +62,10 @@ pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES}; pub(super) const MAX_NEST: u32 = 8; pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type whose text wrap cannot be preserved from the saved objects, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps"; -pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps"; +pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a large canvas's symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps"; pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps"; +pub(super) const PATTERN_PLACEMENT: &str = + "pattern fills and strokes whose placement cannot be read are written gray in the editing data for other apps"; pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps"; pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; @@ -270,10 +272,10 @@ pub(super) struct Writer<'a> { /// ([`Self::symbol_paints_pattern`]). patterned_symbols: HashMap, symbol_omissions: HashMap<*const Node, symbols::OmissionFacts>, - /// Pattern tiles were written in the art being written ([`Self::define_symbol`] starts it over + /// Pattern references or tiles were written in the art ([`Self::define_symbol`] starts it over /// for each symbol's art). wrote_pattern: bool, - /// The symbols whose definitions hold pattern tiles: a brushed stroke's brush art or a live + /// The symbols whose definitions write pattern paint: a brushed stroke's brush art or a live /// object's art can paint with a pattern that the symbol's own objects don't name. pattern_written: HashSet, /// Art that draws as it should only where it is was written in the art being written @@ -1034,6 +1036,7 @@ impl<'a> Writer<'a> { mask = None; mask_written = false; } + let symbol_root = self.root_entries.as_ref().is_some_and(|(id, _)| *id == n.id); let entries = match &self.root_entries { Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e), _ => None, @@ -1084,6 +1087,10 @@ impl<'a> Writer<'a> { } mask_written = false; } + // A pattern may first be written by the root's mask, so declare its space afterwards. + if symbol_root && self.in_symbol && self.symbols_live && self.wrote_pattern { + let _ = writeln!(self.body, "%_1 /Int ({PATTERN_SPACE_KEY}) ,"); + } self.body.push_str("%_;\n%_\n"); mask_written } @@ -1483,7 +1490,8 @@ impl<'a> Writer<'a> { let flat = FillLayer { paint: Paint::solid(Color::gray(0.5)), ..f.clone() }; return self.path_object(path, rule, Some(&flat), None, xy); }; - let tiles = def.instances_in(*xf, path.to_bezpath().bounding_box()); + let inverse = xf.inverse(); + let tiles = def.instances_in(Affine::IDENTITY, inverse.transform_rect_bbox(path.to_bezpath().bounding_box())); // More tiles than a fill places come back as none: the shape is filled gray, as a // pattern that isn't found is. if tiles.is_empty() && !def.art.is_empty() { @@ -1497,8 +1505,26 @@ impl<'a> Writer<'a> { } self.wrote_pattern = true; let outer = self.clip.clone(); - let region = self.cut(path, rule); + let mut region = self.cut(path, rule); + region.transform(inverse); self.clip = Some(region); + let shown = std::mem::take(&mut self.shown); + self.shown = shown + .iter() + .map(|p| { + let mut p = p.clone(); + p.apply_affine(inverse); + p + }) + .collect(); + // Outline and clip strokes in pattern space before applying its affine. Moving + // just their centerlines first kept 2pt strokes at 2pt under a 20% pattern scale; + // scaling by one mean factor would still distort nonuniform/sheared patterns. + let spaces = (self.to_art, self.grad_space, self.canvas, self.instance_space); + self.to_art *= *xf; + self.grad_space *= *xf; + self.canvas *= *xf; + self.instance_space *= *xf; self.nest += 1; self.drawn += 1; for t in &tiles { @@ -1511,6 +1537,8 @@ impl<'a> Writer<'a> { self.end_group("U", xy); self.nest -= 1; self.clip = outer; + self.shown = shown; + (self.to_art, self.grad_space, self.canvas, self.instance_space) = spaces; } Paint::None => {} } diff --git a/crates/eps/src/ai_editing/writer/images.rs b/crates/eps/src/ai_editing/writer/images.rs index 408827663f..7731eb0e9e 100644 --- a/crates/eps/src/ai_editing/writer/images.rs +++ b/crates/eps/src/ai_editing/writer/images.rs @@ -430,7 +430,7 @@ impl Writer<'_> { } /// `[a b c d tx ty]`, each number to ten decimals ([`ps::num`] writes four). -fn matrix(m: Affine) -> String { +pub(super) fn matrix(m: Affine) -> String { let n: Vec = m.as_coeffs().iter().map(|v| precise(*v)).collect(); format!("[{}]", n.join(" ")) } diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index b97dd593cb..86c056b3f9 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -366,7 +366,12 @@ impl Writer<'_> { /// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can /// write it)? pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool { - self.direct(&s.paint) && crate::ai_ops::plain_stroke(s) + let [a, b, c, d, ..] = self.to_art.as_coeffs(); + // Operators receive transformed path coordinates, but their width is in art units. + // A non-isometric map needs the stroke's outline transformed too (including in masks, + // whose dictionary temporarily clears the clipping region of a pattern fallback). + let isometry = (a * a + b * b - 1.0).abs() < 1e-9 && (c * c + d * d - 1.0).abs() < 1e-9 && (a * c + b * d).abs() < 1e-9; + isometry && self.direct(&s.paint) && crate::ai_ops::plain_stroke(s) } /// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the @@ -575,10 +580,10 @@ impl Writer<'_> { /// Can pattern `name` be written as a definition and painted with from here: the document has /// it, its tiles make a grid, its art is within its tile and holds something, and it isn't used - /// in another pattern's tile or a symbol's art (the reader keeps no symbol whose art paints with - /// a pattern) or nested more than [`MAX_NEST`] deep? + /// in another pattern's tile or nested more than [`MAX_NEST`] deep? A large canvas's symbol + /// art uses the original document, whose same-name tiles can differ from the reduced page's. pub(super) fn pattern_writable(&self, name: &str) -> bool { - if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol { + if !self.defining.is_empty() || self.nest >= MAX_NEST || (self.in_symbol && !self.symbols_live) { return false; } if self.patterns.find(name).is_some() { @@ -604,7 +609,14 @@ impl Writer<'_> { let doc = self.doc; // The tile's box is an object of the definition ([`Self::take_objects`]). let (before, bound) = (self.charges(), self.bound.len()); - let Some(def) = doc.pattern(name).filter(|_| self.take_objects(1)) else { return false }; + let Some(def) = doc.pattern(name) else { return false }; + // A pattern is a separate global resource, even when first discovered in symbol art. + // Charge its objects outside the symbol-art budget and isolate parent dictionaries. + let in_symbol = std::mem::take(&mut self.in_symbol); + if !self.take_objects(1) { + self.in_symbol = in_symbol; + return false; + } self.defining.push(name.to_string()); // The art is written in the pattern's space, y up, from the state a definition starts in. let saved = ( @@ -616,6 +628,7 @@ impl Writer<'_> { self.block_end, // The tile's masks' objects are written with their art styles, those of no other art. (std::mem::replace(&mut self.styled, self.pattern_styled.get(name).cloned().unwrap_or_default()), self.mask_level.take()), + (in_symbol, self.root_entries.take(), self.instance_entries.take(), self.block_start), ); // `Bg` places a gradient in a pattern's tile as on the canvas, mirrored top to bottom: its // placement is worked out in the tile's space turned y up. @@ -646,6 +659,7 @@ impl Writer<'_> { (self.clip, self.shown), self.block_end, (self.styled, self.mask_level), + (self.in_symbol, self.root_entries, self.instance_entries, self.block_start), ) = saved; let art = std::mem::replace(&mut self.body, art); self.defining.pop(); @@ -678,7 +692,18 @@ impl Writer<'_> { return self.plain_color(Color::gray(0.5), stroke); }; let m = self.to_art * xf * Affine::translate((0.0, h)) * Affine::FLIP_Y; - let _ = writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), ps::matrix(m), if stroke { 'P' } else { 'p' }); + let written = Affine::new(m.as_coeffs().map(|v| (v * 1e10).round() / 1e10)); + // Keep a definition's reference readable after serialization; a singular or rounded-flat + // paint must not make the reader discard the entire symbol that contains it. + if !written.as_coeffs().iter().all(|v| v.is_finite()) || !written.determinant().is_finite() || written.determinant().abs() < 1e-12 { + self.warn(super::PATTERN_PLACEMENT); + return self.plain_color(Color::gray(0.5), stroke); + } + // Indirect pattern paint (for example in brush art) also prevents a live symbol + // instance: the canvas keeps its pattern phase fixed when placing that instance. + self.wrote_pattern = true; + let _ = + writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), super::images::matrix(m), if stroke { 'P' } else { 'p' }); } /// The definitions, in the setup before the palette: the gradients the art uses (`n Bn`, then diff --git a/crates/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs index 3ba1adbb43..e34869571c 100644 --- a/crates/eps/src/ai_editing/writer/symbols.rs +++ b/crates/eps/src/ai_editing/writer/symbols.rs @@ -19,6 +19,9 @@ pub(in crate::ai_editing) const SYMBOL_CHANGES: &str = "the changes of dynamic symbol instances are kept in dictionary entries of their own, which other apps leave out"; pub(crate) const DYNAMIC_KEY: &str = "VectorCraftDynamicSymbol"; pub(crate) const OVERRIDES_KEY: &str = "VectorCraftSymbolOverrides"; +/// Version 1 declares that pattern matrices in this definition use its art coordinates. +/// Foreign definitions without that declaration retain the reader's conservative fallback. +pub(crate) const PATTERN_SPACE_KEY: &str = "VectorCraftSymbolPatternSpace"; const MAX_OVERRIDES_BYTES: usize = 1 << 20; #[cfg(test)] @@ -385,6 +388,9 @@ impl Writer<'_> { if wrap { self.line("u"); self.node(root); + if self.symbols_live && self.wrote_pattern { + let _ = writeln!(entries, "%_1 /Int ({PATTERN_SPACE_KEY}) ,"); + } let _ = write!(self.body, "U\n%_/ArtDictionary :\n{entries}%_;\n%_\n9 () XW\n"); } else { // A group always writes its dictionary ([`Self::dictionary`]), which takes the entries. diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index 4c5b48c04d..67c6a47db2 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -631,8 +631,12 @@ impl<'a> Reader<'a> { let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1; let Some(frame) = sub.frames.pop().filter(|_| measured) else { return }; let mut kids = frame.children; - // Where a symbol's art puts a pattern's tiles isn't known. - let whole = !head.left_out && sub.unread.is_empty() && sub.hidden_unread.is_empty() && !kids.iter().any(|n| paints_pattern(n, 0)); + // Unmarked foreign symbols do not declare the coordinate convention of their patterns. + // Our writer explicitly declares symbol-art space, so those definitions can retain paint. + let whole = !head.left_out + && sub.unread.is_empty() + && sub.hidden_unread.is_empty() + && (head.pattern_space || !kids.iter().any(|n| paints_pattern(n, 0))); if !whole { let boxes = self.doc.symbol_boxes(); let bounds = kids.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds_with(&boxes))); diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index ec14b864d9..68997618cd 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -805,6 +805,12 @@ impl<'a> Reader<'a> { { head.dynamic = true; } + if self.frames.len() == 1 + && let Some(head) = self.symbol.as_mut() + && o.nums(crate::ai_editing::PATTERN_SPACE_KEY).first().copied() == Some(1.0) + { + head.pattern_space = true; + } if let Some(text) = o.text(crate::ai_editing::OVERRIDES_KEY) && let Some(bytes) = crate::ai_editing::hex_decode(&text) && let Ok(list) = serde_json::from_slice::>(&bytes) diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index 27eb8a8576..2e4d19bff7 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -245,6 +245,8 @@ pub(super) struct SymbolHead { /// `AI13PatternRegistrationType` in the dictionary after the art. pub(super) registration: Option, pub(super) dynamic: bool, + /// The writer declares its pattern matrices to be in symbol-art coordinates (version 1). + pub(super) pattern_space: bool, /// Art the reader left out (type, a placed file, non-native art, an image it can't read or /// place, a gradient it can't read): the symbol isn't kept, and its instances come in as the /// page draws them, within the box of the rest. diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 9ecba0c7ca..8b6e383dfe 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -33,9 +33,9 @@ //! The document has a version of its own (`document.version`, [`vectorcraft_doc::FORMAT_VERSION`]), //! which readers do not check. A version 2 document's Twist effects turn clockwise for a positive //! angle. A version 1 document's Twist angles are negated when it opens, unless the file is of -//! [`VERSION`] and its `generator` is VectorCraft 0.21.0 or later, which turned them clockwise -//! already; [`save_with`] writes a version 1 document with them negated back for an older file -//! version ([`vectorcraft_doc::twist`]). +//! [`PLACED_SINCE`] or later and its `generator` is VectorCraft 0.21.0 or later, which turned them +//! clockwise already; [`save_with`] writes a version 1 document with them negated back for a file +//! version older than [`PLACED_SINCE`] ([`vectorcraft_doc::twist`]). #![forbid(unsafe_code)] #![doc(test(attr(forbid(unsafe_code))))] @@ -64,11 +64,16 @@ use craft_gzip::Gz; pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode}; use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json}; pub use craft_vectorcraft_format::{ - BLOB_MAGIC, COMPRESSED_SINCE, EXTENSION, ICC_MIME, INLINE_MAX, LEGACY_EXTENSION, MIN_VERSION, PREVIEW_MAX, VERSION, is_compressed, json_part, - sniff, + BLOB_MAGIC, COMPRESSED_SINCE, EXTENSION, ICC_MIME, INLINE_MAX, LEGACY_EXTENSION, LIVE_STAR_SINCE, MIN_VERSION, PREVIEW_MAX, VERSION, + is_compressed, json_part, sniff, }; use stream::Out; +/// The first version whose files keep placed documents, Color Halftone's Max Radius in pixels and +/// Twist angles as they are. A save for an older version writes placed documents as the art they +/// show, the radius in points and Twist angles negated back, as apps of those versions read them. +pub const PLACED_SINCE: u32 = 4; + /// Most bytes the JSON of a compressed file may unpack to (a guard against decompression bombs, /// as are [`MAX_BLOB`] and [`MAX_BLOBS`]). A compressed save refuses a document past any of them, /// so every file VectorCraft writes reads back. On wasm32 the cap is a quarter of the native @@ -252,7 +257,7 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { // resources. Otherwise resources only exporting adds are never saved. The images and placed // documents in the stored brushes' art count as those in the layers do. let linked = with_brush_art(&mut d, |d| { - if version < VERSION { + if version < PLACED_SINCE { placed_as_groups(d); } else { d.drop_placed_resources(); @@ -268,15 +273,15 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { if version < 3 { d.store_legacy_color_profiles(); } - // Apps before this one's version take Color Halftone's Max Radius in points (#3260), and - // predate 0.21.0, turning Twist the other way. The radii first: their conversion runs only on - // a document of version 3 or later, and the Twist one then marks it version 1. - if version < VERSION { + // Apps before version 4 take Color Halftone's Max Radius in points (#3260), and predate + // 0.21.0, turning Twist the other way. The radii first: their conversion runs only on a + // document of version 3 or later, and the Twist one then marks it version 1. + if version < PLACED_SINCE { d.halftone_radii_to_points(); d.store_legacy_twist_angles(); } // Older apps don't know live stars: they get the outline a star draws as a plain path. - if version < VERSION { + if version < LIVE_STAR_SINCE { d.live_stars_to_paths(); } let v1 = if version == 1 { @@ -309,7 +314,7 @@ pub fn with_brush_art(d: &mut Document, f: impl FnOnce(&mut Document) -> T) - /// Every placed document in `d`'s art, the art of its stored brushes included, replaced by a group /// of the art it shows, with the resources that art uses, as a save for a version older than -/// [`VERSION`] writes it. Without a placed document, the resources only exporting adds are dropped +/// [`PLACED_SINCE`] writes it. Without a placed document, the resources only exporting adds are dropped /// ([`Document::drop_placed_resources`]). pub fn placed_as_groups(d: &mut Document) { with_brush_art(d, |d| { @@ -576,7 +581,7 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize // version): its Twist angles turned the other way. The app that wrote it is read from the JSON // before the data after it is taken; the walk's depth is bounded by the JSON reader's nesting // limit. - let current_file = f.version >= VERSION; + let current_file = f.version >= PLACED_SINCE; f.document.migrate_twist_angles(|| current_file && vectorcraft_doc::twist::written_clockwise(generator(file.json()).as_deref())); // The bytes after the JSON, read in one pass: the images' first, then the profiles'. let entries: Vec<[u64; 2]> = f.images.values().chain(f.profiles.values()).filter_map(|i| i.blob).collect(); @@ -1128,7 +1133,8 @@ mod tests { } } } - assert_eq!(checked, 20); + // Four for each version, and two compressed for each version from 3. + assert_eq!(checked, 4 * (VERSION - MIN_VERSION + 1) + 2 * (VERSION - COMPRESSED_SINCE + 1)); } /// Files are read through the crate's `Contents` with the messages VectorCraft gave before, @@ -1148,7 +1154,10 @@ mod tests { let doc = v["document"].to_string(); let file = |format: &str, version: u32| format!(r#"{{"format":"{format}","version":{version},"document":{doc}}}"#); assert_eq!(message(&file("svg", 4)).as_deref(), Some("not a VectorCraft file: format is `svg`")); - assert_eq!(message(&file("vectorcraft", 9)).as_deref(), Some("file version 9 is newer than this VectorCraft supports (4)")); + assert_eq!( + message(&file("vectorcraft", 9)).as_deref(), + Some(format!("file version 9 is newer than this VectorCraft supports ({VERSION})").as_str()) + ); // A document that does not read is reported first, as before. assert!( message(r#"{"format":"vectorcraft","version":9,"document":7}"#).is_some_and(|m| m.starts_with("not a VectorCraft file: invalid type")) @@ -1188,15 +1197,16 @@ mod tests { let old = load(&save(&d, false)).unwrap(); assert_eq!(old.version, vectorcraft_doc::FORMAT_VERSION); assert!((radius(&old) - 8.0 * ppi / 72.0).abs() < 1e-9, "8 pt at {ppi} ppi: {}", radius(&old)); - // Saved for an older app, in every older version: the radius in points, which opens - // here in pixels again. + // Saved for an older app, in every version before 4: the radius in points, which opens + // here in pixels again. Version 4 and later keep it in pixels. let px = radius(&old); - for version in MIN_VERSION..VERSION { + for version in MIN_VERSION..=VERSION { let bytes = save_with(&old, &SaveOptions { version, ..SaveOptions::default() }).unwrap(); let json = String::from_utf8(unpack::Unpacked::new(&bytes).unwrap().json().to_vec()).unwrap(); let at = json.find("\"maxRadius\":").unwrap() + "\"maxRadius\":".len(); let saved: f64 = json[at..].split([',', '}']).next().unwrap().trim().parse().unwrap(); - assert!((saved - 8.0).abs() < 1e-9, "{ppi} ppi, version {version} holds 8 pt: {saved}"); + let want = if version < 4 { 8.0 } else { px }; + assert!((saved - want).abs() < 1e-9, "{ppi} ppi, version {version} holds {want}: {saved}"); let back = load(&bytes).unwrap(); assert!((radius(&back) - px).abs() < 1e-9, "{ppi} ppi, version {version}: {}", radius(&back)); } @@ -1410,15 +1420,20 @@ mod tests { let again = load(&save(&old, false)).unwrap(); assert_eq!((again.version, angle(&again)), (now, Some(-30.0)), "saved again, it is the current version"); // Saved for an older file version (apps before 0.21.0): version 1 with the angle negated - // back, whatever the generator, and it reopens as it was. - for version in MIN_VERSION..VERSION { + // back, whatever the generator, and it reopens as it was. Version 4 and later keep it. + for version in MIN_VERSION..=VERSION { let bytes = save_with(&d, &SaveOptions { version, ..SaveOptions::default() }).unwrap(); let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(v["document"]["version"], 1, "file version {version}"); - assert!(String::from_utf8_lossy(&bytes).contains(r#""angle":-30.0"#), "file version {version}"); + let (document, saved) = if version < 4 { (1, r#""angle":-30.0"#) } else { (now, r#""angle":30.0"#) }; + assert_eq!(v["document"]["version"], document, "file version {version}"); + assert!(String::from_utf8_lossy(&bytes).contains(saved), "file version {version}"); let back = load(&bytes).unwrap(); assert_eq!((back.version, angle(&back)), (now, Some(30.0)), "file version {version}"); } + // A version 4 file from 0.21.0 or later turned its version 1 document's angles already. + let mut v4: serde_json::Value = serde_json::from_slice(¤t).unwrap(); + (v4["version"], v4["document"]["version"], v4["generator"]) = (4.into(), 1.into(), "VectorCraft 0.25.2".into()); + assert_eq!(angle(&load(&serde_json::to_vec(&v4).unwrap()).unwrap()), Some(30.0)); } #[test] diff --git a/crates/format/tests/it/native_v4.rs b/crates/format/tests/it/native_v4.rs index 0a41b2d9e7..033a116d9d 100644 --- a/crates/format/tests/it/native_v4.rs +++ b/crates/format/tests/it/native_v4.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind}; -use vectorcraft_format::{BLOB_MAGIC, FormatError, INLINE_MAX, SaveOptions, load, load_file, pdf_content, save_with}; +use vectorcraft_format::{BLOB_MAGIC, FormatError, INLINE_MAX, SaveOptions, VERSION, load, load_file, pdf_content, save_with}; use vectorcraft_geom::Affine; /// A document showing image `key` of `len` bytes. @@ -48,7 +48,7 @@ fn small_files_stay_plain_json_and_older_versions_inline() { let small = save_with(&doc_with_image("small", 100), &SaveOptions::default()).unwrap(); assert!(!has_tail(&small)); let v: Value = serde_json::from_slice(&small).unwrap(); - assert_eq!(v["version"], 4); + assert_eq!(v["version"], VERSION); let big = doc_with_image("big", INLINE_MAX + 10); let v3 = save_with(&big, &SaveOptions { version: 3, ..SaveOptions::default() }).unwrap(); assert!(!has_tail(&v3), "version 3 keeps everything in the JSON"); diff --git a/crates/format/tests/prop_format.rs b/crates/format/tests/prop_format.rs index 26d91ccf97..2af73ca3a5 100644 --- a/crates/format/tests/prop_format.rs +++ b/crates/format/tests/prop_format.rs @@ -136,7 +136,7 @@ proptest! { without_live_stars(&mut older); for o in [SaveOptions { compress: true, ..SaveOptions::default() }, SaveOptions { version: 2, ..SaveOptions::default() }, SaveOptions { version: 1, pretty: true, ..SaveOptions::default() }] { let back = load(&save_with(&d, &o).unwrap()).unwrap(); - let want = if o.version < vectorcraft_format::VERSION { &older } else { &want }; + let want = if o.version < vectorcraft_format::LIVE_STAR_SINCE { &older } else { &want }; prop_assert!(json_approx_eq(&doc_json(&back), want, 1e-12), "{:?} differs", o); } } diff --git a/crates/mcp/src/tests/fileio.rs b/crates/mcp/src/tests/fileio.rs index dd116908ef..e3a84a7c77 100644 --- a/crates/mcp/src/tests/fileio.rs +++ b/crates/mcp/src/tests/fileio.rs @@ -82,6 +82,7 @@ fn export_tool_lists_engine_formats_and_options() { "tga", "psd", "cmx", + "pict", "dwg" ]) ); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 28f81ae703..af38ab1bd8 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -400,7 +400,7 @@ pub fn tool_definitions() -> Vec { tool( "export", "Export", - "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, dwg (the DXF drawing as a DWG file, versions 2000 to 2018), emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF and DWG take it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", + "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, dwg (the DXF drawing as a DWG file, versions 2000 to 2018), emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes, pict QuickDraw pictures as .pct), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF and DWG take it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", obj( json!({ "format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::>(), "description": "Default: from the path's extension"}, diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml index c561ffccf0..e2fbd9b4bf 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -3,21 +3,17 @@ name = "vectorcraft-metafile" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+, WMF, QuickDraw PICT and binary CGM import through craft-metafile" +description = "VectorCraft metafiles: EMF, WMF and QuickDraw PICT export and EMF, EMF+, WMF, QuickDraw PICT and binary CGM import through craft-metafile" [lints] workspace = true -[features] -# The binary CGM reader (`import_cgm`). Off until the craft-metafile CGM reader (craft-libs#5410) -# merges and the workspace pins it; without it, `is_cgm` is false and `import_cgm` is refused. -cgm = [] - [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } vectorcraft-effects = { workspace = true } +vectorcraft-pathops = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } craft-metafile = { workspace = true, features = ["write"] } diff --git a/crates/metafile/src/encode.rs b/crates/metafile/src/encode.rs index 708f386958..c589ed50eb 100644 --- a/crates/metafile/src/encode.rs +++ b/crates/metafile/src/encode.rs @@ -1,4 +1,5 @@ -//! Translate VectorCraft's drawing operations to the shared metafile writers. +//! Translate VectorCraft's drawing operations to the shared metafile writers (EMF, WMF) and to +//! the PICT writer. use craft_metafile::{ Cap, Join, write::{self, Dash, Op, Pen}, @@ -9,11 +10,30 @@ use vectorcraft_geom::{FillRule, Rect}; use crate::{Kind, scene}; pub(crate) fn write(ops: Vec, region: Rect, kind: Kind, title: &str, warnings: &mut Vec) -> Result, String> { - let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect(); let invalid = || "the export region is empty".to_string(); + let mut note = |lost: bool, warning: &str| { + if lost && !warnings.iter().any(|w| w == warning) { + warnings.push(warning.to_string()); + } + }; match kind { - Kind::Emf => write::emf(&ops, region, "VectorCraft", title).ok_or_else(invalid), + Kind::Pict => { + let out = crate::pict::write(&ops, region)?; + note(out.translucent_images, "PICT has no transparency: images are written over white"); + note(out.turned_images, "PICT turns images only by quarter turns: other turns and skews are written upright, filling their bounds"); + note(out.coarsened_fills, "fills with more points than one polygon holds are written with their curves flattened more coarsely"); + note(out.split_fills, "fills with more than 8,189 points are written as several polygons, which may fill their holes"); + note(out.thinned_fills, "outlines with more than 8,187 points are written with fewer points"); + note(out.unresolved_fills, "non-zero fills too complex to resolve are written even-odd, which may leave overlaps unfilled"); + note(out.uncut_fills, "fills too complex to cut to the artboard that reach far outside it may be written distorted"); + Ok(out.bytes) + } + Kind::Emf => { + let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect(); + write::emf(&ops, region, "VectorCraft", title).ok_or_else(invalid) + } Kind::Wmf => { + let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect(); let out = write::wmf(&ops, region).ok_or_else(invalid)?; for (lost, warning) in [ (out.translucent_images, "WMF has no transparency: images are written over white"), @@ -21,9 +41,7 @@ pub(crate) fn write(ops: Vec, region: Rect, kind: Kind, title: &str, (out.clips_ignored, "clipping masks are not applied: the art they clip is written whole"), (out.oversized_images, "WMF images with a side over 32,767 pixels were left out"), ] { - if lost && !warnings.iter().any(|w| w == warning) { - warnings.push(warning.to_string()); - } + note(lost, warning); } Ok(out.bytes) } diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index 298d47f5d7..33acb8402a 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -95,12 +95,9 @@ pub(crate) fn import_pict(bytes: &[u8]) -> Result { } /// The longer side of a CGM picture without a metric scale, points (8 inches). -#[cfg(feature = "cgm")] const CGM_SIDE: f64 = 576.0; /// Read the first picture of a binary CGM (ISO/IEC 8632-3) through `craft_metafile`. -/// `craft_metafile::parse_cgm` comes with craft-libs#5410, so this waits on the `cgm` feature. -#[cfg(feature = "cgm")] pub(crate) fn import_cgm(bytes: &[u8]) -> Result { let cgm = craft_metafile::parse_cgm(bytes, CGM_SIDE).map_err(|e| e.to_string())?; let n = cgm.notes; @@ -113,6 +110,11 @@ pub(crate) fn import_cgm(bytes: &[u8]) -> Result { (n.restricted_text, "restricted text was set at its character height without fitting it to its box"), (n.character_spacing, "character spacing was not applied"), (n.text_cut, "text past 16,384 characters in one string was cut"), + (n.fonts_cut, "fonts past the first 256 of the font list were not read: their text uses the default font"), + (n.append_attributes, "appended text that followed a change to the text's look was set as its text began"), + (n.text_alignment, "text with continuous alignment was aligned left or on its baseline"), + (n.marker_types, "markers of types other than dot, plus, asterisk, circle and cross were drawn as plus signs"), + (n.unsupported_char_set, "text in a character set other than ASCII, Latin-1, UTF-8 and UTF-16 was read as Latin-1"), ]; p.warnings.extend(notes.iter().filter(|(on, _)| *on).map(|(_, w)| (*w).to_string())); if n.damaged_elements > 0 { diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index a32c37ff84..433025635a 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -1088,7 +1088,11 @@ fn retracked(t: &TextObject, laid: &vectorcraft_text::TextLayout, dx: &[f64]) -> /// Read an EMF or WMF file. pub(crate) fn import(bytes: &[u8]) -> Result { - let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?; + let wire_kind = craft_metafile::sniff(bytes).ok_or("not an EMF or WMF file")?; + let kind = match wire_kind { + craft_metafile::Kind::Emf => Kind::Emf, + craft_metafile::Kind::Wmf => Kind::Wmf, + }; let pic = craft_metafile::parse(bytes).map_err(|e| match e { craft_metafile::Error::NotMetafile | craft_metafile::Error::NotPict => "not an EMF or WMF file".to_string(), craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()), @@ -1096,10 +1100,6 @@ pub(crate) fn import(bytes: &[u8]) -> Result { })?; let k = unit(bytes); let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k); - let wire_kind = match kind { - Kind::Emf => craft_metafile::Kind::Emf, - Kind::Wmf => craft_metafile::Kind::Wmf, - }; if craft_metafile::ends_early(bytes, wire_kind) { m.warn(ENDS_EARLY); } diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index b602a5edab..24d311ba46 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -1,4 +1,5 @@ -//! Windows metafiles: hand-written EMF and WMF writers and readers. +//! Windows metafiles: hand-written EMF and WMF writers and readers, and a QuickDraw picture (PICT) +//! writer and reader. //! //! [`export`] writes the visible art over one region of a document (an artboard) as a metafile, //! and [`export_regions`] one metafile per region: @@ -13,6 +14,9 @@ //! placeable header that gives the size; WMF has no clipping paths, transparency, dashes on wide //! lines or gradients, so clipped art is written whole, images over white, dashes as separate //! lines and gradients and patterns as one colour (each loss comes back as a warning). +//! - **PICT**: the art WMF gets, as a QuickDraw version 2 picture in device units of up to 16 to a +//! point: fills are polygons cut to the picture's frame, strokes their filled outlines, and images +//! 24-bit pixel maps over white (see `pict`). //! //! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`) //! into a document of one artboard (the picture's frame) and one layer: paths with fills and @@ -33,26 +37,31 @@ mod bytes; mod dib; mod encode; mod import; +mod pict; mod scene; use vectorcraft_doc::Document; use vectorcraft_geom::Rect; -/// A Windows metafile format. +/// A metafile format: the Windows metafiles, and QuickDraw pictures, which [`export`] writes and +/// [`is_pict`] and [`import_pict`] read ([`sniff`] and [`import`] read only the Windows formats). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { /// Enhanced Metafile (32-bit coordinates, Bézier curves, paths and clipping). Emf, /// Windows Metafile with a placeable header (16-bit coordinates, polygons). Wmf, + /// QuickDraw picture, version 2, in a PICT file (16-bit coordinates, polygons). + Pict, } impl Kind { - /// The format id (`emf`, `wmf`). + /// The format id (`emf`, `wmf`, `pict`). pub fn id(self) -> &'static str { match self { Self::Emf => "emf", Self::Wmf => "wmf", + Self::Pict => "pict", } } } @@ -93,11 +102,21 @@ pub fn check_regions(regions: &[Rect]) -> Result<(), String> { Ok(()) } +/// [`check_regions`] for `kind`: a PICT picture's frame is also at most 32,767 points on a side. +pub fn check_regions_for(regions: &[Rect], kind: Kind) -> Result<(), String> { + check_regions(regions)?; + if kind == Kind::Pict { + regions.iter().try_for_each(|r| pict::check_region(r.abs()))?; + } + Ok(()) +} + /// Write the visible art of `doc` over each of `regions` as `kind`, one metafile per region in the /// same order, each as [`export`] writes it over that region. The live effects are applied once -/// for all of them. When any region is empty, nothing is written and the result is an error. +/// for all of them. When any region is empty (or, for PICT, over 32,767 points on a side), +/// nothing is written and the result is an error. pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result, String> { - check_regions(regions)?; + check_regions_for(regions, kind)?; let regions: Vec = regions.iter().map(|r| r.abs()).collect(); if regions.is_empty() { return Ok(Vec::new()); @@ -236,33 +255,17 @@ pub fn import_pict(bytes: &[u8]) -> Result { Ok(p) } -/// Do `bytes` start like a binary CGM: BEGIN METAFILE, then METAFILE VERSION? Always false -/// without the `cgm` feature (craft-libs#5410). +/// Do `bytes` start like a binary CGM: BEGIN METAFILE, then METAFILE VERSION? pub fn is_cgm(bytes: &[u8]) -> bool { - #[cfg(feature = "cgm")] - return craft_metafile::is_cgm(bytes); - #[cfg(not(feature = "cgm"))] - { - let _ = bytes; - false - } + craft_metafile::is_cgm(bytes) } /// Read the first picture of a binary Computer Graphics Metafile (CGM, ISO/IEC 8632-3) into a -/// document whose one artboard is the picture's VDC extent. Without the `cgm` feature -/// (craft-libs#5410), every file is refused. +/// document whose one artboard is the picture's VDC extent. pub fn import_cgm(bytes: &[u8]) -> Result { - #[cfg(feature = "cgm")] - { - let mut p = import::import_cgm(bytes)?; - p.document.limit_depth_noting(&mut p.warnings); - Ok(p) - } - #[cfg(not(feature = "cgm"))] - { - let _ = bytes; - Err("CGM files can't be read in this build".to_string()) - } + let mut p = import::import_cgm(bytes)?; + p.document.limit_depth_noting(&mut p.warnings); + Ok(p) } #[cfg(test)] diff --git a/crates/metafile/src/pict.rs b/crates/metafile/src/pict.rs new file mode 100644 index 0000000000..b01c06c8ca --- /dev/null +++ b/crates/metafile/src/pict.rs @@ -0,0 +1,385 @@ +//! The PICT writer: the art WMF gets, as a QuickDraw version 2 picture written through +//! [`craft_metafile::write::PictWriter`], which writes the records. +//! +//! The picture frame is the region in whole points; the drawing is in device units of up to 16 to +//! a point (the header's resolution, at most 1,152 dpi), as many as keep the frame within 16-bit +//! coordinates. QuickDraw has no curves, Bézier paths or pens with joins, so: +//! +//! - fills are polygons (`PaintPoly`) in the fill's color, filled even-odd as QuickDraw fills +//! polygons: a path of several figures is one polygon that runs back along the line between its +//! figures, and a non-zero fill is first resolved into figures that do not overlap. Art is cut +//! to the frame first, which keeps every coordinate within 16 bits. +//! - strokes are their outlines (dashes cut first), filled the same way. +//! - images are `DirectBitsRect` records of 24-bit pixels in tiles of at most 1,024 pixels on a +//! side, packed by rows with PackBits; transparency is composited over white, and images that +//! are turned or skewed by other than a quarter turn are written upright, filling their bounds. + +use std::sync::Arc; + +use craft_metafile::write::{Image, PICT_MAX_POLY_POINTS as MAX_POLY_POINTS, PictWriter}; +use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape}; +use vectorcraft_color::Paint; +use vectorcraft_doc::StrokeLayer; +use vectorcraft_geom::{FillRule, PathData}; + +use crate::scene::{Op, Pen}; + +/// The largest 16-bit coordinate. +const MAX_I16: f64 = 32767.0; +/// Most device units a point (16, 1,152 dpi). +const MAX_SCALE: f64 = 16.0; +/// Curves are flattened to within this many device units. +const FLATNESS: f64 = 0.25; +/// Times the flatness is raised (four-fold each time) for a fill with too many points before it +/// is split into several polygons. +const COARSER: u32 = 3; +/// Most pixels along a side of one image record. +const TILE: usize = 1024; +/// Opacity at or above this is written as opaque. +const OPAQUE: f32 = 0.998; + +/// A written picture and what it could not hold. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Pict { + pub bytes: Vec, + /// Images with transparency were written over white. + pub translucent_images: bool, + /// Turned or skewed images were written upright, filling their bounds. + pub turned_images: bool, + /// A fill with more points than one polygon holds was written with its curves flattened more coarsely. + pub coarsened_fills: bool, + /// A fill with more points than one polygon holds was written as several polygons, so its + /// holes may be filled. + pub split_fills: bool, + /// A figure with more points than one polygon holds was written with fewer. + pub thinned_fills: bool, + /// A non-zero fill too complex to resolve into figures that don't overlap was written even-odd. + pub unresolved_fills: bool, + /// A fill too complex to cut to the frame was written with its points past 16 bits moved in. + pub uncut_fills: bool, +} + +/// The device units a point for a picture `w` × `h` points: the most, up to [`MAX_SCALE`], that +/// keep its size within 16 bits. +fn units_per_point(w: f64, h: f64) -> f64 { + let side = w.max(h); + if side > 0.0 { (MAX_I16 / side).floor().clamp(1.0, MAX_SCALE) } else { MAX_SCALE } +} + +/// The error for a region the picture frame can't hold: a side over 32,767 points. +pub(crate) fn check_region(region: Rect) -> Result<(), String> { + if region.width().round() > MAX_I16 || region.height().round() > MAX_I16 { + return Err("PICT pictures are at most 32,767 points on a side".into()); + } + Ok(()) +} + +/// `v` rounded into 16 bits. +fn i16_of(v: f64) -> i16 { + v.round().clamp(-MAX_I16, MAX_I16) as i16 +} + +/// Whether every point of `fig` lies on one line, so that it encloses no area. +fn collinear(fig: &[[i16; 2]]) -> bool { + let Some(&[x0, y0]) = fig.first() else { return true }; + let (x0, y0) = (i64::from(x0), i64::from(y0)); + let Some(&[x1, y1]) = fig.iter().find(|p| **p != fig[0]) else { return true }; + let (dx, dy) = (i64::from(x1) - x0, i64::from(y1) - y0); + fig.iter().all(|&[x, y]| dx * (i64::from(y) - y0) == dy * (i64::from(x) - x0)) +} + +struct Writer { + pic: PictWriter, + /// Document space to device units. + to_dev: Affine, + /// Device units a point. + k: f64, + /// The frame in document space, a little larger: art is cut to it. + cut: Rect, + /// The frame in device units. + frame: Rect, + lost: Pict, +} + +/// Write `ops` (no clips: [`crate::scene::Scene`] gives none for this format) as a PICT file of +/// `region` (corners in order, finite, with an area). The picture frame is the region's size in +/// whole points, and the device frame is that times the device units a point, so a reader maps +/// one onto the other without scaling the drawing. A region [`check_region`] refuses is refused. +pub(crate) fn write(ops: &[Op], region: Rect) -> Result { + check_region(region)?; + let size = |v: f64| (v.round()).clamp(1.0, MAX_I16) as i16; + let (w, h) = (size(region.width()), size(region.height())); + let k = units_per_point(f64::from(w), f64::from(h)); + let units = k as i16; + let pic = PictWriter::new(w, h, units).ok_or("PICT pictures are at most 32,767 points on a side")?; + let mut wr = Writer { + pic, + to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()), + k, + cut: Rect::from_origin_size(region.origin(), (f64::from(w), f64::from(h))).inflate(1.0, 1.0), + frame: Rect::new(0.0, 0.0, f64::from(w) * k, f64::from(h) * k), + lost: Pict::default(), + }; + for op in ops { + match op { + Op::Fill { path, rule, rgb, .. } => wr.fill(path, *rule, *rgb), + Op::Stroke { path, pen } => wr.stroke(path, pen), + Op::Image { image, xf, opacity } => wr.image(image, *xf, *opacity), + Op::Clip { .. } | Op::Unclip => {} + } + } + Ok(Pict { bytes: wr.pic.finish(), ..wr.lost }) +} + +impl Writer { + /// `path` filled by `rule`, as polygons QuickDraw fills even-odd: cut to the frame (which also + /// resolves a non-zero fill into figures that don't overlap) unless it is an even-odd fill + /// inside the frame already. + fn fill(&mut self, path: &BezPath, rule: FillRule, rgb: [u8; 3]) { + let b = path.bounding_box(); + let c = self.cut; + if ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) || b.x0 >= c.x1 || c.x0 >= b.x1 || b.y0 >= c.y1 || c.y0 >= b.y1 { + return; + } + let inside = self.cut.contains(b.origin()) && self.cut.contains(Point::new(b.x1, b.y1)); + let clean = if rule == FillRule::EvenOdd && inside { + path.clone() + } else { + let cut = PathData::from_bezpath(&self.cut.to_path(0.1)); + match vectorcraft_pathops::try_boolean( + &PathData::from_bezpath(path), + rule, + &cut, + FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + vectorcraft_pathops::DEFAULT_PRECISION, + ) { + Ok(p) => p.to_bezpath(), + // Too complex to resolve: written as it is, filled even-odd, its coordinates kept + // within 16 bits. + Err(_) => { + self.lost.unresolved_fills |= rule == FillRule::NonZero; + let d = self.to_dev.transform_rect_bbox(b); + self.lost.uncut_fills |= [d.x0, d.y0, d.x1, d.y1].iter().any(|v| v.abs() > MAX_I16); + path.clone() + } + } + }; + self.polygons(&clean, rgb); + } + + /// A stroke's outline (`vectorcraft_effects::stroke::line_outline`, with its dashes, caps, + /// joins and miter limit), filled non-zero in its color as [`Writer::fill`] fills. A stroke + /// thinner than a device unit is written one unit wide. + fn stroke(&mut self, path: &BezPath, pen: &Pen) { + if !(pen.width.is_finite() && pen.width > 0.0) { + return; + } + let width = pen.width.max(1.0 / self.k); + let mut st = StrokeLayer::new(Paint::None, width); + st.cap = pen.cap; + st.join = pen.join; + st.miter_limit = pen.miter; + st.dash = pen.dash.clone(); + let outline = vectorcraft_effects::stroke::line_outline(path, &st, width, FLATNESS / self.k); + self.fill(&outline, FillRule::NonZero, pen.rgb); + } + + /// The figures of `path` (document space) in device units, flattened to within `flatness` + /// device units, each without repeated points and with three or more. + fn figures(&self, path: &BezPath, flatness: f64) -> Vec> { + let mut figs: Vec> = vec![]; + let mut cur: Vec<[i16; 2]> = vec![]; + let mut done = |cur: &mut Vec<[i16; 2]>| { + if cur.len() > 1 && cur.first() == cur.last() { + cur.pop(); + } + if cur.len() > 2 { + figs.push(std::mem::take(cur)); + } + cur.clear(); + }; + let dev = self.to_dev * path.clone(); + vectorcraft_geom::flatten(dev.iter(), flatness, |el| match el { + PathEl::MoveTo(p) => { + done(&mut cur); + cur.push([i16_of(p.x), i16_of(p.y)]); + } + PathEl::LineTo(p) => { + let q = [i16_of(p.x), i16_of(p.y)]; + if cur.last() != Some(&q) { + cur.push(q); + } + } + PathEl::ClosePath => done(&mut cur), + _ => {} + }); + done(&mut cur); + figs + } + + /// `path` painted as polygons. All its figures go into one polygon, which returns along the + /// lines between them: each such line is crossed twice and changes nothing in an even-odd + /// fill. A path with more points than a polygon holds is flattened more coarsely, and past + /// that split into several polygons. + fn polygons(&mut self, path: &BezPath, rgb: [u8; 3]) { + let count = |figs: &[Vec<[i16; 2]>]| figs.iter().map(|f| f.len() + 2).sum::(); + let mut flatness = FLATNESS; + let mut figs = self.figures(path, flatness); + let mut coarsened = false; + for _ in 0..COARSER { + if count(&figs) <= MAX_POLY_POINTS { + break; + } + flatness *= 4.0; + coarsened = false; + figs = vectorcraft_geom::bez::subpaths(path) + .into_iter() + .flat_map(|(range, _)| { + let subpath = BezPath::from_vec(path.elements()[range].to_vec()); + let coarse = self.figures(&subpath, flatness); + // A small curved figure can collapse to two points, or to points on one line. + // Keep its finer outline rather than lose its area; splitting and thinning + // still bound polygon size. + if coarse.is_empty() || coarse.iter().any(|fig| collinear(fig)) { + self.figures(&subpath, FLATNESS) + } else { + coarsened |= subpath.elements().iter().any(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))); + coarse + } + }) + .collect(); + } + if figs.is_empty() { + return; + } + self.lost.coarsened_fills |= coarsened; + let mut group: Vec<&[[i16; 2]]> = vec![]; + let mut points = 0; + let thinned: Vec> = figs + .iter() + .map(|fig| { + // A figure no polygon holds keeps evenly spaced points, as many as one holds. + let n = fig.len(); + if n + 2 <= MAX_POLY_POINTS { + return fig.clone(); + } + self.lost.thinned_fills = true; + let keep = MAX_POLY_POINTS - 2; + (0..keep).map(|i| fig[i * n / keep]).collect() + }) + .collect(); + for fig in &thinned { + if !group.is_empty() && points + fig.len() + 2 > MAX_POLY_POINTS { + self.lost.split_fills = true; + self.poly(rgb, &group); + group.clear(); + points = 0; + } + points += fig.len() + 2; + group.push(fig); + } + self.poly(rgb, &group); + } + + /// One polygon of `figs` in `rgb`. Each figure is counted above at two points more than + /// [`PictWriter::paint_poly`] adds for it, so every group fits one polygon and is written. + fn poly(&mut self, rgb: [u8; 3], figs: &[&[[i16; 2]]]) { + let _written = self.pic.paint_poly(rgb, figs); + } + + /// An image placed by `xf`, over white. Mirrored and quarter-turned images keep their + /// placement; other turns and skews are written upright, filling their bounds. + fn image(&mut self, img: &Arc, xf: Affine, opacity: f32) { + let (w, h) = (img.width as usize, img.height as usize); + if w == 0 || h == 0 || opacity <= 0.0 || img.rgba.len() < w * h * 4 { + return; + } + let m = self.to_dev * xf; + let [a, b, c, d, e, f] = m.as_coeffs(); + if ![a, b, c, d, e, f].iter().all(|v| v.is_finite()) { + return; + } + let tiny = |v: f64| v.abs() < 1e-9; + // Output pixel (x, y) shows source pixel `src(x, y)`, in an output `ow` × `oh`. + let swapped = tiny(a) && tiny(d) && !tiny(b) && !tiny(c); + let upright = tiny(b) && tiny(c) && !tiny(a) && !tiny(d); + if !(upright || swapped) { + self.lost.turned_images = true; + } + let (ow, oh) = if swapped { (h, w) } else { (w, h) }; + let (flip_x, flip_y) = if swapped { (c < 0.0, b < 0.0) } else { (upright && a < 0.0, upright && d < 0.0) }; + let src = |x: usize, y: usize| { + let (x, y) = (if flip_x { ow - 1 - x } else { x }, if flip_y { oh - 1 - y } else { y }); + if swapped { (y, x) } else { (x, y) } + }; + let dst = m.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); + // The device edges of output columns and rows, and the ones that reach into the frame. + let edge = |from: f64, to: f64, n: usize, i: usize| from + (to - from) * i as f64 / n as f64; + let span = |from: f64, to: f64, n: usize, lo: f64, hi: f64| { + let first = (0..n).find(|&i| edge(from, to, n, i + 1) > lo); + let last = (0..n).rev().find(|&i| edge(from, to, n, i) < hi); + match (first, last) { + (Some(f), Some(l)) if f <= l => Some((f, l + 1)), + _ => None, + } + }; + let (Some((x0, x1)), Some((y0, y1))) = + (span(dst.x0, dst.x1, ow, self.frame.x0, self.frame.x1), span(dst.y0, dst.y1, oh, self.frame.y0, self.frame.y1)) + else { + return; + }; + let alpha = opacity.clamp(0.0, 1.0); + let mut translucent = false; + let mut pixel = |x: usize, y: usize| { + let (sx, sy) = src(x, y); + let i = (sy * w + sx) * 4; + let p = &img.rgba[i..i + 4]; + let a = f32::from(p[3]) / 255.0 * alpha; + if a < OPAQUE { + translucent = true; + } + [0, 1, 2].map(|c| (f32::from(p[c]) * a + 255.0 * (1.0 - a)).round() as u8) + }; + // Tiles of up to `TILE` columns (rows). The edges between the visible columns lie in the + // frame; an outer edge past 16 bits is moved in, so its column (row) is a tile of its own, + // one color however far it is stretched. + let tiles = |from: f64, to: f64, n: usize, first: usize, end: usize| { + let far = |i: usize| edge(from, to, n, i).abs() > MAX_I16; + let mut cuts = vec![]; + let (mut i, mut stop) = (first, end); + if far(i) && i + 1 < stop { + cuts.push((i, i + 1)); + i += 1; + } + let last = (far(stop) && i + 1 < stop).then(|| { + stop -= 1; + (stop, stop + 1) + }); + while i < stop { + let next = (i + TILE).min(stop); + cuts.push((i, next)); + i = next; + } + cuts.extend(last); + cuts + }; + for (ty, ty1) in tiles(dst.y0, dst.y1, oh, y0, y1) { + for (tx, tx1) in tiles(dst.x0, dst.x1, ow, x0, x1) { + let rect = [ + i16_of(edge(dst.x0, dst.x1, ow, tx)), + i16_of(edge(dst.y0, dst.y1, oh, ty)), + i16_of(edge(dst.x0, dst.x1, ow, tx1)), + i16_of(edge(dst.y0, dst.y1, oh, ty1)), + ]; + if rect[2] > rect[0] && rect[3] > rect[1] { + let pixels: Vec<[u8; 3]> = (ty..ty1).flat_map(|y| (tx..tx1).map(move |x| (x, y))).map(|(x, y)| pixel(x, y)).collect(); + // Tiles are at most `TILE` pixels a side and `rect` has an area, so the + // pixel map is written. + let _written = self.pic.direct_bits(tx1 - tx, ty1 - ty, &pixels, rect); + } + } + } + self.lost.translucent_images |= translucent; + } +} diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 8adbd5e9ed..a7e12c9e2f 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -483,6 +483,9 @@ impl<'a> Scene<'a> { } fn stroke(&mut self, bp: &BezPath, rule: FillRule, st: &StrokeLayer, bounds: Rect) { + if st.blend != BlendMode::Normal { + self.warn(BLENDING); + } if st.brush.is_some() && self.nest < MAX_NEST && let Some(art) = self.brush_art(bp, st) @@ -495,9 +498,6 @@ impl<'a> Scene<'a> { self.opacity = opacity; return; } - if st.blend != BlendMode::Normal { - self.warn(BLENDING); - } // A pen paints one colour along the path itself: anything else is the stroke's outline, // filled. let flat_paint = matches!(st.paint, Paint::Solid { .. }) || !self.clips; diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 420edeb077..3ddcc5a014 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -11,11 +11,10 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes}; use crate::*; -// The CGM reader waits on craft-libs#5410 (the `cgm` feature). -#[cfg(feature = "cgm")] mod cgm; mod import; mod pict; +mod pict_export; /// Add `n` (with a fresh id) on top of `d`'s first layer. pub(crate) fn add(d: &mut Document, mut n: Node) { diff --git a/crates/metafile/src/tests/cgm.rs b/crates/metafile/src/tests/cgm.rs index a9cbca18fc..2155d4382e 100644 --- a/crates/metafile/src/tests/cgm.rs +++ b/crates/metafile/src/tests/cgm.rs @@ -313,6 +313,17 @@ fn what_the_reader_left_out_or_set_differently_is_warned_about() { assert!(p.warnings.iter().any(|w| w == "character spacing was not applied"), "{:?}", p.warnings); assert!(p.warnings.iter().any(|w| w == "2 drawing elements cut short or describing no shape were left out"), "{:?}", p.warnings); assert_eq!(paths(&p.document).len(), 1); + + // Continuous horizontal alignment before a text, and a marker type past cross before a marker. + let bytes = cgm( + &[], + &[extent()], + &[el(5, 18, &be(&[4, 0, 0, 0, 0, 0])), el(4, 4, &[be(&[100, 100, 1]), s("x")].concat()), el(5, 6, &be(&[6])), el(4, 3, &be(&[100, 100]))], + ); + let p = import_cgm(&bytes).unwrap(); + assert!(p.warnings.iter().any(|w| w == "text with continuous alignment was aligned left or on its baseline"), "{:?}", p.warnings); + let markers = "markers of types other than dot, plus, asterisk, circle and cross were drawn as plus signs"; + assert!(p.warnings.iter().any(|w| w == markers), "{:?}", p.warnings); } #[test] diff --git a/crates/metafile/src/tests/pict_export.rs b/crates/metafile/src/tests/pict_export.rs new file mode 100644 index 0000000000..4fcce19e7f --- /dev/null +++ b/crates/metafile/src/tests/pict_export.rs @@ -0,0 +1,496 @@ +//! PICT output read back through `craft_metafile`'s QuickDraw reader: the frame and resolution, +//! fills and their fill rules, strokes, images and their placement, and what the format leaves +//! out. + +use craft_metafile::{Item, Seg}; +use vectorcraft_geom::{BezPath, FillRule, Shape}; + +use super::*; + +fn pict(d: &Document) -> Output { + export(d, d.artboards[0].rect, Kind::Pict).unwrap() +} + +fn read(out: &Output) -> craft_metafile::Picture { + let pic = craft_metafile::parse_pict(&out.bytes).unwrap(); + assert!(!pic.truncated && pic.skipped_records == 0 && pic.dropped_images == 0, "{pic:?}"); + pic +} + +fn bez(segs: &[Seg]) -> BezPath { + let mut bp = BezPath::new(); + for s in segs { + match *s { + Seg::Move(x, y) => bp.move_to((f64::from(x), f64::from(y))), + Seg::Line(x, y) => bp.line_to((f64::from(x), f64::from(y))), + Seg::Cubic(a, b, c, d, e, f) => bp.curve_to((f64::from(a), f64::from(b)), (f64::from(c), f64::from(d)), (f64::from(e), f64::from(f))), + Seg::Close => bp.close_path(), + } + } + bp +} + +/// The filled paths of `pic`: their outline and their color. +fn fills(pic: &craft_metafile::Picture) -> Vec<(BezPath, [u8; 4])> { + pic.items + .iter() + .filter_map(|i| match i { + Item::Path { segs, fill: Some(c), stroke: None, .. } => Some((bez(segs), *c)), + _ => None, + }) + .collect() +} + +/// Is `p` painted by one of `pic`'s fills, each filled even-odd as QuickDraw fills polygons? +fn painted(pic: &craft_metafile::Picture, p: (f64, f64)) -> bool { + fills(pic).iter().any(|(bp, _)| bp.winding(p.into()) % 2 != 0) +} + +fn near(a: Rect, b: Rect, tol: f64) -> bool { + [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() <= tol) +} + +fn compound(parts: &[BezPath], rule: FillRule) -> Node { + let mut bp = BezPath::new(); + parts.iter().for_each(|p| bp.extend(p.iter())); + let mut n = path(PathData::from_bezpath(&bp), red(), Paint::None, 0.0); + if let NodeKind::Path { rule: r, .. } = &mut n.kind { + *r = rule; + } + n +} + +fn square(x0: f64, y0: f64, x1: f64, y1: f64, clockwise: bool) -> BezPath { + let mut pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]; + if !clockwise { + pts.reverse(); + } + let mut bp = BezPath::new(); + bp.move_to(pts[0]); + pts[1..].iter().for_each(|p| bp.line_to(*p)); + bp.close_path(); + bp +} + +/// Walk the writer's version 2 opcodes and collect their PaintPoly data. +fn paint_polys(bytes: &[u8]) -> Vec<&[u8]> { + let word = |at: usize| u16::from_be_bytes(bytes[at..at + 2].try_into().unwrap()); + let mut at = 522; // Application data, picSize, and frame. + let mut polys = vec![]; + loop { + at += at % 2; + let opcode = word(at); + at += 2; + let len = match opcode { + 0x0011 => { + assert_eq!(word(at), 0x02FF); + 2 + } + 0x0C00 => 24, + 0x0001 => usize::from(word(at)), + 0x0008 => 2, + 0x0009 => 8, + 0x001A => 6, + 0x0071 => { + let len = usize::from(word(at)); + polys.push(&bytes[at..at + len]); + len + } + 0x009A => { + let row_bytes = usize::from(word(at + 4) & 0x3FFF); + let rows = usize::from(word(at + 10) - word(at + 6)); + let mut end = at + 68; // PixMap, source and destination rectangles, mode. + for _ in 0..rows { + if row_bytes < 8 { + end += row_bytes; + } else if row_bytes > 250 { + end += 2 + usize::from(word(end)); + } else { + end += 1 + usize::from(bytes[end]); + } + } + end - at + } + 0x00FF => { + assert_eq!(at, bytes.len()); + return polys; + } + _ => panic!("unexpected PICT opcode {opcode:#06X}"), + }; + at += len; + } +} + +#[test] +fn pict_frame_is_the_region_in_points_and_art_lands_within_a_sixteenth_of_a_point() { + let r = Rect::new(10.5, 20.25, 100.0, 50.0); + let d = doc_with(612.0, 792.0, vec![path(shapes::rectangle(r), red(), Paint::None, 0.0)]); + let out = pict(&d); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + // 512 bytes of application data, then the frame (top, left, bottom, right) at 72 dpi and the + // version 2 opcodes. + assert_eq!(out.bytes[514..522], [0, 0, 0, 0, 3, 24, 2, 100]); + assert_eq!(out.bytes[522..528], [0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + let pic = read(&out); + assert_eq!((pic.width, pic.height), (612.0, 792.0)); + let f = fills(&pic); + assert_eq!(f.len(), 1, "{f:?}"); + assert_eq!(f[0].1, [255, 0, 0, 255]); + assert!(near(f[0].0.bounding_box(), r, 1.0 / 16.0), "{:?}", f[0].0.bounding_box()); +} + +#[test] +fn pict_fractional_artboards_keep_art_within_a_sixteenth_of_a_point() { + let r = Rect::new(20.25, 10.5, 80.0, 50.0); + let d = doc_with(100.4, 60.7, vec![path(shapes::rectangle(r), red(), Paint::None, 0.0)]); + let pic = read(&pict(&d)); + let artboard = d.artboards[0].rect; + assert_eq!((pic.width, pic.height), (artboard.width().round() as f32, artboard.height().round() as f32)); + let f = fills(&pic); + assert_eq!(f.len(), 1, "{f:?}"); + assert!(near(f[0].0.bounding_box(), r, 1.0 / 16.0), "{:?}", f[0].0.bounding_box()); +} + +#[test] +fn fills_keep_their_holes_and_non_zero_overlaps() { + let even_odd = compound(&[square(10.0, 10.0, 90.0, 90.0, true), square(30.0, 30.0, 70.0, 70.0, true)], FillRule::EvenOdd); + let mut d = doc_with(300.0, 100.0, vec![even_odd]); + // Two overlapping squares drawn the same way round: non-zero fills where they overlap. + add(&mut d, compound(&[square(110.0, 10.0, 150.0, 50.0, true), square(130.0, 30.0, 170.0, 70.0, true)], FillRule::NonZero)); + // A square with a hole drawn the other way round. + add(&mut d, compound(&[square(210.0, 10.0, 290.0, 90.0, true), square(230.0, 30.0, 270.0, 70.0, false)], FillRule::NonZero)); + let pic = read(&pict(&d)); + for (p, filled) in [ + ((20.0, 20.0), true), + ((50.0, 50.0), false), + ((120.0, 20.0), true), + ((140.0, 40.0), true), + ((160.0, 60.0), true), + ((120.0, 60.0), false), + ((220.0, 20.0), true), + ((250.0, 50.0), false), + ] { + assert_eq!(painted(&pic, p), filled, "{p:?}"); + } +} + +#[test] +fn art_off_the_frame_is_cut_to_it() { + // Far enough out that its device coordinates would not fit 16 bits. + let wide = path(shapes::rectangle(Rect::new(-5000.0, 10.0, 5000.0, 20.0)), red(), Paint::None, 0.0); + let away = path(shapes::rectangle(Rect::new(400.0, 10.0, 410.0, 20.0)), blue(), Paint::None, 0.0); + let pic = read(&pict(&doc_with(100.0, 100.0, vec![wide, away]))); + let f = fills(&pic); + assert_eq!(f.len(), 1, "{f:?}"); + let b = f[0].0.bounding_box(); + assert!(b.x0 >= -1.0 && b.x1 <= 101.0 && near(Rect::new(0.0, b.y0, 100.0, b.y1), Rect::new(0.0, 10.0, 100.0, 20.0), 1.0 / 16.0), "{b:?}"); + assert!(painted(&pic, (1.0, 15.0)) && painted(&pic, (99.0, 15.0))); +} + +#[test] +fn strokes_are_written_as_their_outlines() { + let line = |y: f64| { + let mut bp = BezPath::new(); + bp.move_to((10.0, y)); + bp.line_to((50.0, y)); + path(PathData::from_bezpath(&bp), Paint::None, blue(), 4.0) + }; + let butt = line(20.0); + let mut round = line(60.0); + if let Some(s) = round.appearance.stroke_mut() { + s.cap = LineCap::Round; + } + let pic = read(&pict(&doc_with(100.0, 100.0, vec![butt, round]))); + let f = fills(&pic); + assert_eq!(f.len(), 2, "{f:?}"); + assert!(f.iter().all(|(_, c)| *c == [0, 0, 255, 255])); + let tol = 1.0 / 8.0; + assert!(near(f[0].0.bounding_box(), Rect::new(10.0, 18.0, 50.0, 22.0), tol), "{:?}", f[0].0.bounding_box()); + assert!(near(f[1].0.bounding_box(), Rect::new(8.0, 58.0, 52.0, 62.0), tol), "{:?}", f[1].0.bounding_box()); + // A stroke wider than the shape covers its interior. + let dot = path(shapes::ellipse(Rect::new(45.0, 45.0, 55.0, 55.0)), Paint::None, blue(), 40.0); + let pic = read(&pict(&doc_with(100.0, 100.0, vec![dot]))); + assert!(painted(&pic, (50.0, 50.0)) && painted(&pic, (50.0, 32.0)) && !painted(&pic, (50.0, 20.0))); +} + +/// A PNG of `w` × `h` pixels, `rgba` row by row. +fn png_of(w: u32, h: u32, rgba: Vec) -> Vec { + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// A bitmap read back: where it goes (`[x, y, w, h]`), its width and height in pixels, and its +/// RGB pixels. +type Bitmap = ([f32; 4], u32, u32, Vec<[u8; 3]>); + +/// The bitmaps of `pic`. +fn bitmaps(pic: &craft_metafile::Picture) -> Vec { + pic.items + .iter() + .filter_map(|i| match i { + Item::Bitmap { rect, width, height, rgba, .. } => { + Some((*rect, *width, *height, rgba.as_chunks::<4>().0.iter().map(|p| [p[0], p[1], p[2]]).collect())) + } + _ => None, + }) + .collect() +} + +/// Each pixel of a bitmap read back shows the pixel of `src` (`w` × `h`) that `xf` places under +/// its center. +fn shows(bitmap: &Bitmap, src: &[[u8; 3]], w: usize, xf: Affine) { + let (rect, bw, bh, px) = bitmap; + let inv = xf.inverse(); + let (cw, ch) = (f64::from(rect[2]) / f64::from(*bw), f64::from(rect[3]) / f64::from(*bh)); + for y in 0..*bh as usize { + for x in 0..*bw as usize { + let at = Point::new(f64::from(rect[0]) + (x as f64 + 0.5) * cw, f64::from(rect[1]) + (y as f64 + 0.5) * ch); + let s = inv * at; + let want = src[s.y.floor() as usize * w + s.x.floor() as usize]; + assert_eq!(px[y * *bw as usize + x], want, "pixel ({x}, {y}) at {at:?}"); + } + } +} + +#[test] +fn images_keep_their_pixels_mirrored_and_quarter_turned() { + let src: Vec<[u8; 3]> = vec![[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [0, 255, 255], [255, 0, 255]]; + let bytes = png_of(3, 2, src.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect()); + let places = [ + Affine::translate((10.0, 10.0)) * Affine::scale(4.0), + Affine::translate((40.0, 10.0)) * Affine::scale_non_uniform(-4.0, 4.0), + Affine::translate((60.0, 10.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale(4.0), + Affine::translate((70.0, 60.0)) * Affine::rotate(-std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(4.0, -4.0), + ]; + let mut d = doc_with(100.0, 100.0, vec![]); + for xf in places { + let n = image_node(&mut d, bytes.clone(), 3, 2, xf); + add(&mut d, n); + } + let out = pict(&d); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let bm = bitmaps(&read(&out)); + assert_eq!(bm.len(), places.len()); + for (b, xf) in bm.iter().zip(places) { + let want = xf.transform_rect_bbox(Rect::new(0.0, 0.0, 3.0, 2.0)); + let got = Rect::new(f64::from(b.0[0]), f64::from(b.0[1]), f64::from(b.0[0] + b.0[2]), f64::from(b.0[1] + b.0[3])); + assert!(near(got, want, 1.0 / 16.0), "{got:?} {want:?}"); + shows(b, &src, 3, xf); + } +} + +#[test] +fn turned_and_translucent_images_are_reported() { + let mut d = doc_with(100.0, 100.0, vec![]); + // One pixel: a row narrower than two pixels is stored unpacked. + let half = image_node(&mut d, png(1, 1, [0, 0, 0, 128]), 1, 1, Affine::translate((10.0, 10.0)) * Affine::scale(10.0)); + add(&mut d, half); + let out = pict(&d); + assert_eq!(out.warnings, ["PICT has no transparency: images are written over white"]); + let bm = bitmaps(&read(&out)); + assert_eq!(bm.len(), 1); + assert_eq!(bm[0].3, [[127, 127, 127]]); + let turned = image_node(&mut d, png(2, 2, [0, 0, 0, 255]), 2, 2, Affine::translate((50.0, 50.0)) * Affine::rotate(0.5)); + add(&mut d, turned); + assert!(pict(&d).warnings.iter().any(|w| w.contains("quarter turns"))); +} + +#[test] +fn a_brushed_stroke_reports_its_blending_mode() { + let mut bp = BezPath::new(); + bp.move_to((10.0, 50.0)); + bp.line_to((90.0, 50.0)); + let plain = path(PathData::from_bezpath(&bp), Paint::None, blue(), 3.0); + let mut line = plain.clone(); + if let Some(s) = line.appearance.stroke_mut() { + s.brush = Some("3 pt. Round".into()); + s.blend = vectorcraft_color::BlendMode::Multiply; + } + let out = pict(&doc_with(100.0, 100.0, vec![line])); + assert!(!fills(&read(&out)).is_empty(), "the brush's art is written"); + // A brush that doesn't resolve falls back to the stroke's outline. + let mut unresolved = plain; + if let Some(s) = unresolved.appearance.stroke_mut() { + s.brush = Some("missing".into()); + s.blend = vectorcraft_color::BlendMode::Multiply; + } + let fallback = pict(&doc_with(100.0, 100.0, vec![unresolved])); + assert_ne!(out.bytes, fallback.bytes, "the brush resolves, so its art is written rather than the fallback outline"); + assert!(out.warnings.iter().any(|w| w.contains("blending modes are left out")), "{:?}", out.warnings); +} + +#[test] +fn large_images_are_written_in_tiles() { + let (w, h) = (1500usize, 3usize); + // Red changes along each row and green stays the same over long runs: both literal and + // repeated bytes are packed, in rows longer than 250 bytes. + let src: Vec<[u8; 3]> = (0..w * h).map(|i| [(i % w % 256) as u8, (i % w / 256) as u8, (i / w * 60) as u8]).collect(); + let mut d = doc_with(100.0, 100.0, vec![]); + // A pixel a device unit (a sixteenth of a point) wide. + let xf = Affine::translate((5.0, 5.0)) * Affine::scale(0.0625); + let n = image_node(&mut d, png_of(w as u32, h as u32, src.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect()), w as u32, h as u32, xf); + add(&mut d, n); + let bm = bitmaps(&read(&pict(&d))); + assert_eq!(bm.iter().map(|b| (b.1, b.2)).collect::>(), [(1024, 3), (476, 3)]); + for b in &bm { + shows(b, &src, w, xf); + } +} + +#[test] +fn pict_polygon_sizes_fit_a_signed_word() { + // 8,800 figure points, plus closing points and bridges, fit the old unsigned limit. + let squares: Vec = (0..2200) + .map(|i| (f64::from(i % 50) * 1.5 + 1.0, f64::from(i / 50) * 1.5 + 1.0)) + .map(|(x, y)| square(x, y, x + 1.0, y + 1.0, true)) + .collect(); + let out = pict(&doc_with(100.0, 100.0, vec![compound(&squares, FillRule::EvenOdd)])); + let polys = paint_polys(&out.bytes); + assert!(!polys.is_empty()); + for poly in polys { + let size = i16::from_be_bytes(poly[..2].try_into().unwrap()); + assert!(size > 0, "polySize must be a positive signed byte count: {size}"); + let (points, remainder) = poly[10..].as_chunks::<4>(); + assert!(remainder.is_empty()); + assert!(!points.is_empty()); + assert_eq!(size as usize, 10 + 4 * points.len()); + } +} + +#[test] +fn pict_warns_when_curved_fills_fit_only_after_coarsening() { + // At the finest flatness the circles hold more points than one polygon; coarser, they fit. + let circles: Vec = (0..900) + .map(|i| { + let center = (f64::from(i % 30) * 4.5 + 5.0, f64::from(i / 30) * 4.5 + 5.0); + vectorcraft_geom::kurbo::Circle::new(center, 2.0).to_path(0.01) + }) + .collect(); + let small = pict(&doc_with(140.0, 140.0, vec![compound(&circles[..1], FillRule::EvenOdd)])); + assert!(small.warnings.is_empty(), "{:?}", small.warnings); + let out = pict(&doc_with(140.0, 140.0, vec![compound(&circles, FillRule::EvenOdd)])); + assert!(out.warnings.iter().any(|w| w.contains("curves flattened more coarsely")), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w.contains("several polygons")), "{:?}", out.warnings); + assert_eq!(paint_polys(&out.bytes).len(), 1); + let pic = read(&out); + assert!(painted(&pic, (5.0, 5.0)) && painted(&pic, (135.5, 135.5))); +} + +#[test] +fn pict_coarse_flattening_keeps_small_curved_figures() { + // Even four points per lens, plus closing points and bridges, exceed one polygon. + // At the coarsest flatness both curves become lines between the same two endpoints. + let lenses: Vec = (0..2200) + .map(|i| { + let (x, y) = (f64::from(i % 50) * 1.5 + 1.0, f64::from(i / 50) * 1.5 + 1.0); + let mut bp = BezPath::new(); + bp.move_to((x, y)); + bp.quad_to((x + 0.5, y - 0.5), (x + 1.0, y)); + bp.quad_to((x + 0.5, y + 0.5), (x, y)); + bp.close_path(); + bp + }) + .collect(); + let out = pict(&doc_with(100.0, 100.0, vec![compound(&lenses, FillRule::EvenOdd)])); + let pic = read(&out); + for i in [0, lenses.len() / 2, lenses.len() - 1] { + let p = lenses[i].bounding_box().center(); + assert!(painted(&pic, (p.x, p.y)), "lens {i} was lost"); + } + assert!(fills(&pic).len() > 1); + assert!(out.warnings.iter().any(|w| w.contains("several polygons")), "{:?}", out.warnings); +} + +#[test] +fn pict_coarse_flattening_keeps_figures_that_become_one_line() { + // At the coarsest flatness the curve becomes a line, and its three points lie on one line. + let bumps: Vec = (0..2200) + .map(|i| { + let (x, y) = (f64::from(i % 50) * 1.5 + 1.0, f64::from(i / 50) * 1.5 + 1.0); + let mut bp = BezPath::new(); + bp.move_to((x, y)); + bp.quad_to((x + 0.5, y - 0.5), (x + 1.0, y)); + bp.line_to((x + 0.5, y)); + bp.close_path(); + bp + }) + .collect(); + let out = pict(&doc_with(100.0, 100.0, vec![compound(&bumps, FillRule::EvenOdd)])); + let pic = read(&out); + for i in [0_u32, 1100, 2199] { + let (x, y) = (f64::from(i % 50) * 1.5 + 1.0, f64::from(i / 50) * 1.5 + 1.0); + assert!(painted(&pic, (x + 0.5, y - 0.1)), "bump {i} was lost"); + } +} + +#[test] +fn a_fill_past_one_polygon_is_split_or_thinned() { + // 3,000 separate squares: more points than one polygon holds. + let squares: Vec = (0..3000) + .map(|i| (f64::from(i % 60) * 1.5 + 1.0, f64::from(i / 60) * 1.5 + 1.0)) + .map(|(x, y)| square(x, y, x + 1.0, y + 1.0, true)) + .collect(); + let out = pict(&doc_with(100.0, 100.0, vec![compound(&squares, FillRule::EvenOdd)])); + assert!(out.warnings.iter().any(|w| w.contains("several polygons")), "{:?}", out.warnings); + let pic = read(&out); + assert!(fills(&pic).len() > 1); + assert!(painted(&pic, (1.5, 1.5)) && painted(&pic, (59.0 * 1.5 + 1.5, 49.0 * 1.5 + 1.5))); + // One outline of 20,000 points. + let mut star = BezPath::new(); + for i in 0..20_000 { + let t = f64::from(i) / 20_000.0 * std::f64::consts::TAU; + let r = if i % 2 == 0 { 45.0 } else { 40.0 }; + let p = (50.0 + r * t.cos(), 50.0 + r * t.sin()); + if i == 0 { star.move_to(p) } else { star.line_to(p) } + } + star.close_path(); + let out = pict(&doc_with(100.0, 100.0, vec![compound(&[star], FillRule::EvenOdd)])); + assert!(out.warnings.iter().any(|w| w.contains("fewer points")), "{:?}", out.warnings); + let pic = read(&out); + assert!(painted(&pic, (50.0, 50.0)) && !painted(&pic, (2.0, 2.0))); +} + +#[test] +fn an_image_reaching_far_past_the_frame_keeps_its_columns_in_place() { + // Two columns, each 2,550 pt wide: red ends at x = 50, well inside the frame, while the outer + // edges lie past 16-bit device coordinates. + let mut d = doc_with(100.0, 100.0, vec![]); + let bytes = png_of(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]); + let n = image_node(&mut d, bytes, 2, 1, Affine::translate((-2500.0, 10.0)) * Affine::scale_non_uniform(2550.0, 10.0)); + add(&mut d, n); + let bm = bitmaps(&read(&pict(&d))); + let color_at = |x: f64| { + bm.iter().find_map(|(r, bw, _, px)| { + let (x0, w) = (f64::from(r[0]), f64::from(r[2])); + (x0..x0 + w).contains(&x).then(|| px[((x - x0) / w * f64::from(*bw)) as usize]) + }) + }; + assert_eq!(color_at(25.0), Some([255, 0, 0]), "{bm:?}"); + assert_eq!(color_at(49.0), Some([255, 0, 0]), "{bm:?}"); + assert_eq!(color_at(51.0), Some([0, 0, 255]), "{bm:?}"); +} + +#[test] +fn a_non_zero_fill_too_complex_to_resolve_is_reported() { + let squares: Vec = (0..1000).map(|_| square(10.0, 10.0, 50.0, 50.0, true)).collect(); + let out = pict(&doc_with(100.0, 100.0, vec![compound(&squares, FillRule::NonZero)])); + assert!(out.warnings.iter().any(|w| w.contains("written even-odd")), "{:?}", out.warnings); + // The same for a stroke whose outline can't be resolved: it is still written, not left out. + let mut lines = BezPath::new(); + for _ in 0..1000 { + lines.move_to((10.0, 50.0)); + lines.line_to((90.0, 50.0)); + } + let out = pict(&doc_with(100.0, 100.0, vec![path(PathData::from_bezpath(&lines), Paint::None, blue(), 4.0)])); + assert!(out.warnings.iter().any(|w| w.contains("written even-odd")), "{:?}", out.warnings); + assert!(!fills(&read(&out)).is_empty()); +} + +#[test] +fn pict_regions_over_32767_points_are_refused() { + let d = doc_with(100.0, 100.0, vec![]); + assert!(export(&d, Rect::new(0.0, 0.0, 40_000.0, 10.0), Kind::Pict).is_err()); + assert!(check_regions_for(&[Rect::new(0.0, 0.0, 40_000.0, 10.0)], Kind::Pict).is_err()); + assert!(check_regions_for(&[Rect::new(0.0, 0.0, 40_000.0, 10.0)], Kind::Emf).is_ok()); + assert!(export(&d, Rect::new(0.0, 0.0, 32_000.0, 10.0), Kind::Pict).is_ok()); +} diff --git a/crates/render/src/brush_fx.rs b/crates/render/src/brush_fx.rs index 1660ae6caa..96db25a357 100644 --- a/crates/render/src/brush_fx.rs +++ b/crates/render/src/brush_fx.rs @@ -61,6 +61,8 @@ pub(crate) struct BrushCache { /// (frame stamp, document address) the library was last validated for. checked: (u64, usize), lib: HashMap>, + /// Whether brush art or an opacity mask there has a visible plug-in effect. + plugins: bool, /// The names and art of the document's patterns and symbols ([`definitions`]) when the library /// was last validated, the art held weakly as the pattern tiles hold theirs. definitions: Vec<(String, Weak)>, @@ -78,6 +80,7 @@ impl Default for BrushCache { key: 0, checked: (0, 0), lib: HashMap::new(), + plugins: false, definitions: Vec::new(), entries: FrameCache::new(lru::BRUSH_BUDGET, 512), #[cfg(test)] @@ -113,6 +116,7 @@ impl BrushCache { for b in vectorcraft_brush::library(doc) { self.lib.entry(b.name.clone()).or_insert_with(|| Arc::new(b)); } + self.plugins = self.lib.values().any(|b| b.art().into_iter().any(crate::holds_plugin_effect)); } /// [`Self::key`] for the brush library `doc` holds (checked once a frame, `stamp`). @@ -121,6 +125,11 @@ impl BrushCache { self.key } + /// Whether brush art has a visible plug-in effect, valid after [`Self::library_key`] for the frame. + pub(crate) fn has_plugins(&self) -> bool { + self.plugins + } + /// [`Self::library_key`] checked now, between frames: `doc` may be the document of the last /// frame, edited in place. pub(crate) fn library_key_now(&mut self, doc: &Document, stamp: u64) -> u64 { diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 49e252d206..0c58cdf1b4 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -1,3 +1,5 @@ +use std::hash::{DefaultHasher, Hash, Hasher}; + use super::options::{AntiAlias, RenderOptions}; use super::threads::single_threaded_context; use super::{ @@ -224,6 +226,8 @@ pub(crate) struct Frame<'a> { /// Size of one of this frame's pixels in document units. pub(crate) px: f64, pub(crate) opts: &'a RenderOptions, + /// The order-independent fingerprint of `opts.hidden`, shared by this frame's raster lookups. + pub(crate) hidden_inputs: u64, /// What colours paint as: screen colours, or one ink plane of a CMYK document (see [`ink`]). pub(crate) ink: Ink, /// Document → pixels of the output being drawn: `view` itself, except while an export draws @@ -236,6 +240,15 @@ pub(crate) struct Frame<'a> { } impl Frame<'_> { + /// Hash the hidden objects once for the options a frame draws with. + pub(crate) fn hidden_inputs(opts: &RenderOptions) -> u64 { + let mut hidden: Vec<_> = opts.hidden.iter().collect(); + hidden.sort_unstable(); + let mut h = DefaultHasher::new(); + hidden.hash(&mut h); + h.finish() + } + pub(crate) fn reject_patch(&self) -> bool { self.patch.is_some_and(|hit| { hit.set(true); diff --git a/crates/render/src/fx/entries.rs b/crates/render/src/fx/entries.rs index 64c1cf5ad9..d28412ab8c 100644 --- a/crates/render/src/fx/entries.rs +++ b/crates/render/src/fx/entries.rs @@ -221,19 +221,25 @@ pub(crate) struct Reads { /// Pattern paints: the pattern definitions. Their art can hold anything, so content painted /// with a pattern reads everything else too. pub(super) patterns: bool, - /// Symbol instances and type with inline graphics: the symbols' art. Symbol art can hold - /// anything, so content that shows a symbol reads everything else too. + /// Symbol instances, type with inline graphics, pattern art and brush art: the symbols' art. + /// Symbol art can hold anything, so content that shows a symbol reads everything else too. pub(super) symbols: bool, - /// Images and placed documents: their pixels and files, and the options and the layer's Dim - /// Images they are drawn with. + /// Images, placed documents, symbol art, pattern art and brush art: their pixels and files, + /// and the options and the layer's Dim Images they are drawn with. pub(super) images: bool, - /// Brushed strokes: the brush library. + /// Placed documents, symbol art and brushed strokes: the global bitmap generation while + /// progressive previews are on. Symbol and brush art can hold placed documents. Pattern tiles + /// draw with progressive previews off. + pub(super) placed_documents: bool, + /// Brushed strokes, symbol art and pattern art: the brush library. Brush art can hold + /// anything, so content that uses a brushed stroke reads everything else too. pub(super) brushes: bool, /// Type: the fonts, whether overprinting shows ([`crate::proof::overprints`]) and the /// substitution highlights. pub(super) text: bool, /// Plug-in effects on its objects: the plug-ins installed. Those in the symbol and pattern art - /// it shows are found with the document's inputs ([`DocInputs`]). + /// it shows are found with the document's inputs ([`DocInputs`]). Those in brush art are found + /// with the brush library ([`crate::brush_fx::BrushCache`]). pub(super) plugins: bool, } @@ -243,13 +249,24 @@ impl Reads { Self::of_all(std::iter::once(n)) } - /// What the content of `nodes` reads together. A pattern's art can hold anything, as a - /// symbol's can, so content painted with a pattern reads everything else too (#1723). + /// What the content of `nodes` reads together. Pattern, symbol and brush art can hold anything, + /// so content showing any of them reads the other document resources too (#1723). Progressive bitmap + /// readiness follows content that holds placed documents, shows symbol art or uses brushed + /// strokes. Pattern tiles draw with progressive previews off. pub(crate) fn of_all<'a>(nodes: impl Iterator) -> Self { let mut reads = Self::default(); nodes.for_each(|n| reads.add(n)); - if reads.symbols || reads.patterns { - return Self { patterns: true, symbols: true, images: true, brushes: true, text: true, plugins: reads.plugins }; + reads.placed_documents |= reads.symbols || reads.brushes; + if reads.symbols || reads.patterns || reads.brushes { + return Self { + patterns: true, + symbols: true, + images: true, + placed_documents: reads.placed_documents, + brushes: true, + text: true, + plugins: reads.plugins, + }; } reads } @@ -280,7 +297,11 @@ impl Reads { } match &c.kind { NodeKind::SymbolInstance { .. } => self.symbols = true, - NodeKind::Image(_) | NodeKind::PlacedDocument(_) => self.images = true, + NodeKind::Image(_) => self.images = true, + NodeKind::PlacedDocument(_) => { + self.images = true; + self.placed_documents = true; + } NodeKind::Text(t) => { self.text = true; self.symbols |= t.runs.iter().any(|r| r.inline.is_some()); diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index d57c34a315..b742d5718f 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -1,10 +1,10 @@ use super::bounds::{apply_carrying, item_effects, item_raster}; -use super::entries::{Content, DocInputs, Drawn, FX_RASTER_BUDGET, Inputs, ItemGeom, KeptImage, Made, Reads, feather_outline}; +use super::entries::{Content, DocInputs, Drawn, FX_RASTER_BUDGET, Inputs, ItemGeom, KeptImage, Made, Reads, feather_outline, raster_bytes}; #[cfg(test)] use super::raster::RASTERIZED; use super::raster::{ DRAG_PIXEL_BUDGET, PIXEL_BUDGET, PixelEntry, ViewCrop, content_changing, doc_raster_ppi, drag_scale, draw_placed, draw_scaled, filter_region, - filter_region_within, hard_edged, image_size, linear_key, looks_around, pan_margin, + filter_region_within, hard_edged, image_size, linear_key, looks_around, pan_margin, panned_exactly_whole, }; use super::{ Affine, AppearanceItem, Arc, BezPath, Channels, DefaultHasher, Document, FillRule, Frame, GeomContext, Hash, Hasher, Ink, Node, PixelFx, @@ -69,14 +69,18 @@ impl Renderer { /// raster holds at most [`PIXEL_BUDGET`] pixels and [`crate::MAX_RASTER_SIDE`] a side: content /// over the budget is cropped to the view (content with a [`Kept`] image to its window) when /// every effect only looks nearby, and content still over either limit is rendered at a lower - /// resolution. A whole raster at full resolution is cached while the object, the - /// zoom and what the content reads ([`Inputs`]) stay the same (panning only moves it), and - /// while interacting after the content only moved ([`Self::move_pixel_content`]). A cropped or - /// lower-resolution raster is cached while the object, the zoom and what the content reads stay - /// the same and a pan keeps the view inside the rect it was made for ([`PixelEntry::view`]): the - /// view, and for a raster cropped to it that is made again at the same zoom and rotation, outside - /// a drag and for content without a [`Kept`] image, the view with [`pan_margin`] around it. A - /// lower-resolution one is kept resampled to the view's pixels ([`Self::resampled`]). + /// resolution. A raster of the whole content is cached while the object, the zoom and what the + /// content reads ([`Inputs`]) stay the same (panning only moves it, and at a lower resolution + /// only by whole view and output pixels with the same output linear coefficients and the same + /// raster origin, scale and size as a fresh render, [`PixelEntry::pan`]), and at full resolution + /// while interacting after the content only moved ([`Self::move_pixel_content`]). One at a + /// lower resolution draws through its copy resampled + /// to the view's pixels ([`Self::draw_kept`]). A cropped raster is cached while the object, the + /// zoom and what the content reads stay the same and a pan keeps the view inside the rect it + /// was made for ([`PixelEntry::view`]): the view, and for a raster cropped to it that is made + /// again at the same zoom and rotation, outside a drag and for content without a [`Kept`] image, + /// the view with [`pan_margin`] around it. A cropped one at a lower resolution is kept + /// resampled to the view's pixels ([`Self::resampled`]). /// While dragging, content without such a raster to draw renders within [`DRAG_PIXEL_BUDGET`] /// pixels and is not cached, except content cropped to the view whose raster can move: its /// raster covers the view with [`pan_margin`] around it, and the drag's later frames move it with @@ -156,8 +160,14 @@ impl Renderer { Some(m) if !fits => full.intersect(room.inflate(m, m)), _ => full, }; - let (x0, y0) = (region.x0.floor(), region.y0.floor()); - let (rw, rh) = ((region.x1 - x0).max(1.0), (region.y1 - y0).max(1.0)); + // The origin and the sizes, rounded to 2^-20 device pixels, keep the raster's place, dimensions + // and filter scale stable across whole-pixel pans that leave rounding error in the view. Origin + // ties round to even steps, so whole-pixel shifts round alike across zero. Origins of 2^32 pixels + // or more in magnitude are kept as they are. Size fractions round ties away from zero. + let snap_origin = |v: f64| if v.abs() < 4_294_967_296.0 { (v * 1_048_576.0).round_ties_even() / 1_048_576.0 } else { v }; + let round_size = |v: f64| v.trunc() + (v.fract() * 1_048_576.0).round() / 1_048_576.0; + let (x0, y0) = (snap_origin(region.x0).floor(), snap_origin(region.y0).floor()); + let (rw, rh) = (round_size((region.x1 - x0).max(1.0)), round_size((region.y1 - y0).max(1.0))); // (vello_cpu panics drawing near `u16::MAX` pixels a side.) let side = f64::from(crate::MAX_RASTER_SIDE); let k = (PIXEL_BUDGET / (rw * rh)).sqrt().min(side / rw).min(side / rh).min(1.0); @@ -173,11 +183,13 @@ impl Renderer { let (aw, ah) = (around.width().ceil() + 1.0, around.height().ceil() + 1.0); (DRAG_PIXEL_BUDGET / (aw * ah)).sqrt().min(side / aw).min(side / ah).min(1.0) }); - // The cached raster: of the whole content at full size at this zoom, else of this view (and - // the margin around it). + // The cached raster: of the whole content at this zoom (at full size, or at a lower + // resolution when an effect looks anywhere in the object), else of this view (and the margin + // around it). + let entire = fits || margin.is_none(); let whole = fits && k >= 1.0; self.stats.view_sized += usize::from(!whole); - let in_view = (!whole).then(|| ViewCrop::of(f.view, room)); + let in_view = (!entire).then(|| ViewCrop::of(f.view, room)); let stamp = self.stamp; let channels = match f.ink.base() { Ink::Cmy => effects::pixel::Channels::CmyPlane, @@ -197,7 +209,18 @@ impl Renderer { }); let interacting = f.opts.interacting; let in_place = |e: &PixelEntry| match e.view { - None => whole, + None => e.pan.map_or(whole, |(pan, output_pan, output_linear)| { + let p = f.view * e.anchor; + entire + && panned_exactly_whole(pan, f.view) + && output_linear == linear_key(f.output) + && panned_exactly_whole(output_pan, f.output) + && e.k.to_bits() == k.to_bits() + && f64::from(e.image.width()) == w + && f64::from(e.image.height()) == h + && (p.x + e.rel.0).round() == x0 + && (p.y + e.rel.1).round() == y0 + }), Some(v) => !whole && (e.valid.is_some() || v.serves(f.view, screen)), }; // A raster a drag kept draws during a drag, while what the frame shows of the content lies @@ -229,7 +252,7 @@ impl Renderer { if e.image_left_out { self.image_left_out = self.image_left_out.map(|_| true); } - draw_scaled(ctx, image, at, k); + self.draw_kept(ctx, f, key, screen, (image, at, k)); return; } // During a drag, content without a raster to draw renders within the drag's budget (#2558). @@ -368,6 +391,10 @@ impl Renderer { Some((image, x, y)) => (image, x, y, 1.0), None => (image, x0, y0, k), }; + // A raster of the whole content at a lower resolution is kept whole for pans, and drawn + // through its copy resampled to the view's pixels ([`Self::draw_kept`]). + let low = key.is_some() && in_view.is_none() && k < 1.0 && content.kept.is_none_or(|k| k.shared) && !drag_keep; + let mut kept_low = None; // A cancelled export drew part of the content: that raster isn't kept for later frames. if !vectorcraft_doc::cancel::is_cancelled() && let Some(((key, made), inputs)) = key.zip(made).zip(inputs) @@ -386,8 +413,10 @@ impl Renderer { rel, k, image: image.clone(), - view: in_view, + view: (!whole && !low).then(|| ViewCrop::of(f.view, room)), valid, + pan: low.then(|| (f.view.translation(), f.output.translation(), linear_key(f.output))), + shown: None, made, inputs, moved, @@ -395,8 +424,8 @@ impl Renderer { image_left_out, stamp, }; - self.pixel_fx.insert(key, entry); - self.trim_fx_rasters(FX_RASTER_BUDGET); + self.keep_pixel_content(key, entry); + kept_low = low.then_some(key); } // An image over the limits was drawn at a frame's resolution: its raster is kept. The // placements of a copied image each draw their own (`Kept::shared`). @@ -406,7 +435,66 @@ impl Renderer { *kept.image.borrow_mut() = Some(KeptImage::Raster(image.clone(), place, failed, image_left_out)); if f.view == call { draw_scaled(ctx, image, (x0, y0), k) } else { draw_placed(ctx, image, call * place) } } - None => draw_scaled(ctx, image, (x0, y0), k), + None => self.draw_kept(ctx, f, kept_low, screen, (image, (x0, y0), k)), + } + } + + /// Keep `entry` for `key` and trim the cache, deferring trimming for a whole raster at a lower + /// resolution until [`Self::draw_kept`] draws it. + fn keep_pixel_content(&mut self, key: (usize, usize, Ink), entry: PixelEntry) { + let low = entry.pan.is_some(); + self.pixel_fx.insert(key, entry); + if !low { + self.trim_fx_rasters(FX_RASTER_BUDGET); + } + } + + /// Draw `(image, at, k)` as [`draw_scaled`] draws `image` at `at`, `1 / k` device pixels a + /// pixel. When it is the raster kept for `key` of the whole content at a lower resolution + /// ([`PixelEntry::pan`]), in the frame `f` onto `screen`, its copy resampled to the device + /// pixels of a frame through the same view ([`PixelEntry::shown`]) is drawn instead, made again + /// for a frame it does not serve. A copy that alone exceeds [`FX_RASTER_BUDGET`] is not made; + /// the raster draws scaled. When the cache exceeds its budget, [`Self::trim_fx_rasters`] + /// replaces a frame's whole rasters with their view copies before it evicts that frame's + /// entries, least recently drawn frames first. + /// A raster that covers none of `screen`'s pixels draws scaled. + fn draw_kept( + &mut self, + ctx: &mut RenderContext, + f: &Frame, + key: Option<(usize, usize, Ink)>, + screen: Rect, + (image, at, k): (std::sync::Arc, (f64, f64), f64), + ) { + let Some((key, e)) = key.and_then(|key| self.pixel_fx.get(&key).filter(|e| e.pan.is_some()).map(|e| (key, e))) else { + return draw_scaled(ctx, image, at, k); + }; + let p = f.view * e.anchor; + if let Some((_, copy, rel)) = e.shown.as_ref().filter(|(v, ..)| v.serves(f.view, screen)) { + draw_scaled(ctx, copy.clone(), ((p.x + rel.0).round(), (p.y + rel.1).round()), 1.0); + return; + } + let covered = Rect::new(at.0, at.1, at.0 + f64::from(image.width()) / k, at.1 + f64::from(image.height()) / k).intersect(screen); + let (w, h) = (covered.x1.ceil() - covered.x0.floor(), covered.y1.ceil() - covered.y0.floor()); + if w * h * 4.0 > FX_RASTER_BUDGET as f64 { + if let Some(e) = self.pixel_fx.get_mut(&key) { + e.shown = None; + } + self.trim_fx_rasters(FX_RASTER_BUDGET); + return draw_scaled(ctx, image, at, k); + } + match self.resampled(f, image.clone(), at, k, screen) { + Some((copy, x, y)) => { + if let Some(e) = self.pixel_fx.get_mut(&key) { + e.shown = Some((ViewCrop::of(f.view, screen), copy.clone(), (x - p.x, y - p.y))); + } + self.trim_fx_rasters(FX_RASTER_BUDGET); + draw_scaled(ctx, copy, (x, y), 1.0); + } + None => { + self.trim_fx_rasters(FX_RASTER_BUDGET); + draw_scaled(ctx, image, at, k); + } } } @@ -512,26 +600,38 @@ impl Renderer { } /// The inputs a raster of `n`'s content, which reads `reads`, is drawn with in frame `f`: the - /// color settings, the edge smoothing, whether dashed strokes draw as solid lines, the document's raster effects resolution (which a - /// Rasterize or De-Interlace anywhere in the content follows), the knockout `n` inherits and, - /// while `n` holds the isolated group, isolation mode; the pattern definitions, symbols and - /// brush library it reads; for images and placed documents their pixels and files, the - /// layer's Dim Images and the options they are drawn with (with + /// color settings, the render mode ([`crate::RenderOptions::precise`]), the edge smoothing mode, + /// the hidden objects and the instance left out during symbol editing, whether guides and + /// template layers are left out, the guide color and style, whether Layer Options show on + /// screen, whether dashed strokes draw as solid lines, + /// the document's raster effects resolution (which a Rasterize or De-Interlace anywhere in the + /// content follows), the knockout `n` inherits and, while `n` holds the isolated group, + /// isolation mode; the pattern definitions, symbols and brush library it reads; for images and + /// placed documents their pixels and files, the layer's Dim Images, whether images show in + /// Outline mode ([`Self::shows_outline_images`]) and the options they are drawn with (with /// [`crate::RenderOptions::kept_images_only`], also which pixels and undecodable notes the - /// image store holds); for type the fonts and the hyphenation exceptions, whether overprinting shows - /// ([`crate::proof::overprints`]) and Document Setup's substitution highlights; and the - /// plug-ins installed, with the names of the document's swatches and patterns and its pattern - /// definitions (a plug-in's painted pieces can name them), when an object in it has a plug-in - /// effect, and when it shows symbol or pattern art and an object in the document's symbol or - /// pattern art has one. + /// image store holds); for content that holds placed documents, shows symbol art or uses + /// brushed strokes, whether placed documents draw from background bitmaps + /// ([`crate::placed_document::progressive_bitmaps`]) and, when progressive previews are on, + /// how many bitmaps are ready ([`crate::placed_document::generation`]); for type the fonts and the + /// hyphenation exceptions, whether overprinting shows ([`crate::proof::overprints`]) and + /// Document Setup's substitution highlights; and the plug-ins installed, with the names of the + /// document's swatches and patterns and its pattern definitions (a plug-in's painted pieces + /// can name them), when an object in the content has a plug-in effect, when it uses brushed + /// strokes and an object in the document's brush art has one, and when it shows symbol or + /// pattern art and an object in the document's symbol or pattern art has one. pub(crate) fn raster_inputs(&mut self, f: &Frame, n: &Node, reads: Reads) -> Inputs { let doc = self.doc_inputs(f.doc); let mut h = DefaultHasher::new(); - (doc.cms, f.opts.anti_alias.threshold(), self.knockout, f.doc.raster_effects_ppi.to_bits()).hash(&mut h); - // Cached effects on containers can include paths made into guides. - f.opts.hide_guides.hash(&mut h); + (doc.cms, f.opts.precise, std::mem::discriminant(&f.opts.anti_alias), self.knockout, f.doc.raster_effects_ppi.to_bits()).hash(&mut h); + // Cached effects on containers can include paths made into guides, drawn in the guide + // color and style, template layers, and sublayers drawn as their Layer Options show them. + let o = f.opts; + (o.hide_guides, o.guide, o.hide_templates, o.skip_templates, o.dim_templates).hash(&mut h); // Cached effects can include dashed strokes drawn as solid lines. f.opts.solid_dashes.hash(&mut h); + f.hidden_inputs.hash(&mut h); + f.opts.isolated.and_then(|_| f.doc.symbol_edit.as_ref()?.instance).hash(&mut h); if let Some((isolated, path)) = self.isolation_path(f) && n.id != isolated && path.contains(&n.id) @@ -547,12 +647,20 @@ impl Renderer { if reads.images { let o = f.opts; (doc.images, self.dim_images.map(f32::to_bits), o.smooth_images, o.image_mips, o.trace_views, o.progressive_placed).hash(&mut h); + self.shows_outline_images(f).hash(&mut h); o.trace_source.as_deref().hash(&mut h); o.mark_undecoded_images.hash(&mut h); // With only kept pixels drawn, a raster is made again once the store holds more pixels // or notes an image as undecodable. o.kept_images_only.then(|| crate::images::store().added()).hash(&mut h); } + if reads.placed_documents { + let progressive = crate::placed_document::progressive_bitmaps(f); + progressive.hash(&mut h); + if f.opts.progressive_placed { + crate::placed_document::generation().hash(&mut h); + } + } if reads.brushes { self.brushes.library_key(f.doc, self.stamp).hash(&mut h); } @@ -566,7 +674,7 @@ impl Renderer { // Color bitmap glyphs are sampled as images are (`draw_glyph_image`). (vectorcraft_text::layout_inputs(), crate::proof::overprints(f.opts), highlights, o.smooth_images).hash(&mut h); } - if reads.plugins || (doc.plugins && (reads.symbols || reads.patterns)) { + if reads.plugins || (reads.brushes && self.brushes.has_plugins()) || (doc.plugins && (reads.symbols || reads.patterns)) { (effects::plugin_revision(), doc.names, doc.patterns).hash(&mut h); } Inputs { reads, key: h.finish(), _doc: doc } @@ -621,27 +729,46 @@ impl Renderer { d } - /// Drop the least recently drawn shadow and filtered-content rasters beyond `budget` bytes - /// ([`FX_RASTER_BUDGET`]). + /// Trim the shadow and filtered-content entries to `budget` bytes ([`FX_RASTER_BUDGET`]), one + /// frame stamp at a time from the least recently drawn: replace that stamp's whole rasters that + /// have view copies with those copies, then, while the entries still exceed the budget, evict + /// that stamp's entries, reduced ones included. pub(super) fn trim_fx_rasters(&mut self, budget: usize) { - let shadows = self.shadows.iter().map(|(k, e)| (e.stamp, false, *k, e.bytes())); - let pixels = self.pixel_fx.iter().map(|(k, e)| (e.stamp, true, *k, e.bytes())); - let mut all: Vec<_> = shadows.chain(pixels).collect(); - let mut total: usize = all.iter().map(|e| e.3).sum(); + let mut total: usize = self.shadows.values().map(|e| e.bytes()).sum::() + self.pixel_fx.values().map(|e| e.bytes()).sum::(); if total <= budget { return; } + let shadows = self.shadows.iter().map(|(k, e)| (e.stamp, false, *k)); + let pixels = self.pixel_fx.iter().map(|(k, e)| (e.stamp, true, *k)); + let mut all: Vec<_> = shadows.chain(pixels).collect(); all.sort_unstable_by_key(|e| e.0); - for (_, pixel, key, bytes) in all { - if total <= budget { - break; + for group in all.chunk_by(|a, b| a.0 == b.0) { + for &(_, pixel, key) in group { + if total <= budget { + return; + } + if pixel + && let Some(e) = self.pixel_fx.get_mut(&key).filter(|e| e.pan.is_some()) + && let Some((view, copy, rel)) = e.shown.take() + { + total -= raster_bytes(&e.image); + e.image = copy; + e.k = 1.0; + e.rel = rel; + e.view = Some(view); + e.pan = None; + } } - if pixel { - self.pixel_fx.remove(&key); - } else { - self.shadows.remove(&key); + for &(_, pixel, key) in group { + if total <= budget { + return; + } + if pixel { + total -= self.pixel_fx.remove(&key).map_or(0, |e| e.bytes()); + } else { + total -= self.shadows.remove(&key).map_or(0, |e| e.bytes()); + } } - total -= bytes; } } diff --git a/crates/render/src/fx/raster.rs b/crates/render/src/fx/raster.rs index 02bf918089..99723f215e 100644 --- a/crates/render/src/fx/raster.rs +++ b/crates/render/src/fx/raster.rs @@ -90,16 +90,32 @@ pub(crate) struct PixelEntry { pub(super) rel: (f64, f64), pub(super) k: f64, pub(crate) image: std::sync::Arc, - /// For a raster of the content's whole reach at full size, `None`: it draws after a pan too. - /// For one cropped to the view, or made at a lower resolution, the view and the rect it was - /// made for: it draws only there, so dragging other art over the object keeps it (a wide blur, - /// or any blur zoomed in, reaches past the pixel budget). + /// For a raster of the content's whole reach at full size, or at a lower resolution with its + /// pans kept in [`Self::pan`], `None`: it draws after a pan too. For one cropped to the view, + /// or another raster made at a lower resolution (of an image kept for one placement, or kept + /// by a drag), the view and the rect it was made for: it draws only there, so dragging other + /// art over the object keeps it (a wide blur, or any blur zoomed in, reaches past the pixel + /// budget). pub(super) view: Option, /// For a raster a drag's frame kept of content cropped to the view, the device pixels (against /// the anchor's view position) whose pixels the effects decided with all they look at: the /// drag's later frames move the raster with its object while what they show of it lies within /// ([`Renderer::move_pixel_content`]). `None` for other rasters. pub(super) valid: Option, + /// For a raster of the content's whole reach made at a lower resolution than the view's, the + /// pans of the view and output it was made through, and the output's linear coefficients: it + /// draws when both grids pan by whole pixels ([`panned_exactly_whole`]), the output's linear + /// coefficients stay the same, its rounded origin matches a fresh render's floored origin, + /// its scale is bit-identical to a fresh render's, and its size matches a fresh render's. + /// `None` for other rasters. + pub(super) pan: Option<(Vec2, Vec2, [u64; 4])>, + /// For such a raster, its pixels resampled to the device pixels of the last frame that drew it, + /// the view and rect they were made for, and their top-left against the anchor's view position: + /// a frame they serve copies them ([`Renderer::draw_kept`]). Copies that alone exceed the cache + /// budget are not made. When the cache exceeds its budget, [`Renderer::trim_fx_rasters`] + /// goes through the frames least recently drawn first, and replaces a frame's whole rasters + /// with their view copies before it evicts that frame's entries. + pub(super) shown: Option<(ViewCrop, std::sync::Arc, (f64, f64))>, pub(super) made: Made, /// What the content read when the raster was made, with the channels the effects ran on and, /// under De-Interlace, the raster resolution. @@ -121,10 +137,28 @@ pub(crate) struct PixelEntry { impl PixelEntry { /// The bytes it holds, for [`FX_RASTER_BUDGET`]. pub(crate) fn bytes(&self) -> usize { - raster_bytes(&self.image) + self.made.bytes() + raster_bytes(&self.image) + self.shown.as_ref().map_or(0, |(_, copy, _)| raster_bytes(copy)) + self.made.bytes() } } +/// Is `view` panned by whole device pixels from a view whose pan was `pan`? +pub(super) fn panned_whole(pan: Vec2, view: Affine) -> bool { + let d = view.translation() - pan; + (d - Vec2::new(d.x.round(), d.y.round())).hypot() < 1e-6 +} + +/// Is `view` panned by whole device pixels from `pan`, allowing floating-point rounding +/// with a tolerance between 1e-9 and 1e-6 device pixels per axis and a combined error +/// below 1e-6 device pixels, as required by [`panned_whole`]? +pub(super) fn panned_exactly_whole(pan: Vec2, view: Affine) -> bool { + let at = view.translation(); + let whole = |a: f64, b: f64| { + let d = b - a; + (d - d.round()).abs() <= (f64::EPSILON * 64.0 * (a.abs() + b.abs())).clamp(1e-9, 1e-6) + }; + panned_whole(pan, view) && whole(pan.x, at.x) && whole(pan.y, at.y) +} + /// The four linear coefficients of `view` (zoom and rotation, not the pan), as cache keys. pub(crate) fn linear_key(view: Affine) -> [u64; 4] { let c = view.as_coeffs(); @@ -153,7 +187,7 @@ impl ViewCrop { let d = view.translation() - self.pan; let whole = Vec2::new(d.x.round(), d.y.round()); let s = screen - whole; - (d - whole).hypot() < 1e-6 && s.x0 >= self.screen.x0 && s.y0 >= self.screen.y0 && s.x1 <= self.screen.x1 && s.y1 <= self.screen.y1 + panned_whole(self.pan, view) && s.x0 >= self.screen.x0 && s.y0 >= self.screen.y0 && s.x1 <= self.screen.x1 && s.y1 <= self.screen.y1 } /// The rect the raster was made for, in the device pixels of a frame through `view` that it diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index c119ef8b64..ebc82abeb1 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -1142,6 +1142,7 @@ mod tests { visible: Rect::new(0.0, 0.0, 100.0, 100.0), px: 1.0, opts: &opts, + hidden_inputs: Frame::hidden_inputs(&opts), ink: Ink::Display, output: Affine::IDENTITY, plates: None, diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index be44374572..c551162d2f 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -9,6 +9,77 @@ use super::{DRAG_PIXEL_BUDGET, Drawn, PIXEL_BUDGET, drag_scale, filter_region, f use crate::tests_fontchange::{fonts_steady, with_fonts_unchanged}; use crate::{RenderOptions, Rendered, Renderer}; +/// Placed documents, symbol art and brushed strokes follow progressive bitmap readiness. +/// Plain images and paths painted only with patterns keep their rasters when a bitmap is ready. +#[test] +fn reads_follow_progressive_placed_documents_in_content_and_art() { + use super::Reads; + use vectorcraft_doc::{ImageObject, LinkInfo, NodeKind, PlacedDocument}; + + let mut d = Document::new(100.0, 100.0); + let placed = Node::new( + d.alloc_id(), + NodeKind::PlacedDocument(Box::new(PlacedDocument { + link: LinkInfo::new("/art/card.vectorcraft"), + key: "placed".into(), + bounding: false, + page_box: Default::default(), + width: 20.0, + height: 20.0, + xf: Affine::IDENTITY, + placement: Default::default(), + })), + ); + assert!(Reads::of(&placed).placed_documents, "a placed document reads progressive bitmap readiness"); + + let symbol = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Stamp".into(), xf: Affine::IDENTITY }); + assert!(Reads::of(&symbol).placed_documents, "a symbol instance reads progressive bitmap readiness"); + + let mut appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + appearance.stroke_mut().unwrap().brush = Some("Stamp".into()); + let brushed = Node::path(d.alloc_id(), shapes::line((0.0, 0.0).into(), (20.0, 20.0).into()), appearance); + assert!(Reads::of(&brushed).placed_documents, "a brushed stroke reads progressive bitmap readiness"); + + let image = Node::new( + d.alloc_id(), + NodeKind::Image(Box::new(ImageObject { + key: "image".into(), + width: 20, + height: 20, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + })), + ); + assert!(!Reads::of(&image).placed_documents, "a plain image does not read progressive bitmap readiness"); + + let patterned = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), + Appearance::basic(Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY }, Paint::None, 0.0), + ); + assert!(!Reads::of(&patterned).placed_documents, "a pattern-only path does not read progressive bitmap readiness"); +} + +/// Brush and symbol art can hold images drawn with the frame's image options, and brush art can +/// show symbols. +#[test] +fn reads_follow_images_in_brush_and_symbol_art() { + use super::Reads; + use vectorcraft_doc::NodeKind; + + let mut d = Document::new(100.0, 100.0); + let mut appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + appearance.stroke_mut().unwrap().brush = Some("Stamp".into()); + let brushed = Node::path(d.alloc_id(), shapes::line((0.0, 0.0).into(), (20.0, 20.0).into()), appearance); + assert!(Reads::of(&brushed).images, "a brushed stroke reads images"); + assert!(Reads::of(&brushed).symbols, "a brushed stroke reads symbol art"); + + let symbol = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Stamp".into(), xf: Affine::IDENTITY }); + assert!(Reads::of(&symbol).images, "a symbol instance reads images"); +} + /// Rasterize and culling include the complete rendered image under lights from opposite sides. #[test] fn rendered_three_d_painted_bounds_hold_both_shadows() { @@ -1889,6 +1960,710 @@ fn a_zoomed_drag_keeps_the_sampling_footprint_inside_the_valid_crop() { assert_eq!(r.stats.previewed, 1, "the sampling footprint outside the valid crop filters the content again"); } +/// At 6400% a 200 × 150 pt rectangle with Torn Edges, which looks anywhere in the object, covers +/// 12800 × 9600 px, past the pixel budget, so its raster holds the whole object at a lower +/// resolution. The view shows its torn right edge. Pans by whole pixels with the same sampling +/// grid draw that raster again, and a frame through the same view copies its pixels resampled to +/// the view; a new fill, color mode or zoom, or a pan by part of a pixel, filters the content +/// again. +#[test] +fn pans_draw_the_lower_resolution_raster_of_the_whole_object_again() { + let mut d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let id = d.layers[0].children().unwrap()[0].id; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |zoom: f64, dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(zoom) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let first = r.render(&d, 1280, 800, view(64.0, 0.0), &opts); + assert!(first.pixels.as_chunks::<4>().0.iter().any(|pixel| *pixel != first.pixel(0, 0)), "the view shows the torn edge"); + assert_eq!(r.pixel_fx.len(), 1); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let image = kept.image.clone(); + let drawn = |r: &Renderer, image: &Arc| r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, image)); + for dx in [40.0, 80.0, -40.0] { + let pixels = r.render(&d, 1280, 800, view(64.0, dx), &opts).pixels; + assert!(drawn(&r, &image), "a pan of {dx} px draws the kept raster"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(64.0, dx), &opts).pixels, "a pan of {dx} px as a new renderer draws it"); + } + let copy = |r: &Renderer| r.pixel_fx.values().next().and_then(|e| e.shown.as_ref()).map(|(_, copy, _)| copy.clone()).unwrap(); + let before = copy(&r); + let _ = r.render(&d, 1280, 800, view(64.0, -40.0), &opts); + assert!(Arc::ptr_eq(&before, ©(&r)), "a frame through the same view copies the resampled pixels"); + for pan in [(39.9999999, 0.0), (0.0, 39.9999999), (40.0000001, 0.0), (0.0, 40.0000001)] { + let _ = r.render(&d, 1280, 800, view(64.0, 0.0), &opts); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + let shifted = Affine::translate(pan) * view(64.0, 0.0); + let pixels = r.render(&d, 1280, 800, shifted, &opts).pixels; + assert!(!drawn(&r, &image), "a nearly whole-pixel pan with a different raster origin or sampling grid filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, shifted, &opts).pixels, "after a nearly whole-pixel pan"); + } + let _ = r.render(&d, 1280, 800, view(64.0, 40.0), &opts); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + let n = d.node_mut(id).unwrap(); + let effects = std::mem::take(&mut n.appearance.effects); + n.appearance = Appearance::basic(Paint::solid(Color::rgb(0.1, 0.4, 0.9)), Paint::None, 0.0).into(); + n.appearance.effects = effects; + let pixels = r.render(&d, 1280, 800, view(64.0, 40.0), &opts).pixels; + assert!(!drawn(&r, &image), "a new fill filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(64.0, 40.0), &opts).pixels, "with the new fill"); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + d.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let pixels = r.render(&d, 1280, 800, view(64.0, 40.0), &opts).pixels; + assert!(!drawn(&r, &image), "a new color mode filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(64.0, 40.0), &opts).pixels, "in the new color mode"); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + let pixels = r.render(&d, 1280, 800, view(48.0, 40.0), &opts).pixels; + assert!(!drawn(&r, &image), "a new zoom filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(48.0, 40.0), &opts).pixels, "at the new zoom"); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + let pixels = r.render(&d, 1280, 800, view(48.0, 40.5), &opts).pixels; + assert!(!drawn(&r, &image), "a pan by part of a pixel filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(48.0, 40.5), &opts).pixels, "after a pan by part of a pixel"); +} + +/// At 6400% a 2000 × 1 pt bar with Torn Edges is 128000 px wide, so its whole-object raster is +/// capped at the widest raster side and its scale stays the same across vertical pans. A vertical +/// pan by part of a pixel that leaves the raster's rounded origin and size unchanged moves the +/// sampling grid, so it filters the content again. +#[test] +fn a_pan_by_part_of_a_pixel_filters_a_width_capped_whole_object_raster_again() { + let d = doc_with(Rect::new(100.0, 100.0, 2100.0, 101.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |y: f64| Affine::translate((640.0, y)) * Affine::scale(64.0) * Affine::translate((-1100.0, -100.5)); + for (start, pan) in [(400.1, 40.2), (400.3, 40.7)] { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(start), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + assert_eq!(u32::from(kept.image.width()), crate::MAX_RASTER_SIDE, "the raster is as wide as a raster can be"); + let image = kept.image.clone(); + let pixels = r.render(&d, 1280, 800, view(start + pan), &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "a pan of {pan} px from {start} filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(start + pan), &opts).pixels, "after a pan of {pan} px from {start}"); + } +} + +/// The canvas centers its view on a document point and pans by moving that point by the pan's +/// device pixels over the scale, here across and down in turn. At scales from 50 to 120, with +/// centers on whole points and between them, each whole-pixel pan keeps the raster's origin, scale +/// and size bit-identical to a fresh render's and draws the kept raster. +#[test] +fn pans_of_a_centered_view_draw_the_whole_object_raster_again() { + let d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |scale: f64, c: Point| Affine::translate((640.0, 400.0)) * Affine::scale(scale) * Affine::translate((-c.x, -c.y)); + for (scale, c) in [ + (96.0, Point::new(295.3, 175.7)), + (96.0, Point::new(291.137, 171.913)), + (96.0, Point::new(150.0, 120.0)), + (72.0, Point::new(200.0, 175.0)), + (120.0, Point::new(295.3, 175.7)), + (56.0, Point::new(150.0, 120.0)), + (50.0, Point::new(291.137, 171.913)), + ] { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(scale, c), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let image = kept.image.clone(); + let mut at = c; + for i in 1..=4 { + if i % 2 == 1 { + at.x -= 40.0 / scale; + } else { + at.y -= 40.0 / scale; + } + let pixels = r.render(&d, 1280, 800, view(scale, at), &opts).pixels; + assert!(r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "pan {i} of 40 px at scale {scale} from {c:?} draws the kept raster"); + let mut fresh = Renderer::new(); + assert!(pixels == fresh.render(&d, 1280, 800, view(scale, at), &opts).pixels, "pan {i} at scale {scale} from {c:?}"); + let made = fresh.pixel_fx.values().next().unwrap(); + let kept = r.pixel_fx.values().next().unwrap(); + assert_eq!(kept.k.to_bits(), made.k.to_bits(), "pan {i} at scale {scale} from {c:?}"); + assert_eq!((kept.image.width(), kept.image.height()), (made.image.width(), made.image.height())); + } + } +} + +/// A whole-object raster kept for pans draws again only while its scale, its size, and the zoom, +/// rotation and whole-pixel pan of the output it was made for match the frame's. +#[test] +fn a_whole_object_raster_draws_after_a_pan_only_as_made_for_this_output_scale_and_size() { + use super::linear_key; + let d = doc_with(Rect::new(100.0, 100.0, 2100.0, 101.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |dy: f64| Affine::translate((640.0, 400.0 + dy)) * Affine::scale(64.0) * Affine::translate((-1100.0, -100.5)); + type Change = fn(&mut super::PixelEntry); + let changes: [(&str, Change); 6] = [ + ("the same output scale and size", |_| {}), + ("an output at another zoom", |e| { + if let Some(pan) = &mut e.pan { + pan.2 = linear_key(Affine::scale(2.0) * Affine::scale(64.0)); + } + }), + ("an output panned by part of a pixel", |e| { + if let Some(pan) = &mut e.pan { + pan.1.y += 0.5; + } + }), + ("a scale off by a small relative amount", |e| e.k *= 1.0 + 1e-6), + ("another width", |e| { + e.image = Arc::new(vello_cpu::Pixmap::new(e.image.width() + 1, e.image.height())); + }), + ("another height", |e| { + e.image = Arc::new(vello_cpu::Pixmap::new(e.image.width(), e.image.height() + 1)); + }), + ]; + for (case, (what, change)) in changes.into_iter().enumerate() { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let e = r.pixel_fx.values_mut().next().unwrap(); + assert!(e.k < 1.0 && e.pan.is_some(), "a raster of the whole object kept for pans"); + assert_eq!(u32::from(e.image.width()), crate::MAX_RASTER_SIDE, "the raster is as wide as a raster can be"); + change(e); + let image = e.image.clone(); + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + let reused = r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)); + assert_eq!(reused, case == 0, "reuse after a pan, for {what}"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels, "after a pan, for {what}"); + } +} + +/// A width-capped whole-object raster draws after a whole-pixel pan, but filters again when the +/// pan differs from whole pixels by more than floating-point rounding. +#[test] +fn a_pan_near_a_whole_pixel_filters_a_width_capped_whole_object_raster_again() { + let d = doc_with(Rect::new(100.0, 100.0, 2100.0, 101.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |y: f64| Affine::translate((640.0, y)) * Affine::scale(64.0) * Affine::translate((-1100.0, -100.5)); + let drawn = |r: &Renderer, image: &Arc| r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, image)); + for start in [400.1, 400.3] { + for pan in [40.0000001, 39.9999999, 40.0] { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(start), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + assert_eq!(u32::from(kept.image.width()), crate::MAX_RASTER_SIDE, "the raster is as wide as a raster can be"); + let image = kept.image.clone(); + let pixels = r.render(&d, 1280, 800, view(start + pan), &opts).pixels; + if pan == 40.0 { + assert!(drawn(&r, &image), "a whole-pixel pan of the width-capped raster draws the kept raster"); + } else { + assert!(!drawn(&r, &image), "a pan within 1e-6 px of whole but off the grid filters the content again"); + } + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(start + pan), &opts).pixels, "after a pan of {pan} px from {start}"); + } + } +} + +/// Hiding a member of a group filters its whole-object raster again after a pan by whole pixels. +#[test] +fn hiding_a_member_filters_the_whole_object_raster_again_after_a_pan() { + let mut d = Document::new(100.0, 100.0); + let mut square = + |r: Rect, c: Color| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))); + let members = vec![square(Rect::new(100.0, 100.0, 300.0, 250.0), Color::WHITE), square(Rect::new(200.0, 100.0, 300.0, 250.0), Color::BLACK)]; + let id = members[1].id; + let mut g = Node::group(d.alloc_id(), members); + g.appearance.effects = vec![Effect { id: "sketch.tornEdges".into(), params: json!({}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let mut opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + opts.hidden.insert(id); + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels, "hiding a member filters the content again"); +} + +/// Image smoothing changes the pixels of an effected stroke whose scatter brush holds an image. +#[test] +fn image_smoothing_filters_a_brushed_strokes_raster_again_after_a_pan() { + use vectorcraft_brush::{Brush, BrushKind, Colorization, Scatter}; + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; + + let mut d = Document::new(160.0, 100.0); + let rgba = [0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 255]; + let png = crate::encode::png::encode(&rgba, 2, 2, &Default::default()).unwrap(); + d.images.insert("checks".into(), ImageBlob::new("image/png", png)); + let art = Node::new( + d.alloc_id(), + NodeKind::Image(Box::new(ImageObject { + key: "checks".into(), + width: 2, + height: 2, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + })), + ); + vectorcraft_brush::store( + &mut d, + &[Brush { name: "Checks".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) }], + ); + let mut appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 20.0); + appearance.stroke_mut().unwrap().brush = Some("Checks".into()); + let mut n = Node::path(d.alloc_id(), shapes::line((20.0, 50.0).into(), (100.0, 50.0).into()), appearance); + n.appearance.effects = vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": 1}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let mut opts = RenderOptions { background: Some([255, 255, 255, 255]), smooth_images: false, image_mips: false, ..Default::default() }; + let mut r = Renderer::new(); + let _ = r.render(&d, 160, 100, Affine::IDENTITY, &opts); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + let view = Affine::translate((4.0, 0.0)); + let unchanged = Renderer::new().render(&d, 160, 100, view, &opts).pixels; + opts.smooth_images = true; + let pixels = r.render(&d, 160, 100, view, &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "image smoothing filters the content again"); + assert!(pixels != unchanged, "image smoothing changes the brush art through the effect"); + assert!(pixels == Renderer::new().render(&d, 160, 100, view, &opts).pixels, "image smoothing draws as a new renderer does"); +} + +/// A symbol's fill color changes the pixels of an effected stroke whose scatter brush shows it. +#[test] +fn editing_a_symbol_in_brush_art_filters_a_brushed_strokes_raster_again_after_a_pan() { + use vectorcraft_brush::{Brush, BrushKind, Colorization, Scatter}; + use vectorcraft_doc::{NodeKind, Symbol}; + + let mut d = Document::new(160.0, 100.0); + let mut art = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(-4.0, -4.0, 4.0, 4.0)), + Appearance::basic(Paint::solid(Color::rgb(0.9, 0.1, 0.1)), Paint::None, 0.0), + ); + d.symbols.push(Symbol { dynamic: false, name: "Stamp".into(), art: Arc::new(art.clone()) }); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Stamp".into(), xf: Affine::IDENTITY }); + vectorcraft_brush::store( + &mut d, + &[Brush { + name: "Stamps".into(), + kind: BrushKind::Scatter(Scatter { art: instance, colorization: Colorization::None, ..Default::default() }), + }], + ); + let mut appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); + appearance.stroke_mut().unwrap().brush = Some("Stamps".into()); + let mut n = Node::path(d.alloc_id(), shapes::line((20.0, 50.0).into(), (100.0, 50.0).into()), appearance); + n.appearance.effects = vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": 1}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + let _ = r.render(&d, 160, 100, Affine::IDENTITY, &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.view.is_none(), "a raster of the whole object"); + let image = kept.image.clone(); + let view = Affine::translate((4.0, 0.0)); + let unchanged = Renderer::new().render(&d, 160, 100, view, &opts).pixels; + art.appearance = Appearance::basic(Paint::solid(Color::rgb(0.1, 0.4, 0.9)), Paint::None, 0.0).into(); + d.symbols[0].art = Arc::new(art); + let pixels = r.render(&d, 160, 100, view, &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "editing a symbol in brush art filters the content again"); + assert!(pixels == Renderer::new().render(&d, 160, 100, view, &opts).pixels, "the edited symbol draws as a new renderer does"); + assert!(pixels != unchanged, "the edited symbol changes the brush art through the effect"); +} + +/// Removing a plug-in used only in brush art filters a stroke again after a whole-pixel pan. +#[test] +fn removing_a_plugin_in_brush_art_filters_a_brushed_strokes_raster_again_after_a_pan() { + use vectorcraft_brush::{Brush, BrushKind, Colorization, Scatter}; + use vectorcraft_geom::{PathData, SubPath}; + use vectorcraft_plugins::wat as tpl; + + let _fonts = fonts_steady(); + const ID: &str = "test.render.fx.brush-art"; + let triangle = PathData::single(SubPath::polyline(&[Point::new(-4.0, -4.0), Point::new(4.0, -4.0), Point::new(0.0, 4.0)], true)); + let output = json!({"objects": [{"path": triangle}]}).to_string(); + let module = wat::parse_str(tpl::returning(&tpl::manifest(ID, "effect", "{}"), &output)).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + + let mut d = Document::new(160.0, 100.0); + let mut r = Renderer::new(); + let mut art = + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-4.0, -4.0, 4.0, 4.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + art.appearance.effects = vec![Effect { id: format!("plugin.{ID}"), params: json!({}), visible: true }]; + vectorcraft_brush::store( + &mut d, + &[Brush { name: "Stamps".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) }], + ); + let mut appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); + appearance.stroke_mut().unwrap().brush = Some("Stamps".into()); + let mut n = Node::path(d.alloc_id(), shapes::line((20.0, 50.0).into(), (100.0, 50.0).into()), appearance); + n.appearance.effects = vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": 1}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let opts = RenderOptions { precise: true, background: Some([255, 255, 255, 255]), ..Default::default() }; + let _ = r.render(&d, 160, 100, Affine::IDENTITY, &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.view.is_none(), "a raster of the whole object"); + let image = kept.image.clone(); + let view = Affine::translate((4.0, 0.0)); + let unchanged = Renderer::new().render(&d, 160, 100, view, &opts).pixels; + assert!(vectorcraft_plugins::registry::remove(ID), "the plug-in was installed"); + let pixels = r.render(&d, 160, 100, view, &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "removing the brush art's plug-in filters the content again"); + assert!(pixels != unchanged, "the plug-in changes the brush art through the effect"); + assert!(pixels == Renderer::new().render(&d, 160, 100, view, &opts).pixels, "removing the plug-in draws as a new renderer does"); +} + +/// Symbol editing leaves out the original instance inside a group's whole-object raster. +#[test] +fn symbol_editing_filters_the_whole_object_raster_again_after_a_pan() { + use vectorcraft_doc::{NodeKind, Symbol, SymbolEdit}; + + let mut d = Document::new(100.0, 100.0); + let white = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let art = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(200.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + d.symbols.push(Symbol { dynamic: false, name: "Stamp".into(), art: Arc::new(art.clone()) }); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Stamp".into(), xf: Affine::IDENTITY }); + let id = instance.id; + let mut g = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(instance)]); + g.appearance.effects = vec![Effect { id: "sketch.tornEdges".into(), params: json!({}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let mut opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let image = kept.image.clone(); + let layer = d.add_layer(Some("Stamp")); + let copy = d.reid(&art); + d.insert(Some(layer), 0, copy).unwrap(); + d.symbol_edit = Some(SymbolEdit { + symbol: "Stamp".into(), + layer, + instance: Some(id), + xf: Affine::IDENTITY, + group: false, + changed: false, + back_isolation: None, + back_layer: None, + }); + opts.isolated = Some(layer); + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "symbol editing filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels, "symbol editing draws as a new renderer does"); +} + +/// Hiding or skipping template layers filters the whole-object raster of a layer with effects +/// that holds a template sublayer again after a pan by whole pixels. +#[test] +fn hiding_templates_filters_the_whole_object_raster_again_after_a_pan() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let mut square = + |r: Rect, c: Color| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))); + let white = square(Rect::new(100.0, 100.0, 300.0, 250.0), Color::WHITE); + let black = square(Rect::new(200.0, 100.0, 300.0, 250.0), Color::BLACK); + let mut template = Node::layer(d.alloc_id(), "Template", vectorcraft_doc::LayerColor::Preset(0)); + if let vectorcraft_doc::NodeKind::Layer { template: flag, children, .. } = &mut template.kind { + *flag = true; + children.push(black); + } + d.insert(Some(l), 0, Arc::unwrap_or_clone(white)).unwrap(); + d.insert(Some(l), 1, template).unwrap(); + d.node_mut(l).unwrap().appearance.effects = vec![Effect { id: "sketch.tornEdges".into(), params: json!({}), visible: true }]; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), dim_templates: false, ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + for (left_out, what) in + [(RenderOptions { hide_templates: true, ..opts.clone() }, "hiding"), (RenderOptions { skip_templates: true, ..opts.clone() }, "skipping")] + { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let fresh = Renderer::new().render(&d, 1280, 800, view(40.0), &left_out).pixels; + assert!(fresh != Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels, "the template shows through the effect"); + let pixels = r.render(&d, 1280, 800, view(40.0), &left_out).pixels; + assert!(pixels == fresh, "{what} templates filters the content again"); + } +} + +/// Show Images in Outline Mode filters the whole-object raster of a layer with Torn Edges and +/// an embedded image in a sublayer with Preview off again after a pan by whole pixels. +#[test] +fn outline_images_filters_the_whole_object_raster_again_after_a_pan() { + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; + + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let white = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let rgba = [255, 0, 0, 255].repeat(200 * 150); + let png = crate::encode::png::encode(&rgba, 200, 150, &Default::default()).unwrap(); + d.images.insert("red".into(), ImageBlob::new("image/png", png)); + let im = ImageObject { + key: "red".into(), + width: 200, + height: 150, + xf: Affine::translate((100.0, 100.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let image = Arc::new(Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))); + let mut outlined = Node::layer(d.alloc_id(), "Outlined", vectorcraft_doc::LayerColor::Preset(0)); + if let NodeKind::Layer { preview, children, .. } = &mut outlined.kind { + *preview = false; + children.push(image); + } + d.insert(Some(l), 0, white).unwrap(); + d.insert(Some(l), 1, outlined).unwrap(); + d.node_mut(l).unwrap().appearance.effects = vec![Effect { id: "sketch.tornEdges".into(), params: json!({}), visible: true }]; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.pan.is_some(), "a raster of the whole object at a lower resolution"); + let image = kept.image.clone(); + let unchanged = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + d.setup.outline_images = true; + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "Show Images in Outline Mode filters the content again"); + assert!(pixels != unchanged, "Show Images in Outline Mode changes the image through the effect"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels, "Show Images in Outline Mode draws as a new renderer does"); +} + +/// A new guide color or style, or turning the Layer Options' screen look on or off, filters the +/// whole-object raster of a layer with effects that holds a guide and a sublayer with Preview +/// off again after a pan by whole pixels. +#[test] +fn guide_style_and_layer_options_filter_the_whole_object_raster_again_after_a_pan() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let mut square = + |r: Rect, c: Color| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))); + let white = square(Rect::new(100.0, 100.0, 300.0, 250.0), Color::WHITE); + let black = square(Rect::new(200.0, 100.0, 300.0, 250.0), Color::BLACK); + let mut guide = Arc::unwrap_or_clone(square(Rect::new(150.0, 120.0, 290.0, 230.0), Color::BLACK)); + if let vectorcraft_doc::NodeKind::Path { guide: flag, .. } = &mut guide.kind { + *flag = true; + } + let mut outlined = Node::layer(d.alloc_id(), "Outlined", vectorcraft_doc::LayerColor::Preset(0)); + if let vectorcraft_doc::NodeKind::Layer { preview, children, .. } = &mut outlined.kind { + *preview = false; + children.push(black); + } + d.insert(Some(l), 0, Arc::unwrap_or_clone(white)).unwrap(); + d.insert(Some(l), 1, outlined).unwrap(); + d.insert(Some(l), 2, guide).unwrap(); + d.node_mut(l).unwrap().appearance.effects = + vec![Effect { id: "blur.radial".into(), params: json!({"amount": 1, "quality": "draft"}), visible: true }]; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), guide: ([0, 200, 255], false), ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let changes = [ + (RenderOptions { guide: ([255, 0, 0], false), ..opts.clone() }, "a new guide color"), + (RenderOptions { guide: ([0, 200, 255], true), ..opts.clone() }, "dotted guides"), + (RenderOptions { dim_templates: false, ..opts.clone() }, "Layer Options turned off"), + ]; + let unchanged = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + for (changed, what) in changes { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let fresh = Renderer::new().render(&d, 1280, 800, view(40.0), &changed).pixels; + assert!(fresh != unchanged, "{what} changes the effect's pixels"); + let pixels = r.render(&d, 1280, 800, view(40.0), &changed).pixels; + assert!(pixels == fresh, "{what} filters the content again"); + } +} + +/// Switching the render mode ([`crate::RenderOptions::precise`]) filters the whole-object raster +/// again after a pan by whole pixels. +#[test] +fn render_mode_filters_the_whole_object_raster_again_after_a_pan() { + let d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { precise: false, background: Some([255, 255, 255, 255]), ..Default::default() }; + let precise = RenderOptions { precise: true, ..opts.clone() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.pan.is_some(), "a raster of the whole object at a lower resolution"); + let image = kept.image.clone(); + let pixels = r.render(&d, 1280, 800, view(40.0), &precise).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "the precise render mode filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(40.0), &precise).pixels, "in the precise render mode"); +} + +/// Art and Type edge smoothing share a coverage threshold, but Type snaps glyphs to the pixel +/// grid: switching between them filters the whole-object raster of a group with type again after +/// a pan by whole pixels. +#[test] +fn anti_aliasing_mode_filters_the_whole_object_text_raster_again_after_a_pan() { + use vectorcraft_doc::NodeKind; + use vectorcraft_doc::text::{CharStyle, TextObject}; + + let _fonts = fonts_steady(); + let mut d = Document::new(100.0, 100.0); + let white = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let style = CharStyle { font_family: "Source Sans 3".into(), size: 20.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(270.013, 180.017), "Hm", style)))); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(text)]); + group.appearance.effects = vec![Effect { id: "blur.radial".into(), params: json!({"amount": 1, "quality": "draft"}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, group).unwrap(); + let art = RenderOptions { background: Some([255, 255, 255, 255]), anti_alias: crate::AntiAlias::Art, ..Default::default() }; + let snapped = RenderOptions { anti_alias: crate::AntiAlias::Type, ..art.clone() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-280.0, -175.0)); + with_fonts_unchanged(|| { + let unchanged = Renderer::new().render(&d, 1280, 800, view(40.0), &art).pixels; + let fresh = Renderer::new().render(&d, 1280, 800, view(40.0), &snapped).pixels; + assert!(fresh != unchanged, "Art and Type anti-aliasing draw different text pixels"); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &art); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let pixels = r.render(&d, 1280, 800, view(40.0), &snapped).pixels; + assert!(pixels == fresh, "changing anti-aliasing mode filters the text again after a whole-pixel pan"); + }); +} + +/// A whole-object raster gives way to its view copy when the cache budget cannot hold both. +/// The same view draws the copy again without filtering the content. +#[test] +fn a_lower_resolution_whole_raster_keeps_its_view_copy_under_the_cache_budget() { + let d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::translate((640.0, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view, &opts); + let _ = r.render(&d, 1280, 800, view, &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.pan.is_some() && kept.k < 1.0, "the whole-object raster is kept at a lower resolution"); + let copy = kept.shown.as_ref().unwrap().1.clone(); + let budget = kept.bytes() - super::entries::raster_bytes(&kept.image); + r.trim_fx_rasters(budget); + assert_eq!(r.pixel_fx.len(), 1); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.view.is_some() && kept.pan.is_none() && kept.shown.is_none(), "the entry holds only its view copy"); + assert_eq!(kept.k, 1.0); + assert!(Arc::ptr_eq(&kept.image, ©), "the copy replaces the whole-object raster"); + let pixels = r.render(&d, 1280, 800, view, &opts).pixels; + assert!(Arc::ptr_eq(&r.pixel_fx.values().next().unwrap().image, ©), "the same view draws the copy without filtering again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view, &opts).pixels, "the copy draws the same pixels as a new renderer"); +} + +/// An older shadow gives way before the newest whole-object raster loses its whole image. +#[test] +fn an_older_shadow_is_evicted_before_the_newest_whole_raster_loses_its_whole_image() { + let shadow_fx = ("stylize.dropShadow", json!({"x": 4, "y": 3, "blur": 2, "opacity": 80})); + let shadow = doc_with(Rect::new(20.0, 20.0, 40.0, 40.0), Color::BLACK, vec![shadow_fx]); + let d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::translate((640.0, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&shadow, 200, 200, Affine::scale(2.0), &opts); + assert_eq!(r.shadows.len(), 1, "the first frame keeps a shadow"); + let _ = r.render(&d, 1280, 800, view, &opts); + assert_eq!(r.pixel_fx.len(), 1); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.pan.is_some() && kept.k < 1.0 && kept.shown.is_some(), "the whole raster holds its view copy"); + assert!(r.shadows.values().all(|e| e.stamp < kept.stamp), "the shadow is older than the whole raster"); + let image = kept.image.clone(); + let budget = kept.bytes(); + assert!(r.shadows.values().all(|e| e.bytes() > 0), "the shadow and the whole raster together exceed the budget"); + r.trim_fx_rasters(budget); + assert!(r.shadows.is_empty(), "the older shadow is evicted first"); + assert_eq!(r.pixel_fx.len(), 1); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.pan.is_some() && kept.view.is_none(), "the newest raster stays whole"); + assert!(Arc::ptr_eq(&kept.image, &image), "the newest raster keeps its whole image"); + assert!(kept.shown.is_some(), "the newest raster keeps its view copy"); + assert!(kept.bytes() <= budget, "the remaining entry fits the budget"); +} + +/// An older whole raster and its view copy give way before a newer whole raster is reduced. A +/// frame's start holds the previous frame's rasters, so the test marks one of two rasters older. +#[test] +fn an_older_whole_raster_is_evicted_before_a_newer_whole_raster_is_reduced() { + let mut d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::BLACK, vec![("sketch.tornEdges", json!({}))]); + let next = doc_with(Rect::new(300.0, 100.0, 500.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let mut n = (**next.layers[0].children().unwrap().first().unwrap()).clone(); + n.id = d.alloc_id(); + d.insert(Some(d.layers[0].id), 0, n).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::translate((640.0, 400.0)) * Affine::scale(64.0) * Affine::translate((-300.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view, &opts); + assert_eq!(r.pixel_fx.len(), 2, "the view shows both objects"); + assert!(r.pixel_fx.values().all(|e| e.pan.is_some() && e.shown.is_some()), "both whole rasters hold view copies"); + let older_stamp = r.stamp - 1; + if let Some(e) = r.pixel_fx.values_mut().next() { + e.stamp = older_stamp; + } + let old = r.pixel_fx.values().find(|e| e.stamp == older_stamp).unwrap(); + let kept = r.pixel_fx.values().find(|e| e.stamp > older_stamp).unwrap(); + let newest_stamp = kept.stamp; + let image = kept.image.clone(); + let copy = kept.shown.as_ref().unwrap().1.clone(); + let budget = kept.bytes(); + assert!(old.bytes() > super::entries::raster_bytes(&old.image), "reducing the older raster leaves the cache over budget"); + r.trim_fx_rasters(budget); + assert_eq!(r.pixel_fx.len(), 1, "the older entry is evicted"); + let kept = r.pixel_fx.values().next().unwrap(); + assert_eq!(kept.stamp, newest_stamp); + assert!(kept.pan.is_some() && kept.view.is_none(), "the newer raster stays whole"); + assert!(Arc::ptr_eq(&kept.image, &image), "the newer raster keeps its whole image"); + assert!(Arc::ptr_eq(&kept.shown.as_ref().unwrap().1, ©), "the newer raster keeps its view copy"); + assert!(kept.bytes() <= budget, "the remaining entry fits the budget"); +} + +/// A whole raster is reduced before a shadow drawn in the same frame is evicted. +#[test] +fn a_whole_raster_is_reduced_before_a_shadow_of_the_same_stamp_is_evicted() { + let shadow_fx = ("stylize.dropShadow", json!({"x": 0.25, "y": 0.25, "blur": 0.5, "opacity": 80})); + let shadow = doc_with(Rect::new(292.0, 174.0, 293.0, 175.0), Color::BLACK, vec![shadow_fx]); + let mut d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let mut n = (**shadow.layers[0].children().unwrap().first().unwrap()).clone(); + n.id = d.alloc_id(); + d.insert(Some(d.layers[0].id), 0, n).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::translate((640.0, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view, &opts); + assert_eq!(r.shadows.len(), 1); + assert_eq!(r.pixel_fx.len(), 1); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.pan.is_some() && kept.shown.is_some(), "the whole raster holds its view copy"); + let shadow = r.shadows.values().next().unwrap(); + assert_eq!(shadow.stamp, kept.stamp, "both effects are drawn in the same frame"); + let copy = kept.shown.as_ref().unwrap().1.clone(); + let budget = shadow.bytes() + kept.bytes() - super::entries::raster_bytes(&kept.image); + assert!(shadow.bytes() > 0, "the shadow occupies cache space"); + r.trim_fx_rasters(budget); + assert_eq!(r.shadows.len(), 1, "the shadow stays cached"); + assert_eq!(r.pixel_fx.len(), 1, "the reduced raster stays cached"); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.view.is_some() && kept.pan.is_none() && kept.shown.is_none(), "the entry holds only its view copy"); + assert_eq!(kept.k, 1.0); + assert!(Arc::ptr_eq(&kept.image, ©), "the copy replaces the whole raster"); + assert!(kept.bytes() + r.shadows.values().map(|e| e.bytes()).sum::() <= budget, "both entries fit the budget"); +} + #[test] fn a_drag_glow_fallback_cannot_be_spliced_into_a_still_frame() { let doc = doc_with( @@ -2241,6 +3016,56 @@ fn photoshop_filters_on_content_larger_than_the_budget() { } } +/// Glowing Edges scales every edge by the strongest one in the object, so a zoomed-in frame draws +/// a point's glow as the whole object draws it. The object is a white 4 × 80 pt bar beside +/// stripes 0.5 pt wide and 1 pt apart, whose edges lie close together and glow strongest, on +/// black. At 400 % the whole object fits the pixel budget; at 6400 % a 200 × 200 view shows only +/// the bar's left edge, and the stripes lie beyond what the effect reads around the view. The pans +/// move the view 10 and 20 pixels, the second within the margin a raster made again at the same +/// zoom keeps, which reaches the stripes. +#[test] +fn glowing_edges_zoomed_in_glow_as_bright_as_in_the_whole_object() { + use vectorcraft_geom::{PathData, SubPath}; + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| { + SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true) + }; + let mut subpaths = vec![rect(10.0, 10.0, 14.0, 90.0)]; + subpaths.extend((0..30).map(|i| rect(16.0 + f64::from(i), 10.0, 16.5 + f64::from(i), 90.0))); + let mut d = Document::new(100.0, 100.0); + let mut ap = Appearance::basic(Paint::solid(Color::rgb(1.0, 1.0, 1.0)), Paint::None, 0.0); + ap.effects = + vec![Effect { id: "stylize.glowingEdges".into(), params: json!({"edgeWidth": 1, "edgeBrightness": 6, "smoothness": 1}), visible: true }]; + let n = Node::path(d.alloc_id(), PathData::new(subpaths), ap); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let opts = RenderOptions { background: Some([0, 0, 0, 255]), ..Default::default() }; + // Just inside the bar's left edge. + let at = Point::new(10.125, 50.0); + let glow = |img: &Rendered, view: Affine| { + let p = view * at; + img.pixel(p.x.floor() as u32, p.y.floor() as u32)[0] + }; + let whole_view = Affine::scale(4.0); + let mut whole = Renderer::new(); + let whole_img = whole.render(&d, 400, 400, whole_view, &opts); + assert_eq!(whole.stats.view_sized, 0, "at 400 % the whole object is one raster"); + let whole = glow(&whole_img, whole_view); + let zoomed = |dx: f64| Affine::translate((100.0 - dx, 100.0)) * Affine::scale(64.0) * Affine::translate((-at.x, -at.y)); + let mut r = Renderer::new(); + let mut seen = vec![]; + for dx in [0.0, 10.0, 20.0] { + let view = zoomed(dx); + let panned = glow(&r.render(&d, 200, 200, view, &opts), view); + let fresh = glow(&Renderer::new().render(&d, 200, 200, view, &opts), view); + seen.push((dx, panned, fresh)); + assert!(panned.abs_diff(fresh) <= 2, "panned {dx} px, the frame draws the glow a fresh renderer draws: {seen:?}"); + } + assert!(r.stats.view_sized > 0, "at 6400 % the object is over the pixel budget"); + for (dx, panned, _) in &seen { + assert!(panned.abs_diff(whole) <= 24, "panned {dx} px, the glow is as bright as the whole object's {whole}: {seen:?}"); + } +} + /// #5308: an image's Inner Glow follows its visible pixels, not its frame. A 40 × 40 image whose /// left half is transparent and right half opaque black, on a black page, with a white glow from /// the edges: the transparent half stays black, and the glow lights the opaque half's left edge diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index 75d783e8a8..bc8423a2e5 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -201,6 +201,7 @@ fn rasterize_as( // A tile drawn for a proof that preserves the colors' numbers shows its images through that // proof too. let plates = crate::proof::ink_plate_lut(ink, doc); + let hidden_inputs = Frame::hidden_inputs(&opts); for o in def.offsets_covering(region) { let v = view * def.instance_xf(o); let frame = Frame { @@ -212,6 +213,7 @@ fn rasterize_as( visible: v.inverse().transform_rect_bbox(px_rect), px: 1.0 / v.determinant().abs().sqrt().max(1e-12), opts: &opts, + hidden_inputs, ink, output: v, plates: plates.as_deref(), diff --git a/crates/render/src/placed_document.rs b/crates/render/src/placed_document.rs index fab8122af4..ec0d55ac48 100644 --- a/crates/render/src/placed_document.rs +++ b/crates/render/src/placed_document.rs @@ -550,6 +550,11 @@ fn mean_scale(a: Affine) -> f64 { a.determinant().abs().sqrt() } +/// Whether frame `f` allows placed documents to draw from progressive bitmaps. +pub(crate) fn progressive_bitmaps(f: &Frame) -> bool { + f.opts.progressive_placed && f.ink == Ink::Display && !f.opts.outline && f.opts.proof.is_none() && !f.opts.overprint_preview +} + impl Renderer { /// Draw placed document `p` in frame `f`: from a cached bitmap on screen, else exactly; in /// Outline mode without Document Setup → Show Images in Outline Mode, its box crossed from @@ -558,8 +563,7 @@ impl Renderer { if self.crosses_placed(f) { return self.draw_crossed_placed(ctx, f, p); } - let plain = f.ink == Ink::Display && !f.opts.outline && f.opts.proof.is_none() && !f.opts.overprint_preview; - if f.opts.progressive_placed && plain && depth() == 0 && self.draw_placed_bitmap(ctx, f, p) { + if progressive_bitmaps(f) && depth() == 0 && self.draw_placed_bitmap(ctx, f, p) { return; } let Some(blob) = f.doc.images.get(&p.key) else { return }; diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index c2a10b37a4..692d7d3fbc 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -225,7 +225,21 @@ impl Renderer { let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; let plates = proof::plate_lut(opts, doc); - let frame = Frame { mt: threads > 0, patch, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() }; + let hidden_inputs = Frame::hidden_inputs(opts); + let frame = Frame { + mt: threads > 0, + patch, + doc, + symbols: &symbols, + view, + visible, + px, + opts, + hidden_inputs, + ink: screen, + output, + plates: plates.as_deref(), + }; let _crossed = self.cross_placed(&frame); self.begin_frame(); // View Opacity Mask: the mask's coverage in greyscale instead of the artwork. @@ -549,7 +563,9 @@ impl Renderer { ctx.set_aliasing_threshold(opts.anti_alias.threshold()); let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; - let frame = Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; + let hidden_inputs = Frame::hidden_inputs(opts); + let frame = + Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, hidden_inputs, ink: Ink::Display, output, plates: None }; let raster = std::mem::replace(&mut self.raster, raster_settings(opts)); let _crossed = self.cross_placed(&frame); self.begin_frame(); diff --git a/crates/render/src/tests/bitmapglyphs.rs b/crates/render/src/tests/bitmapglyphs.rs index d1a96458ae..ebe7756623 100644 --- a/crates/render/src/tests/bitmapglyphs.rs +++ b/crates/render/src/tests/bitmapglyphs.rs @@ -98,6 +98,7 @@ fn rasters_of_type_follow_image_smoothing() { visible: vectorcraft_geom::Rect::new(0.0, 0.0, 160.0, 160.0), px: 1.0, opts: &opts, + hidden_inputs: Frame::hidden_inputs(&opts), ink: crate::ink::Ink::Display, output: Affine::IDENTITY, plates: None, diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index d7606f3094..57340de555 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -575,6 +575,128 @@ fn on_screen_a_placed_document_shows_a_placeholder_then_its_bitmap() { } } +/// A group with a whole-object effect drawn while its placed document showed a placeholder +/// filters its content again with the bitmap after a pan by whole pixels. +#[test] +fn a_ready_placed_bitmap_filters_the_whole_object_raster_again_after_a_pan() { + let _serial = serial(); + vectorcraft_doc::placed_document::set_loader(gated_blue_page); + let mut d = Document::new(100.0, 100.0); + let key = "whole-object-preview-1"; + d.images.insert(key.into(), ImageBlob::new("application/json", b"blue whole-object preview".to_vec())); + let white = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let placed = placed_node(d.alloc_id().0, key, 40.0, 20.0, Affine::translate((280.0, 170.0)) * Affine::scale(0.5)); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(placed)]); + group.appearance.effects = + vec![vectorcraft_doc::Effect { id: "blur.radial".into(), params: serde_json::json!({"amount": 1, "quality": "draft"}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, group).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), progressive_placed: true, ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-290.0, -175.0)); + let gate = shut_gate(); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let image = &r.pixel_fx.values().next().unwrap().image; + assert!( + image.width() > 1280 && image.height() > 800 && f64::from(image.width()) < 200.0 * 64.0, + "the group keeps a lower-resolution whole-object effect raster" + ); + let placeholder = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + drop(gate); + settle(); + let fresh = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(fresh != placeholder, "the ready placed bitmap changes the effect's pixels"); + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(pixels == fresh, "a ready placed bitmap filters the content again after a whole-pixel pan"); +} + +/// A group with a whole-object effect that holds a placed document's placeholder filters its +/// content again when Overprint Preview turns on and the view pans by whole pixels before the +/// bitmap is ready. +#[test] +fn overprint_preview_filters_the_whole_object_raster_again_after_a_pan() { + let _serial = serial(); + vectorcraft_doc::placed_document::set_loader(gated_blue_page); + let mut d = Document::new(100.0, 100.0); + let key = "whole-object-overprint-preview-1"; + d.images.insert(key.into(), ImageBlob::new("application/json", b"blue whole-object overprint preview".to_vec())); + let white = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let placed = placed_node(d.alloc_id().0, key, 40.0, 20.0, Affine::translate((280.0, 170.0)) * Affine::scale(0.5)); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(placed)]); + group.appearance.effects = + vec![vectorcraft_doc::Effect { id: "blur.radial".into(), params: serde_json::json!({"amount": 1, "quality": "draft"}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, group).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), progressive_placed: true, ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-290.0, -175.0)); + let gate = shut_gate(); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let placeholder = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + let opts = RenderOptions { overprint_preview: true, ..opts }; + let fresh = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(fresh != placeholder, "Overprint Preview draws the placed art before its bitmap is ready"); + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(pixels == fresh, "Overprint Preview filters the content again after a whole-pixel pan"); + drop(gate); + settle(); +} + +/// A group with a whole-object effect that holds only an ordinary image keeps its raster after a +/// placed document's bitmap in another document is ready and the view pans by whole pixels. +#[test] +fn an_ordinary_image_keeps_its_whole_object_raster_when_a_placed_bitmap_elsewhere_is_ready() { + let _serial = serial(); + let elsewhere = doc("ordinary-image-unrelated-preview-1"); + let mut d = Document::new(100.0, 100.0); + let raw = [0u8, 0, 255, 255].repeat(40 * 20); + let blue = craft_image_codecs::Image::from_raw(40, 20, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, raw).unwrap(); + let png = craft_image_codecs::encode(&blue, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + let key = "whole-object-ordinary-image-1"; + d.images.insert(key.into(), ImageBlob::new("image/png", png.to_vec())); + let image = vectorcraft_doc::ImageObject { + key: key.into(), + width: 40, + height: 20, + xf: Affine::translate((10.0, 10.0)) * Affine::scale(2.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image))); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(image)]); + group.appearance.effects = + vec![vectorcraft_doc::Effect { id: "blur.radial".into(), params: serde_json::json!({"amount": 1, "quality": "draft"}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, group).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), progressive_placed: true, ..Default::default() }; + let gate = shut_gate(); + let mut r = Renderer::new(); + let _ = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + let kept = r.pixel_fx.values().next().unwrap().image.clone(); + let _ = r.render(&d, 100, 100, Affine::translate((8.0, 0.0)), &opts); + assert!(Arc::ptr_eq(&kept, &r.pixel_fx.values().next().unwrap().image), "a whole-pixel pan keeps the ordinary image's effect raster"); + let generation = placed_document::generation(); + render(&elsewhere, true); + assert!(placed_document::pending_for("ordinary-image-unrelated-preview-1"), "the unrelated placed bitmap waits for the gate"); + drop(gate); + settle(); + assert!(placed_document::generation() > generation, "the unrelated placed bitmap becomes ready"); + let _ = r.render(&d, 100, 100, Affine::translate((16.0, 0.0)), &opts); + assert!( + Arc::ptr_eq(&kept, &r.pixel_fx.values().next().unwrap().image), + "an unrelated ready placed bitmap preserves the ordinary image's effect raster after a whole-pixel pan" + ); +} + #[test] fn a_bitmap_that_panics_while_made_on_the_drawing_thread_stops_being_pending() { let _serial = serial(); diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index ecab89c083..55961d0e06 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -48,6 +48,12 @@ write-fonts = "0.48" # The craft-fonts face types of the tables `build.rs` writes (`CRAFT_FONTS`, and `SERVED_FONTS` on the web). craft-fonts-build = { workspace = true } +[target.'cfg(windows)'.dependencies] +# The fonts registered in the registry, compared by the font database's change check while the +# font catalog's own check leaves them out (src/fontdb/dirs.rs); MIT OR Apache-2.0, already in the +# build through the font catalog. +windows-registry = "0.6" + [build-dependencies] # Embeds the craft-fonts faces (`Embed::write`) and, for the web, writes the served ones (`Embed::serve`). craft-fonts-build = { workspace = true } diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 80d1230994..b55e9fe937 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -46,12 +46,13 @@ use cache::GlyphCache; use cache::{CanonicalNames, GlyphColours, GlyphImages}; pub use composite::{CompositeCoverage, LentCompositeFonts}; use craft::font_catalog::Catalog; -#[cfg(test)] -pub(crate) use dirs::sfnt_of; +pub use db::FontWatch; pub use dirs::{ - PlatformFontFiles, app_font_dir, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, system_font_dirs, - user_font_dirs, + PlatformFontFiles, app_font_dir, set_app_font_dir, set_platform_font_files, set_platform_font_files_complete, set_user_font_dirs, + set_user_font_dirs_confined, system_font_dirs, user_font_dirs, }; +#[cfg(test)] +pub(crate) use dirs::{REGISTERED_IN_TESTS, sfnt_of, uses_font_service}; use face::Instances; pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat}; @@ -100,11 +101,12 @@ pub struct FontDb { colours: Mutex, /// The installed fonts: the system font scan's faces, found by any of their names /// ([`FontDb::catalog`]). Lookups by family name wait for its first scan, so what they find - /// never depends on what ran before them. The bundled faces join it on the first call of - /// [`FontDb::catalog`], so its faces are read through that call. + /// never depends on what ran before them. It also holds the bundled faces, added when the + /// database is made and read from the binary in place. catalog: Arc, - /// The bundled faces were added to [`Self::catalog`]. - bundled_cataloged: std::sync::Once, + /// The registry's fonts as the catalog's last scan saw them, when the catalog does not compare + /// them itself ([`FontDb::installed_fonts_changed`]). + registered: Option>, /// Fonts files carried for their type ([`vectorcraft_doc::FileFonts`]): apart from the faces, /// so no family name, font menu, fallback or PostScript name lookup finds them. pub(super) file_faces: RwLock, @@ -399,14 +401,25 @@ mod bundled_catalog_tests { } #[test] - fn the_bundled_fonts_join_the_catalog_when_it_is_first_read() { + fn the_bundled_fonts_are_in_the_catalog_from_the_start() { let db = FontDb::with_font_dirs(Vec::new()); assert!(!db.read_faces().is_empty(), "the database draws with its bundled faces from the start"); - assert_eq!(bundled_in_catalog(&db.catalog), 0, "making the database copies no bundled font into the catalog"); + let added = bundled_in_catalog(&db.catalog); + assert!(added > 0, "making the database adds the bundled fonts to the catalog"); + // The catalog reads each bundled face from the bytes in the binary, not from a copy. + let embedded: Vec<*const u8> = super::face::BUNDLED.iter().map(|b| b.as_ptr()).collect(); + for face in db.catalog.faces().iter().filter(|f| f.source == craft::font_catalog::Source::Bundled) { + let data = db.catalog.face_data(face).expect("a bundled face's bytes"); + let ptr = data.bytes().as_ptr(); + assert!( + embedded.contains(&ptr) || crate::craft_fonts::document_fonts().iter().any(|f| f.bytes.as_ptr() == ptr), + "{} {} is read from a copy of its font file", + face.family, + face.style + ); + } // A lookup that only the catalog answers finds a bundled face. assert_eq!(db.by_postscript_name("SourceSans3-Bold"), Some(("Source Sans 3".to_string(), "Bold".to_string()))); - let added = bundled_in_catalog(&db.catalog); - assert!(added > 0, "the first read of the catalog adds the bundled fonts"); assert!(db.catalog().families().iter().any(|f| f == "Inter"), "font pickers list a bundled family"); assert_eq!(bundled_in_catalog(db.catalog()), added, "later reads add them no second time"); } diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index b65dbab4f2..976e2d73c3 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -1,10 +1,10 @@ -use craft::font_catalog::{Catalog, FontEnv, Limits, Os, Source}; +use craft::font_catalog::{Catalog, FontEnv, Os, Source}; use super::build::make_face; use super::cache::{CanonicalNames, GlyphCache}; #[cfg(not(target_arch = "wasm32"))] use super::dirs::confined_font_dirs; -use super::dirs::system_catalog; +use super::dirs::{RegisteredFonts, system_catalog}; use super::face::{BUNDLED, FontBytes, FontFace, Instances}; #[cfg(not(target_arch = "wasm32"))] use super::names::SysFallback; @@ -32,14 +32,14 @@ impl FontDb { /// A database holding the bundled fonts, whose system font scan reads `font_dirs` (folders, /// read with their subfolders, and font files) and nothing else. pub fn with_font_dirs(font_dirs: Vec) -> Self { - Self::new(font_dirs_catalog(font_dirs)) + Self::new((font_dirs_catalog(font_dirs), None)) } /// [`FontDb::with_font_dirs`] whose every scan also calls `lister` before it reads a folder, /// for tests that hold a scan until they let it go on. #[cfg(test)] pub(crate) fn with_font_dirs_and_lister(font_dirs: Vec, lister: craft::font_catalog::Lister) -> Self { - Self::new(font_dirs_catalog(font_dirs).with_lister(lister)) + Self::new((font_dirs_catalog(font_dirs).with_lister(lister), None)) } /// Same scan paths as [`FontDb::global`] (platform lister and font folders), for tests. @@ -48,7 +48,15 @@ impl FontDb { Self::new(system_catalog()) } - fn new(catalog: Catalog) -> Self { + /// [`FontDb::for_system_scan_test`] as with a complete platform lister + /// ([`super::set_platform_font_files_complete`]): the scan does not ask the platform's font service. + /// Its lister lists no platform files, so another test's process-wide lister does not change what it scans. + #[cfg(test)] + pub(crate) fn for_complete_lister_scan_test() -> Self { + Self::new(super::dirs::system_catalog_with(false, Vec::new)) + } + + fn new((catalog, registered): (Catalog, Option>)) -> Self { #[cfg(not(target_arch = "wasm32"))] catalog.set_confined_dirs(confined_font_dirs()); let mut faces = Vec::new(); @@ -58,6 +66,11 @@ impl FontDb { faces.push(Arc::new(f)); } } + // The catalog reads the bytes in place, so font pickers list the bundled faces without a + // second copy of them in memory. + if let Err(e) = catalog.add_static(data, Source::Bundled) { + log::warn!("a bundled font is not in the font catalog: {e}"); + } } Self { faces: RwLock::new(faces), @@ -65,7 +78,7 @@ impl FontDb { images: Mutex::new(GlyphCache::default()), colours: Mutex::new(GlyphCache::default()), catalog: Arc::new(catalog), - bundled_cataloged: std::sync::Once::new(), + registered, file_faces: RwLock::new(super::FileFaces::default()), canonical_cache: Mutex::new(CanonicalNames::new()), #[cfg(not(target_arch = "wasm32"))] @@ -121,19 +134,9 @@ impl FontDb { /// The installed fonts this database finds by name, shared with the framework's font menus and /// pickers. Its lookups wait for its first scan ([`FontDb::scan_in_background`]). /// - /// The first call adds the bundled fonts to it as [`Source::Bundled`] faces, so font pickers - /// list them. A run that never looks a font up in the catalog, such as exporting a file without - /// type, does not hold the catalog's copies of their bytes. - // The catalog keeps its own copy of the bytes it is given. Adding the bundled fonts on first use - // can go once the catalog takes static bytes without copying them (craft-libs#4888). + /// It holds the bundled fonts as [`Source::Bundled`] faces, read from the binary in place, so + /// font pickers list them. pub fn catalog(&self) -> &Arc { - self.bundled_cataloged.call_once(|| { - for data in bundled_fonts() { - if let Err(e) = self.catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default()) { - log::warn!("a bundled font is not in the font catalog: {e}"); - } - } - }); &self.catalog } @@ -420,16 +423,61 @@ impl FontDb { } /// Whether fonts were installed or removed since the last scan (a font folder it read - /// changed, or a new one is to be read), for [`FontDb::load_system_fonts`] to catalog them. - /// Costs a look at each folder the scan read, not a scan. `false` before the first scan and on - /// wasm. + /// changed, a new one is to be read, or on Windows the registry's font list changed), for + /// [`FontDb::load_system_fonts`] to catalog them. Costs a look at each folder the scan read, + /// not a scan. `false` before the first scan and on wasm. pub fn installed_fonts_changed(&self) -> bool { #[cfg(not(target_arch = "wasm32"))] - { - self.catalog.installed_fonts_changed() - } + let folders = self.catalog.installed_fonts_changed(); #[cfg(target_arch = "wasm32")] - false + let folders = false; + // No catalog leaves the registry to the database on wasm, where the font service is on. + folders || (self.catalog.is_ready() && self.registered.as_ref().is_some_and(|r| r.changed())) + } + + /// Rescans the catalog when [`FontDb::installed_fonts_changed`] says so, registry included. + /// Returns whether it rescanned. One look of [`FontDb::watch`]. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn rescan_if_installed_fonts_changed(&self) -> bool { + let changed = self.installed_fonts_changed(); + if changed { + self.catalog().rescan(); + } + changed + } + + /// Looks for installed and removed fonts every `interval` on a thread of its own, with + /// [`FontDb::installed_fonts_changed`], which also compares the registry's fonts when the + /// catalog's own check leaves them out. When they changed, it rescans the catalog and calls + /// `on_change`. Stops when the returned [`FontWatch`] is dropped. + #[cfg(not(target_arch = "wasm32"))] + pub fn watch(&'static self, interval: std::time::Duration, on_change: impl Fn() + Send + 'static) -> FontWatch { + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let flag = Arc::clone(&stop); + let _ = std::thread::Builder::new().name("font-db-watch".into()).spawn(move || { + loop { + std::thread::sleep(interval); + if flag.load(Ordering::Relaxed) { + return; + } + if self.rescan_if_installed_fonts_changed() { + on_change(); + } + } + }); + FontWatch { stop } + } +} + +/// Stops a `FontDb::watch` when dropped. +#[must_use = "dropping a FontWatch stops it"] +pub struct FontWatch { + stop: Arc, +} + +impl Drop for FontWatch { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); } } diff --git a/crates/text/src/fontdb/dirs.rs b/crates/text/src/fontdb/dirs.rs index 51e16807a0..dfde291368 100644 --- a/crates/text/src/fontdb/dirs.rs +++ b/crates/text/src/fontdb/dirs.rs @@ -47,6 +47,22 @@ pub fn set_platform_font_files(list: PlatformFontFiles) { let _ = list; } +/// [`set_platform_font_files`] for a lister that lists every font the platform's font service +/// lists. [`FontDb::global`]'s scan then reads the lister's files and does not also ask the font +/// service, which opens every installed face a second time. Only the first lister set counts. +pub fn set_platform_font_files_complete(list: PlatformFontFiles) { + #[cfg(not(target_arch = "wasm32"))] + if PLATFORM_FONT_FILES.set(list).is_ok() { + LISTER_IS_COMPLETE.store(true, std::sync::atomic::Ordering::Relaxed); + } + #[cfg(target_arch = "wasm32")] + let _ = list; +} + +/// Whether the lister was set with [`set_platform_font_files_complete`]. +#[cfg(not(target_arch = "wasm32"))] +static LISTER_IS_COMPLETE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + /// The most files [`platform_font_files`] takes from the lister. #[cfg(not(target_arch = "wasm32"))] const MAX_PLATFORM_FILES: usize = 1 << 16; @@ -64,12 +80,99 @@ fn platform_font_files() -> Vec { Vec::new() } -/// The catalog of [`FontDb::global`]: the platform's font folders and font service, the font -/// store, VectorCraft's own folders ([`app_dirs`]) and the files [`set_platform_font_files`] lists. -pub(super) fn system_catalog() -> Catalog { - let catalog = Catalog::new(FontEnv::from_process()).with_lister(Arc::new(platform_font_files)); +/// Whether [`system_catalog`] asks the platform's font service: not when the lister was set with +/// [`set_platform_font_files_complete`]. +pub(crate) fn uses_font_service() -> bool { + #[cfg(not(target_arch = "wasm32"))] + return !LISTER_IS_COMPLETE.load(std::sync::atomic::Ordering::Relaxed); + #[cfg(target_arch = "wasm32")] + true +} + +/// The catalog of [`FontDb::global`]: the platform's font folders, the platform's font service +/// ([`uses_font_service`]), the font store, VectorCraft's own folders ([`app_dirs`]) and the files +/// [`set_platform_font_files`] lists, with the registry's fonts its own change check leaves out. +pub(super) fn system_catalog() -> (Catalog, Option>) { + system_catalog_with(uses_font_service(), platform_font_files) +} + +/// [`system_catalog`], asking the platform's font service when `service` and reading the files +/// `platform` lists. Without the service the catalog neither reads nor compares the fonts the +/// Windows registry lists, so its lister adds them to the scan and the database compares them +/// ([`RegisteredFonts`]). +pub(super) fn system_catalog_with(service: bool, platform: fn() -> Vec) -> (Catalog, Option>) { + let registered = (!service).then(|| Arc::new(RegisteredFonts::default())); + let seen = registered.clone(); + let lister = move || { + let mut files = platform(); + if let Some(seen) = &seen { + files.extend(seen.record()); + } + files + }; + let catalog = Catalog::new(FontEnv::from_process()).with_font_service(service).with_lister(Arc::new(lister)); catalog.set_app_dirs(app_dirs()); - catalog + (catalog, registered) +} + +/// The font files the Windows registry lists by full path, as the last scan of a catalog whose +/// font service is off read them. That catalog does not compare them, so without this a font +/// registered from a folder no scan has read waits for a manual rescan. Remove it once the pinned +/// font catalog has `Catalog::with_registry` (storytold/craft-libs#5676) and [`system_catalog_with`] +/// turns that on. +#[derive(Default)] +pub(super) struct RegisteredFonts(super::Mutex>>); + +impl RegisteredFonts { + /// Note the registry's list for the scan that is starting, and return it for the scan to read. + fn record(&self) -> Vec { + let now = registered_font_files(); + *self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(now.clone()); + now + } + + /// Whether the registry's list changed since the last scan noted it: `false` before one. The + /// registry is read before the lock is taken, so a scan's [`RegisteredFonts::record`] does not + /// wait for the read. + pub(super) fn changed(&self) -> bool { + let now = registered_font_files(); + self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref().is_some_and(|seen| *seen != now) + } +} + +#[cfg(test)] +thread_local! { + /// What [`registered_font_files`] gives on this thread in tests, in place of the registry. + pub(crate) static REGISTERED_IN_TESTS: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// The full paths the registry lists for the machine's and the current user's fonts, sorted and +/// each once, as the font catalog reads them. Bare file names (files in the Windows font folder) +/// are left out: the scan reads that folder. Empty elsewhere than on Windows. +fn registered_font_files() -> Vec { + #[cfg(test)] + if let Some(files) = REGISTERED_IN_TESTS.with_borrow(Clone::clone) { + return files; + } + #[cfg(windows)] + { + const MAX_REGISTERED: usize = 1 << 16; + const KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Fonts"; + use windows_registry::{CURRENT_USER, LOCAL_MACHINE}; + let mut files: Vec = [LOCAL_MACHINE, CURRENT_USER] + .into_iter() + .filter_map(|root| root.open(KEY).ok()) + .flat_map(|key| key.values().map(|vs| vs.filter_map(|(_, v)| String::try_from(v).ok()).collect::>()).unwrap_or_default()) + .take(MAX_REGISTERED) + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .collect(); + files.sort(); + files.dedup(); + files + } + #[cfg(not(windows))] + Vec::new() } /// The folders VectorCraft adds to the platform's: its own Fonts folder ([`set_app_font_dir`]), diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index af85cf99bd..39b8f5aaab 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -45,12 +45,13 @@ pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; pub use file_font::{FILE_FONT_UPEM, FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font}; +pub use fontdb::FontWatch; pub use fontdb::{ CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate, GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, InstalledFace, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat, PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, UnloadedFile, WantedFont, WantedFonts, - app_font_dir, is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, - set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, + app_font_dir, is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_platform_font_files_complete, + set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index d82ca9ae38..420664f17a 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -760,7 +760,9 @@ fn fonts_the_platform_lists_outside_the_font_folders_are_cataloged() { use std::sync::Mutex; static FILES: Mutex> = Mutex::new(Vec::new()); let list = |files: Vec| *FILES.lock().unwrap_or_else(|e| e.into_inner()) = files; - set_platform_font_files(|| FILES.lock().unwrap_or_else(|e| e.into_inner()).clone()); + assert!(crate::fontdb::uses_font_service(), "without a complete lister the scan asks the font service"); + set_platform_font_files_complete(|| FILES.lock().unwrap_or_else(|e| e.into_inner()).clone()); + assert!(!crate::fontdb::uses_font_service(), "with a complete lister the scan does not also ask the font service"); let file = service_font(); std::fs::create_dir_all(file.parent().unwrap()).unwrap(); let _ = std::fs::remove_file(&file); @@ -783,6 +785,46 @@ fn fonts_the_platform_lists_outside_the_font_folders_are_cataloged() { assert_eq!(dirs.iter().filter(|d| **d == file).count(), 1, "{dirs:?}"); } +/// With a complete platform lister the catalog does not compare the fonts the Windows registry +/// lists, so the database does: a font registered from a folder no scan has read is a change, and +/// the scan that follows catalogs it and notes it. +#[test] +fn a_font_registered_since_the_scan_is_a_change_with_a_complete_lister() { + use crate::fontdb::REGISTERED_IN_TESTS; + REGISTERED_IN_TESTS.set(Some(Vec::new())); + let db = FontDb::for_complete_lister_scan_test(); + assert!(!db.installed_fonts_changed(), "nothing to compare with before the first scan"); + db.load_system_fonts(); + assert!(!db.installed_fonts_changed()); + let registered = std::env::temp_dir().join(format!("vc-sysfonts-{}-registered", std::process::id())).join("Registered.ttf"); + std::fs::create_dir_all(registered.parent().unwrap()).unwrap(); + std::fs::write(®istered, renamed_to("SourceSans3-Regular.ttf", "Registry Sans")).unwrap(); + REGISTERED_IN_TESTS.set(Some(vec![registered.clone()])); + assert!(db.installed_fonts_changed(), "a font registered since the scan"); + db.load_system_fonts(); + assert_eq!(db.styles("Registry Sans"), ["Regular"], "the scan reads the font the registry lists"); + assert!(!db.installed_fonts_changed(), "the scan noted the registered font"); + REGISTERED_IN_TESTS.set(None); + let _ = std::fs::remove_dir_all(registered.parent().unwrap()); +} + +/// Each look of the font watch (`FontDb::watch`) uses the database's check, so a font registered +/// from a folder no scan has read rescans while the catalog's own check sees no change. +#[test] +fn the_font_watch_rescans_for_a_font_registered_since_the_scan() { + use crate::fontdb::REGISTERED_IN_TESTS; + REGISTERED_IN_TESTS.set(Some(Vec::new())); + let db = FontDb::for_complete_lister_scan_test(); + db.load_system_fonts(); + assert!(!db.rescan_if_installed_fonts_changed(), "nothing changed since the scan"); + let registered = std::env::temp_dir().join(format!("vc-sysfonts-{}-watched", std::process::id())).join("Registered.ttf"); + REGISTERED_IN_TESTS.set(Some(vec![registered])); + assert!(!db.catalog().installed_fonts_changed(), "the catalog's own check leaves the registry out"); + assert!(db.rescan_if_installed_fonts_changed(), "a font registered since the scan"); + assert!(!db.installed_fonts_changed(), "the watch's rescan noted the registered font"); + REGISTERED_IN_TESTS.set(None); +} + #[test] fn a_resource_fork_gives_up_its_font_files() { let (regular, bold) = (renamed("SourceSans3-Regular.ttf"), renamed("SourceSans3-Bold.ttf")); diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 6ef02bfd11..528578d8b7 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -56,6 +56,8 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool pub struct EyedropperTool { /// Sampling for the selected gradient stop: the tool to switch back to afterwards. stop: Option, + /// Sampling for the selected freeform point: the tool to switch back to afterwards. + point: Option, /// The Type tool's highlighted range while sampling, including its selection overlay. text_selection: crate::text::TypeTool, /// Brush Options › Key Color (Hue Shift): sample into the dialog, then [`Self::stop`]. @@ -567,8 +569,14 @@ impl Tool for EyedropperTool { } Click::Back(back) => { self.stop = None; + self.point = None; vec![Action::SwitchTool(back)] } + Click::SamplePoint(color, _, index, back) => { + self.point = None; + let params = json!({ "index": index, "stroke": !cx.fill_active, "color": color_json(&color), "keepModel": true }); + vec![Action::Exec("paint.freeform.setPoint".into(), params), Action::SwitchTool(back)] + } Click::MeshPoints(id, points, color) => { let params = json!({ "id": id.0, "points": points, "color": color_json(&color), "keepModel": true }); vec![Action::Exec("object.mesh.setPointColor".into(), params)] @@ -605,6 +613,9 @@ impl Tool for EyedropperTool { let mut options = if selected.get("editing").is_some_and(|v| !v.is_null()) { selected } else { json!({}) }; if let Some(o) = options.as_object_mut() { o.insert("stop".into(), json!(self.stop)); + if let Some(back) = &self.point { + o.insert("freeformPoint".into(), json!(back)); + } o.insert("brushKeyColor".into(), json!(self.brush_key_color)); if let Some(binding) = &self.image_trace_ignore_color { o.insert("imageTraceIgnoreColor".into(), binding.clone()); @@ -621,7 +632,18 @@ impl Tool for EyedropperTool { /// Type tool or a tool that picks mesh points. fn set_option(&mut self, key: &str, value: &Value) { match key { - "stop" => self.stop = value.as_str().map(str::to_string), + "stop" => { + self.stop = value.as_str().map(str::to_string); + if self.stop.is_some() { + self.point = None; + } + } + "freeformPoint" => { + self.point = value.as_str().map(str::to_string); + if self.point.is_some() { + self.stop = None; + } + } "brushKeyColor" => self.brush_key_color = value.as_bool().unwrap_or(false), "imageTraceIgnoreColor" => self.image_trace_ignore_color = (!value.is_null()).then(|| value.clone()), "meshPoints" => self.mesh_points = crate::meshedit::points_of(value), @@ -633,7 +655,7 @@ impl Tool for EyedropperTool { fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { use crate::option_check as c; match key { - "stop" => c::string_or_null(key, value), + "stop" | "freeformPoint" => c::string_or_null(key, value), "brushKeyColor" => c::boolean(key, value), "textSelection" => self.text_selection.check_option(key, value), _ => Err(c::unknown(key)), @@ -663,6 +685,9 @@ impl Tool for EyedropperTool { if key != ToolKey::Escape || !self.picking() { return vec![]; } + if let Some(back) = self.point.take() { + return vec![Action::SwitchTool(back)]; + } if let Some(binding) = self.image_trace_ignore_color.take() { let back = self.stop.take().unwrap_or_else(|| "selection".to_string()); return vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "cancel": true })), Action::SwitchTool(back)]; @@ -678,7 +703,7 @@ impl Tool for EyedropperTool { } fn returns_to(&self) -> Option<&str> { - self.stop.as_deref().filter(|_| !self.brush_key_color && self.image_trace_ignore_color.is_none()) + self.point.as_deref().or_else(|| self.stop.as_deref().filter(|_| !self.brush_key_color && self.image_trace_ignore_color.is_none())) } /// Escape is the tool's while a pick is armed, so it switches back and ends nothing else. @@ -697,9 +722,10 @@ enum Click { ImageTrace(Value), /// Brush Options › Key Color: this color, sampled from this object. BrushKeyColor(Color, NodeId), - /// A pick for a stop of the gradient a tool paints with (the Live Paint Bucket's, the Shape - /// Builder's fill) that is no longer selected switches back to that tool unsampled. + /// The pick's target is no longer valid. Return to the previous tool without sampling. Back(String), + /// This color, sampled from this object, goes to the armed freeform point. + SamplePoint(Color, NodeId, usize, String), /// The fill color goes to these points of this selected gradient mesh. MeshPoints(NodeId, Vec, Color), /// `appearance.copyFrom` this source, with `reverse` or `append` or neither. @@ -715,19 +741,28 @@ impl Click { fn object(&self) -> Option { match self { Click::ImageTrace(_) | Click::Back(_) => None, - Click::BrushKeyColor(_, id) | Click::MeshPoints(id, ..) | Click::CopyFrom(id, _) | Click::Sample { source: id, .. } => Some(*id), + Click::BrushKeyColor(_, id) + | Click::SamplePoint(_, id, ..) + | Click::MeshPoints(id, ..) + | Click::CopyFrom(id, _) + | Click::Sample { source: id, .. } => Some(*id), } } } impl EyedropperTool { - /// Is a gradient stop, Brush Key Color or Image Trace Ignore Color pick armed? + /// Is a gradient stop, freeform point, Brush Key Color or Image Trace Ignore Color pick armed? fn picking(&self) -> bool { - self.stop.is_some() || self.brush_key_color || self.image_trace_ignore_color.is_some() + self.stop.is_some() || self.point.is_some() || self.brush_key_color || self.image_trace_ignore_color.is_some() } /// What a click at `p` with `mods` does, or None when it does nothing. fn click(&self, cx: &ToolContext, p: Point, mods: Mods) -> Option { + if let Some(back) = &self.point { + let Some(index) = cx.freeform_point else { return Some(Click::Back(back.clone())) }; + let (color, source) = sample_at(cx, p)?; + return Some(Click::SamplePoint(color, source, index, back.clone())); + } if let Some(binding) = &self.image_trace_ignore_color { return Some(Click::ImageTrace(binding.clone())); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 72657ef6ae..d0953f6e0b 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -87,6 +87,9 @@ craft = { workspace = true, features = ["dialogs", "update", "automation-agents" # The local date and time the status bar's Date and Time readout shows (`chrono::Local`). Already in # Cargo.lock with the time-zone crates `clock` uses. chrono = { workspace = true, features = ["clock"] } +# The digest of each open document's file, which Save compares with the file before asking whether to replace it +# (`src/io/saved_contents.rs`). Already in Cargo.lock (the engine's and the plug-ins' digests). +sha2 = { version = "0.10", default-features = false } [target.'cfg(target_arch = "wasm32")'.dependencies] # The status bar's Date and Time readout reads the page's clock with this crate in the web build. It diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 162d1867ef..5650751445 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -5,12 +5,13 @@ use craft::platform::clipboard::{Clipboard, ClipboardProbe, EventClipboard}; use craft::platform::clock::monotonic_ms; use craft::theme::variant::Tone; use craft::ui::buttons::{ActiveLook, PushButtonLook}; -use craft::ui::choice::ChoiceLook; +use craft::ui::choice::{ChoiceLook, SwatchCorners}; use craft::ui::contract::{Bind, CaptionInk, GlyphColon, LinkLabelInk, LinkLabelUnderline, MoveBandCursor, QuietHeader, SectionRhythm}; -use craft::ui::docking::IconGroupSeparator; +use craft::ui::docking::{FloatingGroupLook, IconGroupSeparator}; use craft::ui::list::{CommandHighlight, ThumbRows}; use craft::ui::menu::{MenuTitleLook, MenuTitlePad}; use craft::ui::patterns::form_dialogs::PresetCardLook; +use craft::ui::primitives::DrawingCursorLook; use craft::ui::runtime::drag::{self, OsFiles}; use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey, WordsOverride, with_env}; use craft::ui::runtime::frame::{FrameInput, FrameOutput}; @@ -167,7 +168,6 @@ impl VectorcraftApp { hover_object: None, grab: None, carry_target: None, - removed_press: false, last_drag: None, escaped_press: false, pressed_at: None, @@ -671,6 +671,7 @@ impl VectorcraftApp { if !self.background.jobs.is_empty() || !self.opening.pending.is_empty() || !self.opening.converting.is_empty() + || io::save::checks_pending(self) || plugin_runs::any_pending(self) || !self.placing.pending.is_empty() || !self.trace_runs.running.is_empty() @@ -712,7 +713,7 @@ impl VectorcraftApp { if ctx.current_pass_index() == 0 && let Some(u) = self.pending_url.take() { - ctx.open_url(egui::OpenUrl::new_tab(u)); + self.open_pending_url(ctx, u); } self.flush_clipboard_out(); self.drain_inbox(); @@ -792,6 +793,7 @@ impl VectorcraftApp { self.handle_input(&ctx); self.ui_frame(ui); self.window_keys(&ctx); + io::save::after_ui(self, &ctx); // What the canvas, a panel, a dialog or a window key changed in this pass reaches // the plug-ins that react to it now, since an idle app draws no further frame; a // line a handler wrote shows in the next one. The handlers' time counts toward the @@ -939,6 +941,9 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print let mut root = RootEnv::new().theme(theme).mode(mode).accent(accent).scale(Scale::new(scaling)).tooltips(prefs.show_tool_tips); // Painted tool cursors grow with UI Scaling only when Scale Cursor Proportional to UI is on. root = root.cursor_follows_zoom(prefs.scale_cursor_with_ui); + // The Selection, Direct Selection and Hand pointers, the drawing crosshairs and the tool cursors draw in black and + // white over the artwork in either interface theme. + root.values.set(DrawingCursorLook::Monochrome); root.sizes = theme::app_sizes(); root.values.set(view::zoom_scheme(print, native_ppp)); root.values.set(if prefs.scrub_numeric_fields { ScrubDrags::LabelOnly } else { ScrubDrags::Off }); @@ -967,6 +972,10 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print // Check boxes, radio buttons and switches that are on take the strong accent with a white mark, sliders fill their // track to the value in the accent, and a dialog's Cancel is a filled button beside its accent answer. root.values.set(ChoiceLook::Strong); + // Color swatches and the Fill and Stroke wells keep square corners, so a small sample shows its whole color. + root.values.set(SwatchCorners::Square); + // Floating panel groups and tool palettes are square palettes with a small shadow. + root.values.set(FloatingGroupLook::Palette); root.values.set(TrackFill::Accent); root.values.set(DialogButtonLook::Filled); // Sections stand apart with production's room around their dividers. diff --git a/crates/ui-egui/src/app/fonts.rs b/crates/ui-egui/src/app/fonts.rs index f327da0b42..4c8f77bdeb 100644 --- a/crates/ui-egui/src/app/fonts.rs +++ b/crates/ui-egui/src/app/fonts.rs @@ -17,9 +17,10 @@ impl VectorcraftApp { // PLAN: hub-w1 calls `watch_fonts` once in `VectorcraftApp::new` (beside `scan_in_background`, app.rs:49) and `follow_fonts` once per frame in `tick` (app.rs:354-359), adds the fields `font_watch: Option` and `fonts_seen: u64` (lib.rs:280-285), makes `FONT_INSTALL_POLL` a `Duration` (state.rs:1585) and drops the `WindowFocused` refresh (app/input.rs:210). impl VectorcraftApp { /// Fonts installed or removed while the app runs are listed without Refresh Font List: the - /// font catalog looks at the font folders every [`FONT_INSTALL_POLL`] on a thread of its own - /// (asking the platform for the fonts font services loaded meanwhile takes tens of milliseconds - /// on Windows, #579), rescans only when they changed, and wakes the app for + /// font database looks at the font folders, and on Windows the registry's font list, every + /// [`FONT_INSTALL_POLL`] on a thread of its own (asking the platform for the fonts font services + /// loaded meanwhile takes tens of milliseconds on Windows, #579), rescans only when they + /// changed, and wakes the app for /// [`Self::follow_fonts`]. Called once, at start; the watch stops with the app. Not on wasm, /// which has no installed fonts. /// @@ -28,7 +29,7 @@ impl VectorcraftApp { #[cfg(not(target_arch = "wasm32"))] { let (ctx, changed) = (ctx.clone(), std::sync::Arc::clone(&self.fonts_changed)); - let watch = vectorcraft_text::FontDb::global().catalog().watch(crate::state::FONT_INSTALL_POLL, move |_| { + let watch = vectorcraft_text::FontDb::global().watch(crate::state::FONT_INSTALL_POLL, move || { changed.store(true, std::sync::atomic::Ordering::Release); ctx.request_repaint(); }); diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index b7b7f5e6ec..aad6f18d42 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -15,6 +15,20 @@ impl VectorcraftApp { } } + /// Open the URL [`Self::open_url`] asked for: a `file:` URL with the host's + /// [`Services::open_file_url`](crate::Services::open_file_url) when it has one, any other URL + /// (and a `file:` URL without that service) as egui's `OpenUrl` in a new tab. + pub(crate) fn open_pending_url(&mut self, ctx: &egui::Context, url: String) { + let file = url.split_once(':').is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("file")); + if file && let Some(open) = self.services.open_file_url.as_mut() { + if let Err(error) = open(&url) { + log::warn!("could not open {url:?}: {error}"); + } + return; + } + ctx.open_url(egui::OpenUrl::new_tab(url)); + } + /// Open `url`, which came from a document (an object's URL attribute), in the browser: /// [`browsable_url`]s only. pub(crate) fn open_document_url(&mut self, url: &str) -> Result<(), String> { @@ -122,3 +136,65 @@ impl VectorcraftApp { } } } + +#[cfg(test)] +mod tests { + use super::VectorcraftApp; + use std::cell::RefCell; + use std::rc::Rc; + + /// An app whose host opens `file:` URLs by recording them in the returned list. + fn app_opening_files() -> (VectorcraftApp, Rc>>) { + let opened = Rc::new(RefCell::new(Vec::new())); + let seen = Rc::clone(&opened); + let services = crate::Services { + open_file_url: Some(Box::new(move |url: &str| { + seen.borrow_mut().push(url.to_owned()); + Ok(()) + })), + ..Default::default() + }; + (VectorcraftApp::new(vectorcraft_engine::Session::new(), services), opened) + } + + /// The URLs the next frame of `app` asked egui to open. + fn opened_in_frame(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + out.platform_output + .commands + .into_iter() + .filter_map(|c| match c { + egui::OutputCommand::OpenUrl(open) => Some(open.url), + _ => None, + }) + .collect() + } + + /// A file the app wrote opens through the host once, outside egui's links, which the UI + /// runtime's link opener would drop; a web link still goes to egui. + #[test] + fn a_written_file_opens_through_the_host_and_a_web_link_through_egui() { + let (mut app, files) = app_opening_files(); + let ctx = crate::testing::ui_context(); + + app.open_url("FILE:///tmp/out.pdf"); + assert!(opened_in_frame(&mut app, &ctx).is_empty(), "the file URL is not handed to egui"); + assert_eq!(*files.borrow(), ["FILE:///tmp/out.pdf"], "the host opens the file URL"); + assert!(opened_in_frame(&mut app, &ctx).is_empty()); + assert_eq!(files.borrow().len(), 1, "a frame without a request opens nothing again"); + + app.open_link("help.discord"); + assert_eq!(opened_in_frame(&mut app, &ctx), ["https://discord.gg/artcraft"]); + assert_eq!(files.borrow().len(), 1, "a web link does not reach the file opener"); + } + + /// Without the host's file opener (the web build), a `file:` URL goes to egui as before. + #[test] + fn without_a_file_opener_a_file_url_goes_to_egui() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + app.open_url("file:///tmp/out.svg"); + assert_eq!(opened_in_frame(&mut app, &ctx), ["file:///tmp/out.svg"]); + } +} diff --git a/crates/ui-egui/src/app/tests.rs b/crates/ui-egui/src/app/tests.rs index a3682de34c..7e1636154b 100644 --- a/crates/ui-egui/src/app/tests.rs +++ b/crates/ui-egui/src/app/tests.rs @@ -78,3 +78,39 @@ fn the_close_caption_asks_about_unsaved_documents() { assert_eq!(close_frame(&mut app, &ctx), Some(CloseDecision::Close)); assert!(!asks_about_unsaved(&app), "nothing unsaved, nothing asked"); } + +/// A color swatch fills its well to the corners: every opaque rectangle the well paints has square corners, so a +/// small sample shows its whole color. +#[test] +fn a_color_swatch_paints_a_square_well() { + use craft::theme::Srgba; + use craft::ui::choice::Swatch; + use craft::ui::contract::Show as _; + let mut well = egui::Rect::NOTHING; + let mut out = crate::testing::ui_context().run_ui(Default::default(), |ui| { + well = Swatch::new("Color", Srgba::rgb(0.2, 0.6, 0.4)).show(ui).response.rect; + }); + out.textures_delta.clear(); + let fills: Vec<(egui::Rect, egui::CornerRadius)> = out + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Rect(rect) if rect.fill.a() == 255 && well.expand(1.0).contains_rect(rect.rect) => Some((rect.rect, rect.corner_radius)), + _ => None, + }) + .collect(); + assert!(!fills.is_empty(), "the well paints its color in {well:?}"); + let rounded: Vec<_> = fills.iter().filter(|(_, corners)| *corners != egui::CornerRadius::ZERO).collect(); + assert!(rounded.is_empty(), "the well's corners are square: {rounded:?}"); +} + +/// Floating panel groups and tool palettes take the palette frame, square with a small shadow, not the rounded frame +/// of a floating window. +#[test] +fn floating_groups_take_the_palette_frame() { + use craft::ui::docking::FloatingGroupLook; + use craft::ui::runtime::env::Env; + let mut look = None; + crate::testing::ui_context().run_ui(Default::default(), |ui| look = Some(Env::of(ui).get::())).textures_delta.clear(); + assert_eq!(look, Some(FloatingGroupLook::Palette)); +} diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 660b2814ef..a260b8d6b7 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -123,9 +123,6 @@ pub struct CanvasCache { /// The uid of the document a tab rest showed while art carried off the canvas waits over it: only its canvas takes /// the art, so a target closed or left by other means carries nothing (`canvas::drops`). pub carry_target: Option, - /// The tool host ended the tool's press with a `Removed` cancel in this pass: the canvas was hidden for a pass, as - /// when art carried off it rests on another document's tab and comes back (`tool_adapter::resume_carry`). - pub removed_press: bool, /// The last drag the tool was sent and the screen point it was at: when the view scrolls under the held /// pointer, the drag goes on at that point in the scrolled view. pub last_drag: Option<(egui::Pos2, vectorcraft_tools::PointerEvent)>, diff --git a/crates/ui-egui/src/canvas/marks.rs b/crates/ui-egui/src/canvas/marks.rs index 0a6f5ddbdb..7784554630 100644 --- a/crates/ui-egui/src/canvas/marks.rs +++ b/crates/ui-egui/src/canvas/marks.rs @@ -625,9 +625,8 @@ impl Component for ArtMarks<'_> { fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { let style = &cx.style; let draw = ui.draw(); - for quad in self.fade { - draw.data_fill(&PaintShape::Polygon(quad.to_vec()), FADE_OUTSIDE); - } + let pieces: Vec<_> = self.fade.iter().map(|quad| quad.to_vec()).collect(); + draw.data_fill_tiled(&pieces, FADE_OUTSIDE); let bleed = self.bleed.iter().map(|path| (path, style.bleed)); for (path, color) in bleed.chain(self.artboard_marks.iter().map(|path| (path, style.marks))) { for (points, closed) in path_runs(&self.view, path) { diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 861eda0790..5496faf6b5 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -682,12 +682,118 @@ struct MeshKey { pixels_per_point: f32, options: egui::epaint::TessellationOptions, look: MarkLook, + /// [`Joins`] of the paint, or none under a fade. + joins: Option, +} + +/// When a mark's fill and its edge are one shape, as `BezierOverlay`'s kept mesh joins them: the edge is opaque and +/// wider than `thin_line`, the widest stroke egui tessellates as a translucent ridge (0.9 of the feathering, in points). +/// Under a fade (a painter opacity below 1) the overlay keeps them two shapes, so the fill shows through the edge. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Joins { + thin_line: f32, +} + +impl Joins { + /// The joins of a painter at `opacity` with `options` at `pixels_per_point`. + fn of(opacity: f32, options: &egui::epaint::TessellationOptions, pixels_per_point: f32) -> Option { + let thin_line = if options.feathering { 0.9 * (options.feathering_size_in_pixels * (1.0 / pixels_per_point)) } else { 0.0 }; + (opacity >= 1.0).then_some(Self { thin_line }) + } + + /// Whether a fill and then `edge` around the same square or circle are one shape. + fn join(joins: Option, edge: Stroke) -> bool { + joins.is_some_and(|joins| edge.color.is_opaque() && edge.width > joins.thin_line) + } } /// The anchor marks tessellated as one mesh, and what they were tessellated from. pub(crate) struct KeptMesh { key: MeshKey, mesh: Arc, + /// How far the marks moved on screen since they were tessellated, in physical pixels, unrounded + /// ([`KeptMesh::translate`]). The mesh moved by this distance rounded. + moved: [f64; 2], +} + +/// How far from a whole number of physical pixels the marks' move since they were tessellated may be on screen, and +/// still count as whole: rounding noise of the screen position, well under what the tessellator's `f32` positions hold. +const PIXEL_SLACK: f64 = 1e-6; + +impl KeptMesh { + /// Moves the mesh by `by` in the document when tessellating the moved marks would give the same mesh moved, and + /// returns whether it did. `points` are the marks' anchors and direction handles before the move ([`knot_points`]), + /// and `options` the Path Options they are drawn with. The mesh moves when the marks' whole move since they were + /// tessellated is a whole number of physical pixels on screen, and when every point's `f32` screen position moves + /// by this move's whole pixels too. Every square [`mark_shapes`] could draw at a point, at the anchor side and at + /// the handle side, must keep its `f32` size and have each edge round to pixels as the tessellator rounds it, moved + /// by the same whole pixels; a square thin enough for the tessellator to draw as a line is tessellated again. It + /// also needs every point inside the canvas before and after the move, so the marks are drawn near and inside the + /// clip on both sides and no anchor, handle or outline is left out or culled. + fn translate(&mut self, by: Vec2, points: impl IntoIterator, options: &PathOptionsSettings) -> bool { + let key = &self.key; + let ppp = f64::from(key.pixels_per_point); + let view = key.view.affine(); + let shift = (view * (Point::ZERO + by)) - (view * Point::ZERO); + let moved = [self.moved[0] + shift.x * ppp, self.moved[1] + shift.y * ppp]; + if moved.iter().any(|p| !p.is_finite() || (p - p.round()).abs() > PIXEL_SLACK) { + return false; + } + // This move in whole physical pixels. + let pixels = [moved[0].round() - self.moved[0].round(), moved[1].round() - self.moved[1].round()]; + let area = key.rect.expand(key.look.reach).intersect(key.clip); + // `CanvasView::to_screen` with the affine computed once. + let screen = |p: Point| { + let s = view * p; + egui::pos2(s.x as f32, s.y as f32) + }; + let whole = |from: f32, to: f32, px: f64| ((f64::from(to) - f64::from(from)) * ppp - px).abs() <= PIXEL_SLACK; + // The tessellator's `f32` rounding of an edge to pixels (`GuiRounding::round_to_pixels`), in whole pixels. + let ppp_f32 = key.pixels_per_point; + let snapped = |edge: f32| f64::from((edge * ppp_f32).round()); + let lands = |from: f32, to: f32, px: f64| snapped(to) - snapped(from) == px; + let sides = mark_sides(options, &key.look); + // Below this side the tessellator draws a filled square as a line, which it rounds other ways. + let feathering = if key.options.feathering { key.options.feathering_size_in_pixels / ppp_f32 } else { 0.0 }; + if sides.iter().any(|side| *side <= 2.0 * feathering) { + return false; + } + for p in points { + let (from, to) = (screen(p), screen(p + by)); + if !(area.contains(from) && area.contains(to) && whole(from.x, to.x, pixels[0]) && whole(from.y, to.y, pixels[1])) { + return false; + } + for side in sides { + let (a, b) = (Rect::from_center_size(from, egui::Vec2::splat(side)), Rect::from_center_size(to, egui::Vec2::splat(side))); + // The tessellator tests the built square's `f32` width and height, which can come out below `side`. + if a.size() != b.size() + || [a, b].iter().any(|r| r.width() <= 2.0 * feathering || r.height() <= 2.0 * feathering) + || !(lands(a.min.x, b.min.x, pixels[0]) + && lands(a.max.x, b.max.x, pixels[0]) + && lands(a.min.y, b.min.y, pixels[1]) + && lands(a.max.y, b.max.y, pixels[1])) + { + return false; + } + } + } + let offset = vec2((pixels[0] / ppp) as f32, (pixels[1] / ppp) as f32); + self.moved = moved; + Arc::make_mut(&mut self.mesh).translate(offset); + true + } +} + +/// Every anchor and direction handle of `anchors`, in document units. The outlines lie inside the hull of these +/// points, as a curve lies inside the hull of its points. +fn knot_points(anchors: &Anchors) -> impl Iterator + '_ { + anchors + .paths + .iter() + .chain(&anchors.plain) + .flat_map(|p| &p.subpaths) + .flat_map(|sp| &sp.knots) + .flat_map(|knot| [knot.anchor, knot.in_ctrl, knot.out_ctrl]) } /// One set of anchors as `BezierOverlay` took it: the paths, which anchors are selected and how they show. @@ -782,19 +888,21 @@ impl Component for AnchorMarks<'_> { reach: style.reach, }; let painter = ui.content_painter(cx); + let (pixels_per_point, options) = (painter.pixels_per_point(), painter.painter.ctx().tessellation_options(|options| *options)); let key = MeshKey { marks: self.key, view: space.view, rect: cx.rect, clip: painter.painter.clip_rect(), - pixels_per_point: painter.pixels_per_point(), - options: painter.painter.ctx().tessellation_options(|options| *options), + pixels_per_point, + options, look, + joins: Joins::of(painter.painter.opacity(), &options, pixels_per_point), }; let shapes = || { let mut shapes = Vec::new(); for set in mark_sets(self.anchors) { - mark_shapes(&mut shapes, &set, &space.view, cx.rect, &look); + mark_shapes(&mut shapes, &set, &space.view, cx.rect, &look, key.joins); } shapes }; @@ -809,7 +917,7 @@ impl Component for AnchorMarks<'_> { None => { let shapes = shapes(); let mesh = Arc::new(tessellate(shapes, &key)); - *kept = Some(KeptMesh { key, mesh: Arc::clone(&mesh) }); + *kept = Some(KeptMesh { key, mesh: Arc::clone(&mesh), moved: [0.0; 2] }); mesh } }; @@ -864,14 +972,21 @@ enum MarkFill { Path, } +/// The side of an anchor's mark, then of a direction handle's end, under `options`. +fn mark_sides(options: &PathOptionsSettings, look: &MarkLook) -> [f32; 2] { + let anchor = options.anchor_size.unwrap_or(look.anchor); + let handle = if options.handles == HandleStyle::Large { look.large } else { look.anchor }; + [anchor, handle] +} + /// The egui shapes `BezierOverlay` paints for `set` under `BezierTool::Anchors`, in its order: every outline, the -/// selected segment, then the anchors and handles near `rect`, then the handles of the other paths' selected anchors. -fn mark_shapes(out: &mut Vec, set: &MarkSet<'_>, view: &CanvasView, rect: Rect, look: &MarkLook) { +/// selected segment, then the anchors and handles near `rect`, then the handles of the other paths' selected anchors +/// that reach near `rect`. An anchor's or a handle end's fill and edge are one shape under `joins`. +fn mark_shapes(out: &mut Vec, set: &MarkSet<'_>, view: &CanvasView, rect: Rect, look: &MarkLook, joins: Option) { let options = set.options; let option_color = options.color.map(|[r, g, b]| Color32::from(Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0))); let path_color = |path: &EditPath| path.color.map(Color32::from); - let anchor_side = options.anchor_size.unwrap_or(look.anchor); - let handle_side = if options.handles == HandleStyle::Large { look.large } else { look.anchor }; + let [anchor_side, handle_side] = mark_sides(options, look); let circles = set.shown == AnchorsShown::Curvature; let line = |out: &mut Vec, points: Vec, closed: bool, segment: bool, color: Option| { let named = if segment { look.thick } else { look.medium }; @@ -917,14 +1032,18 @@ fn mark_shapes(out: &mut Vec, set: &MarkSet<'_>, view: &CanvasView, rect: MarkFill::Path => color.unwrap_or(look.line), }; let edge = Stroke::new(look.thin, color.unwrap_or(look.edge)); - if circle { - let radius = side / 2.0; - out.push(Shape::Circle(egui::epaint::CircleShape { center: at, radius, fill, stroke: Stroke::NONE })); - out.push(Shape::Circle(egui::epaint::CircleShape { center: at, radius, fill: Color32::TRANSPARENT, stroke: edge })); + let shape = |fill: Color32, stroke: Stroke| { + if circle { + Shape::Circle(egui::epaint::CircleShape { center: at, radius: side / 2.0, fill, stroke }) + } else { + Shape::Rect(egui::epaint::RectShape::new(Rect::from_center_size(at, egui::Vec2::splat(side)), 0.0, fill, stroke, StrokeKind::Inside)) + } + }; + if Joins::join(joins, edge) { + out.push(shape(fill, edge)); } else { - let square = Rect::from_center_size(at, egui::Vec2::splat(side)); - out.push(Shape::Rect(egui::epaint::RectShape::new(square, 0.0, fill, Stroke::NONE, StrokeKind::Inside))); - out.push(Shape::Rect(egui::epaint::RectShape::new(square, 0.0, Color32::TRANSPARENT, edge, StrokeKind::Inside))); + out.push(shape(fill, Stroke::NONE)); + out.push(shape(Color32::TRANSPARENT, edge)); } }; // A direction handle: its line from the anchor, then its end. @@ -957,7 +1076,10 @@ fn mark_shapes(out: &mut Vec, set: &MarkSet<'_>, view: &CanvasView, rect: if circles || set.handles == HandlesShown::All { return; } - // The handles of anchors selected in paths other than the edited one. + // The handles of anchors selected in paths other than the edited one whose end is near `rect`, or whose line from + // the anchor may cross it. Near is the reach, or the half side and edge of the largest handle end and one point for + // its feathered edge when that is further. + let near = rect.expand(look.reach.max(look.anchor.max(look.large) / 2.0 + look.thin + 1.0)); let edited = set.selection.path.map_or(0, |_| set.selection.anchors.len()); for path in set.paths { if set.selection.path == Some(path.key) || !selected.listed.contains(&path.key) { @@ -966,7 +1088,10 @@ fn mark_shapes(out: &mut Vec, set: &MarkSet<'_>, view: &CanvasView, rect: let own = PathSelection::new(Some(path.key), Vec::new(), None); let listed = |key: u64, knot: KnotRef| selected.others.contains(&(key, knot)); for (_, knot, end) in handles_of(std::slice::from_ref(path), &own, listed, selected.others_len + edited, set.handles, view) { - handle(out, path, knot, end); + let reaches = near.contains(end) || path.knot(knot).is_some_and(|k| Rect::from_two_pos(view.to_screen(k.anchor), end).intersects(near)); + if reaches { + handle(out, path, knot, end); + } } } } @@ -1198,12 +1323,22 @@ impl SelectionMarks { self.from = (moved.from.clone(), moved.by); self.doc = moved.to.clone(); } + // The kept mesh shows these marks, so it stays theirs under the new key. + let was = self.key; + if let Some(kept) = self.mesh.get_mut().as_mut().filter(|kept| kept.key.marks == was) { + kept.key.marks = key; + } self.key = key; Some(self) } - /// Moves every mark by `by`. + /// Moves every mark by `by`, and the kept mesh of the anchor marks with them when it can move as it is + /// ([`KeptMesh::translate`]); otherwise the next paint tessellates the marks again. fn translate(&mut self, by: Vec2) { + let mesh = self.mesh.get_mut(); + if mesh.as_mut().is_some_and(|kept| !kept.translate(by, knot_points(&self.anchors), &self.anchors.options)) { + *mesh = None; + } let shift = vectorcraft_geom::Affine::translate(by); for o in &mut self.outlines { o.paths.iter_mut().chain(o.key.as_mut()).for_each(|path| path.apply_affine(shift)); diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 65ca87aff3..875b9fe682 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -1014,7 +1014,48 @@ fn canvas_shapes(app: &mut VectorcraftApp, ctx: &egui::Context, overlay: bool) - let out = canvas_frame(app, ctx, vec![]); OVERLAY_MARKS.with(|on| on.set(false)); RAW_MARKS.with(|on| on.set(false)); - crate::tests::labels::flat_painted_shapes(&out.shapes) + // A placeholder that was never filled paints nothing. + crate::tests::labels::flat_painted_shapes(&out.shapes).into_iter().filter(|shape| !matches!(shape, egui::Shape::Noop)).collect() +} + +/// `marks` with each run of shapes that `overlay` paints as one kept mesh replaced by that run tessellated into one +/// mesh, as `Draw::kept_mesh` tessellates it: the context's options, no font atlas discs and no clip. A run ends where +/// its mesh reaches the vertex count of the overlay's mesh at the same place; anything else is left as it was. Also +/// returns how many runs of more than one shape became a mesh. +fn kept_like(overlay: &[egui::Shape], marks: Vec, ctx: &egui::Context) -> (Vec, usize) { + let options = ctx.tessellation_options(|options| *options); + let mut marks = marks.into_iter().peekable(); + let mut out = Vec::new(); + let mut runs = 0; + for shape in overlay { + // A mesh both frames paint is compared as it is. + let both = matches!(marks.peek(), Some(egui::Shape::Mesh(_))); + let egui::Shape::Mesh(kept) = shape else { + out.extend(marks.next()); + continue; + }; + if both { + out.extend(marks.next()); + continue; + } + let mut tessellator = egui::epaint::Tessellator::new(ctx.pixels_per_point(), options, [1, 1], Vec::new()); + let mut mesh = egui::Mesh::default(); + let mut run = Vec::new(); + while mesh.vertices.len() < kept.vertices.len() + && let Some(next) = marks.next() + { + run.push(next.clone()); + tessellator.tessellate_shape(next, &mut mesh); + } + if mesh.vertices.len() == kept.vertices.len() { + runs += usize::from(run.len() > 1); + out.push(egui::Shape::Mesh(std::sync::Arc::new(mesh))); + } else { + out.extend(run); + } + } + out.extend(marks); + (out, runs) } /// A canvas app with one curve, the task bar off and every frame drawn on this thread. @@ -1039,8 +1080,9 @@ fn the_anchor_marks_paint_what_the_bezier_overlay_paints() { change(&mut marks.anchors); } let overlay = canvas_shapes(app, &ctx, true); - let marks = canvas_shapes(app, &ctx, false); - assert!(overlay.len() > 20, "{case}: the overlay painted the marks ({} shapes)", overlay.len()); + // The overlay paints its anchors and handles as one kept mesh, the marks paint them one shape at a time. + let (marks, runs) = kept_like(&overlay, canvas_shapes(app, &ctx, false), &ctx); + assert!(runs > 0, "{case}: the overlay painted the marks as a kept mesh ({} shapes)", overlay.len()); let differs = overlay.iter().zip(&marks).position(|(a, b)| a != b); assert!( overlay == marks, @@ -1090,6 +1132,16 @@ fn the_anchor_marks_paint_what_the_bezier_overlay_paints() { } }); app.session.active_mut().unwrap().selection.segments.clear(); + // Another path's selected anchors far off the canvas: their handles, ends and lines both off it, are left out. + let far = id_of(&app.run("path.create", json!({"d": "M-3000 -3000 C-2900 -3100 -2800 -3100 -2700 -3000"})).unwrap()); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + app.run("select.anchors", json!({"id": far.0, "anchors": [[0, 0], [0, 1]], "mode": "add"})).unwrap(); + compare(&mut app, "handles of another path off the canvas", &|anchors| { + assert!( + anchors.selection.others.iter().any(|(key, knots)| !knots.is_empty() && anchors.paths.iter().any(|p| p.key == *key)), + "another path's anchors are selected" + ); + }); app.run("select.set", json!({"ids": [curve.0]})).unwrap(); app.select_tool("curvature"); compare(&mut app, "the Curvature tool", &same); @@ -1283,3 +1335,166 @@ fn a_move_of_the_selection_moves_its_marks_without_building_them() { assert_eq!(frames(&mut app, 3), 1, "an undo"); assert!(kept_marks_are_current(&app), "after an undo"); } + +/// The mesh of the anchor marks the canvas keeps. +fn kept_mesh(app: &VectorcraftApp) -> Arc { + let marks = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks"); + let kept = marks.mesh.borrow(); + Arc::clone(&kept.as_ref().expect("the canvas kept the anchor marks' mesh").mesh) +} + +// A drag of the selection moves the kept mesh of its anchor marks instead of tessellating them again: steps of whole +// pixels tessellate nothing and leave the mesh a new tessellation gives, a new revision of the same marks keeps it, and +// a step of part of a pixel or one that takes the marks past the canvas's edge tessellates them once. +#[test] +fn a_drag_of_the_selection_moves_the_anchor_marks_mesh_without_tessellating_it() { + let (mut app, curve) = canvas_app(); + app.select_tool("selection"); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + let ctx = crate::testing::ui_context(); + let frames = |app: &mut VectorcraftApp, n: usize| { + let before = MESHES_BUILT.with(std::cell::Cell::get); + for _ in 0..n { + canvas_frame(app, &ctx, vec![]); + } + MESHES_BUILT.with(std::cell::Cell::get) - before + }; + assert_eq!(frames(&mut app, 2), 1, "the first frame tessellates the marks"); + // A document distance that is `px` physical pixels across on screen. + let pixels = |app: &VectorcraftApp, px: f64| px / (app.canvas_view().unwrap().zoom * f64::from(ctx.pixels_per_point())); + let step = |app: &mut VectorcraftApp, dx: f64| { + app.session.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 0], "copy": false})).unwrap(); + }; + + let layer = app.session.active().unwrap().doc.layers[0].id; + app.run("layer.setCurrent", json!({"id": layer.0})).unwrap(); + assert_eq!(frames(&mut app, 2), 0, "a new revision of the same document and selection"); + + // The kept mesh matches the one marks built now tessellate; the kept marks go back afterwards, so the drag + // goes on moving them. + let matches_new = |app: &mut VectorcraftApp, case: &str| { + let moved = kept_mesh(app); + let kept = app.canvas.selection_marks.take(); + canvas_frame(app, &ctx, vec![]); + let fresh = kept_mesh(app); + app.canvas.selection_marks = kept; + assert!(!fresh.vertices.is_empty(), "{case}: the marks drew something"); + assert_eq!(moved.indices, fresh.indices, "{case}: the moved mesh has the triangles of a new one"); + assert_eq!(moved.vertices.len(), fresh.vertices.len(), "{case}"); + for (a, b) in moved.vertices.iter().zip(&fresh.vertices) { + assert_eq!(a.color, b.color, "{case}"); + assert!((a.pos - b.pos).length() < 1e-3, "{case}: a moved vertex at {:?}, a new one at {:?}", a.pos, b.pos); + } + }; + + app.session.begin_interaction("Move").unwrap(); + let built = MARKS_BUILT.with(std::cell::Cell::get); + for px in [3.0, 10.0, -4.0] { + let dx = pixels(&app, px); + step(&mut app, dx); + assert_eq!(frames(&mut app, 2), 0, "a drag's step to {px} pixels"); + } + assert_eq!(MARKS_BUILT.with(std::cell::Cell::get), built, "the drag moved the kept marks"); + matches_new(&mut app, "after whole pixels"); + + let built = MARKS_BUILT.with(std::cell::Cell::get); + let dx = pixels(&app, -4.5); + step(&mut app, dx); + assert_eq!(frames(&mut app, 2), 1, "a step to part of a pixel"); + let dx = pixels(&app, -3.5); + step(&mut app, dx); + assert_eq!(frames(&mut app, 2), 0, "a whole pixel from the marks tessellated at part of one"); + assert_eq!(MARKS_BUILT.with(std::cell::Cell::get), built, "the drag moved the kept marks"); + matches_new(&mut app, "after part of a pixel and a whole one"); + // Whole pixels from the last step. + let dx = pixels(&app, 1996.5); + step(&mut app, dx); + assert_eq!(frames(&mut app, 2), 1, "a step past the canvas's edge"); + app.session.commit_interaction().unwrap(); +} + +// A move of whole pixels keeps the mesh only when every point's `f32` screen position moves by those whole pixels: +// at x = 255.999991 the screen position before a one-pixel move is 255.99998 and after it 257.0, so the marks' +// squares would round to other pixels than the moved mesh's. +#[test] +fn a_whole_pixel_move_keeps_the_mesh_only_when_the_screen_positions_move_by_whole_pixels() { + let by = Vec2::new(1.0, 0.0); + let options = PathOptionsSettings::default(); + assert!(kept_at_one_pixel_per_point().translate(by, [Point::new(255.5, 10.0)], &options), "a point whose screen position moves one whole pixel"); + let mut off = kept_at_one_pixel_per_point(); + assert!(!off.translate(by, [Point::new(255.5, 10.0), Point::new(255.999_991, 10.0)], &options), "a point that moves 1.0000153 pixels"); + assert_eq!(off.moved, [0.0; 2], "the refused move leaves the mesh where it was"); +} + +/// A kept mesh of no marks at one physical pixel per point, with the document's coordinates on screen unchanged. +fn kept_at_one_pixel_per_point() -> KeptMesh { + let screen = Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(1000.0, 1000.0)); + let look = MarkLook { + line: Color32::BLACK, + fill: Color32::WHITE, + edge: Color32::BLACK, + anchor: 5.0, + large: 7.0, + thin: 1.0, + medium: 2.0, + thick: 3.0, + reach: 20.0, + }; + KeptMesh { + key: MeshKey { + marks: 0, + view: CanvasView::new(screen, Point::new(500.0, 500.0), 1.0), + rect: screen, + clip: screen, + pixels_per_point: 1.0, + options: egui::epaint::TessellationOptions::default(), + look, + joins: Joins::of(1.0, &egui::epaint::TessellationOptions::default(), 1.0), + }, + mesh: Arc::new(egui::Mesh::default()), + moved: [0.0; 2], + } +} + +// A point whose `f32` screen position moves by exactly one pixel can still put a square's edge on other pixels: an +// anchor at x = 252.99998 moves to 253.99998, but its 5 pt square's right edge goes from 255.49998 to 256.5, which +// round to 255 and 257, so the moved mesh's edge at 256 is not the one a new tessellation draws. A 6 pt square there +// has edges that round one pixel on, but its `f32` width grows from 6 to 6.0000153, and the tessellator compares the +// width with its thresholds for drawing a square as a line or a stroke as a fill. +#[test] +fn a_whole_pixel_move_keeps_the_mesh_only_when_every_square_edge_rounds_by_those_pixels() { + let by = Vec2::new(1.0, 0.0); + let options = PathOptionsSettings::default(); + // The `f32` just under 253: 252.99998474121094. + let center = f64::from(253.0_f32 - 2.0_f32.powi(-16)); + let mut kept = kept_at_one_pixel_per_point(); + assert!(!kept.translate(by, [Point::new(center, 10.0)], &options), "a right edge that rounds two pixels on"); + assert_eq!(kept.moved, [0.0; 2], "the refused move leaves the mesh where it was"); + assert!(kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "edges on whole pixels"); + // Near the origin a move is whole within the rounding noise: an anchor at x = 2.9999998 (the `f32` just under 3) + // moved to 4 keeps its square's width, but the left edge goes from 0.4999998 to 1.5, which round to 0 and 2. + let near = f64::from(3.0_f32 - 2.0_f32.powi(-22)); + let step = Vec2::new(4.0 - near, 0.0); + assert!(!kept_at_one_pixel_per_point().translate(step, [Point::new(near, 10.0)], &options), "a left edge that rounds two pixels on"); + // Anchors and handle ends 6 pt across. + let mut six = kept_at_one_pixel_per_point(); + six.key.look.anchor = 6.0; + assert!(!six.translate(by, [Point::new(center, 10.0)], &options), "a square whose width changes"); +} + +// The tessellator draws a filled square no wider than twice its feathering as a line and rounds it another way, so a +// square that small is tessellated again after any move. +#[test] +#[allow(clippy::field_reassign_with_default)] // `PathOptionsSettings` is non-exhaustive: no struct literal outside its crate +fn a_move_tessellates_the_marks_again_when_a_square_is_drawn_as_a_line() { + let by = Vec2::new(1.0, 0.0); + let mut options = PathOptionsSettings::default(); + options.anchor_size = Some(2.0); + assert!(!kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "a 2 pt anchor at 1 pixel per point"); + // The `f32` just over 2 passes the check on the side, but the square built at x = 252.5 spans 251.5 to 253.5 in + // `f32`, 2 pixels wide, so the tessellator draws it as a line. + options.anchor_size = Some(f32::from_bits(2.0_f32.to_bits() + 1)); + assert!(!kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "a square built 2 pixels wide"); + options.anchor_size = Some(3.0); + assert!(kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "a 3 pt anchor"); +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 6d114665da..0357564509 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6023,6 +6023,32 @@ fn the_pasteboard_fade_leaves_exports_unchanged() { assert_eq!(exports(&mut app), plain); } +/// The fade's pieces around the artboard are painted as one mesh with no feathered edges. Each +/// piece used to be filled on its own and faded out along the edges it shares with the next, so a +/// lighter line ran from each artboard corner to the edges of the canvas (#10221). +#[test] +fn the_pasteboard_fade_is_one_mesh_with_no_seam_between_its_pieces() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("prefs.set", json!({"key": "fadeRegionOutsideArtboard", "value": true})).unwrap(); + app.select_tool("artboard"); + let ctx = crate::testing::ui_context(); + let fade = Color32::from_black_alpha(102); + let drawn = shapes(&mut app, &ctx); + assert!(super::artboards::fades_outside_artboards(&app)); + let meshes: Vec<_> = drawn + .iter() + .filter_map(|s| match s { + Shape::Mesh(m) if m.vertices.iter().any(|v| v.color == fade) => Some(m), + _ => None, + }) + .collect(); + assert_eq!(meshes.len(), 1, "the fade is one mesh"); + assert!(meshes[0].vertices.iter().all(|v| v.color == fade), "no vertex of the fade fades out (a feathered edge)"); + // The pieces surround the artboard: more than one quad's two triangles. + assert!(meshes[0].indices.len() > 6, "{} indices", meshes[0].indices.len()); +} + /// Finished worker renders are uploaded whenever they are not older than what is currently /// displayed on screen. During continuous edit streams (drag previews, held arrow nudges, or /// command bursts) where the document revision advances every frame, intermediate worker frames diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 6e77eaf51a..0205c4416d 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -1,9 +1,7 @@ //! The document tool as the framework's `CanvasTool`: the pointer and key calls of the tool host go to the engine //! session, and what the session asks of the UI is applied here. -use std::any::Any; use std::cell::{Cell, RefCell, RefMut}; -use std::sync::Arc; use craft::behavior::{CancelReason, CanvasView, Cursor, PointerKind as Device, PressPhase}; use craft::keymap::{Chord, Key}; @@ -12,9 +10,6 @@ use craft::ui::canvas::{ Autoscroll, CanvasTool, Momentary, MomentaryShift, ToolAction, ToolClaims, ToolContext, ToolHost, ToolHostResponse, ToolKey, ToolPass, ToolPointer, }; -use craft::ui::contract::DragPreview; -use craft::ui::runtime::drag; -use craft::ui::runtime::env::Env; use serde_json::json; use vectorcraft_engine::ViewInfo; use vectorcraft_geom::Point; @@ -453,9 +448,6 @@ impl CanvasTool for SessionTool<'_> { fn cancel(&mut self, reason: CancelReason, cx: &mut ToolContext<'_>) { self.send_samples(); let mut app = self.app(); - if reason == CancelReason::Removed { - app.canvas.removed_press = true; - } if app.ui.screen_mode == 3 { // The tool had no press of Presentation Mode's. app.canvas.last_drag = None; @@ -712,8 +704,6 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too app.canvas.keys_at = Some(ui.input(|i| i.time)); } let view_info = app.view_info(); - let carry = carried_session(ui.ctx()); - app.canvas.removed_press = false; let mut picked = ToolHostResponse::default(); let mut response = if crate::dialogs::recolor::edit_tab::with_theme_pick(app, |app, tool| picked = host_run(app, ui, pass, tool)) { picked @@ -747,7 +737,6 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too drop(tool); response }; - resume_carry(app, ui, pass, carry); // The framework ends a press at Escape; the engine's tool still takes the release that ends it. if app.canvas.escaped_press && !ui.input(|i| i.pointer.primary_down()) { app.canvas.escaped_press = false; @@ -796,28 +785,6 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too response } -/// The art a move carries off the canvas and what the panels see of it, while that drag session runs. -type Carry = (Arc, Arc); - -/// The drag session of art carried off the canvas, when one runs. -fn carried_session(ctx: &egui::Context) -> Option { - Some((drag::active::(ctx)?, drag::active::(ctx)?)) -} - -/// Starts the drag session `carry` again when the tool host ended it in this pass with the press's `Removed` cancel -/// while the button is still held. The canvas was hidden for a pass, as when the art rests on another document's tab -/// and comes back, and the release then drops the art where it lands. -// Workaround: storytold/craft-libs#5281 keeps the session running; remove this with the pin bump that takes it. -fn resume_carry(app: &mut VectorcraftApp, ui: &Ui, pass: &ToolPass, carry: Option) { - let removed = std::mem::take(&mut app.canvas.removed_press); - let Some((art, panel)) = carry else { return }; - if !removed || drag::active::(ui.ctx()).is_some() || !ui.input(|i| i.pointer.primary_down()) { - return; - } - let also: Arc = panel; - drag::start(ui.ctx(), pass.id, &Env::of(ui).view(), art, vec![also], DragPreview::None); -} - fn host_run_session(tool: &mut SessionTool<'_>, ui: &Ui, pass: &ToolPass) -> ToolHostResponse { let mut app = tool.app(); // The host borrows the tool and the app both through the cell, one call at a time. diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index c1fed7f9fa..4431a3ac3f 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -293,7 +293,7 @@ fn opacity_field(app: &mut VectorcraftApp, ui: &mut Ui, opacity: f32, selected: let target = crate::panels::transparency_target(app); group(ui, rank::OPACITY, |ui| { let field = Field::new(label).side(SideLabel::new().link().scrub(true)).show(ui, |ui, _| { - let number = NumberField::new(label, Bind::given(Some(crate::panels::shown_percent(opacity)))) + let number = NumberField::new(label, Bind::given(Some(f64::from(opacity) * 100.0))) .range(0.0..=100.0) .unit("%") .scrub_by_label() diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index c83bd7fd1c..9030486c4c 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -6,15 +6,14 @@ use super::*; fn every_tool_cursors_hotspot_is_on_its_glyph() { use craft::ui::primitives::{painted_image, register_app_icons}; use craft::ui::runtime::env::Env; - use craft::ui::style::rgba_color; crate::icons::register(); register_app_icons(&CURSOR_ICONS); let mut missed = Vec::new(); crate::testing::ui_context() .run_ui(Default::default(), |ui| { let env = Env::of(ui); - let ink = rgba_color(env.tokens.tokens().color.overlay.cursor); - let near_ink = |px: &[u8]| px[3] == 255 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8); + // The tool marks are black; their white halo is not a part of the glyph a click lands on. + let near_ink = |px: &[u8]| px[3] == 255 && px[..3].iter().all(|value| *value <= 8); for c in GLYPHS { let cb::Cursor::Painted(painted @ PaintedCursor::Tool { .. }) = tool_cursor(c) else { continue }; let Some(image) = painted_image(&env, &painted, 2.0) else { @@ -71,6 +70,42 @@ fn a_tools_move_resize_grab_and_not_allowed_cursors_are_drawn_like_its_own() { assert!(matches!(tool_cursor(Cursor::Busy), cb::Cursor::System(_)), "the wait pointer stays the system's"); } +/// The Selection and Direct Selection arrows, the Hand, the drawing crosshair and a tool cursor draw in black and +/// white only, in the Modern and Classic color schemes and in light and dark interfaces: no pixel takes the accent or +/// another hue over the artwork. +#[test] +fn drawing_pointers_draw_in_black_and_white() { + use craft::ui::primitives::{painted_image, register_app_icons}; + use craft::ui::runtime::env::Env; + use craft::ui::runtime::frame::{FrameInput, set_input}; + crate::icons::register(); + register_app_icons(&CURSOR_ICONS); + let pointers = [Cursor::Arrow, Cursor::ArrowHollow, Cursor::Hand, Cursor::Crosshair, Cursor::Pen]; + use crate::theme::{Brightness, Scheme}; + let looks = [(Scheme::Modern, Brightness::Dark), (Scheme::Classic, Brightness::MediumDark), (Scheme::Classic, Brightness::Light)]; + for (scheme, brightness) in looks { + let ctx = crate::testing::ui_context(); + let prefs = vectorcraft_engine::Prefs { ui_color_scheme: scheme.id().into(), ui_brightness: brightness.id().into(), ..Default::default() }; + set_input(&ctx, FrameInput::new(crate::app::root_env(&prefs, 1.0, None))); + ctx.run_ui(Default::default(), |ui| { + let env = Env::of(ui); + for c in pointers { + let cb::Cursor::Painted(painted) = tool_cursor(c) else { panic!("{c:?} is painted") }; + let image = painted_image(&env, &painted, 2.0).unwrap_or_else(|| panic!("{c:?} has no image")); + let tinted = image + .rgba + .as_chunks::<4>() + .0 + .iter() + .find(|px| px[3] > 0 && px[..3].iter().max().zip(px[..3].iter().min()).is_some_and(|(hi, lo)| hi - lo > 8)); + assert!(tinted.is_none(), "{scheme:?} {brightness:?} {c:?}: a pixel takes a hue: {tinted:?}"); + } + }) + .textures_delta + .clear(); + } +} + /// A `cursor-` icon name a cursor uses must be in the set the host registers. #[test] fn every_cursor_icon_the_app_names_is_in_its_set() { @@ -87,18 +122,16 @@ fn every_cursor_icon_the_app_names_is_in_its_set() { fn the_painted_pen_nibs_keep_their_breather_holes() { use craft::ui::primitives::{painted_image, register_app_icons}; use craft::ui::runtime::env::Env; - use craft::ui::style::rgba_color; register_app_icons(&crate::icons::APP_ICONS); register_app_icons(&CURSOR_ICONS); crate::testing::ui_context() .run_ui(Default::default(), |ui| { let env = Env::of(ui); - let tokens = env.tokens.tokens(); - let ink = rgba_color(tokens.color.overlay.cursor); - let is_ink = |px: &[u8]| px[3] >= 240 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8); + // The tool marks are black, drawn on the icon's 24-unit box at one point per unit. + let is_ink = |px: &[u8]| px[3] >= 240 && px[..3].iter().all(|value| *value <= 8); let scale = 4.0; - let from_art_units = tokens.size.icon.md * scale / 24.0; + let from_art_units = scale; for c in [Cursor::Pen, Cursor::PenConvert, Cursor::PenJoin, Cursor::Curvature] { let cb::Cursor::Painted(painted @ PaintedCursor::Tool { hotspot, .. }) = tool_cursor(c) else { panic!("{c:?} must have painted tool art"); diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index c55707fd02..eb418d42da 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -512,14 +512,26 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R // Where new art goes now is taken before Replace selects the object it swaps again. let current = placement.and_then(|_| crate::placing::Insertion::of(app)); // A drawing converted off the UI thread replaces the object selected when Place - // started, selected again, unless it changed meanwhile. + // started, selected again, unless it changed meanwhile. When the drawing is not placed, + // the user's selection comes back. + let mut user_selection = None; if let Some((old, node)) = placement.and_then(|pl| pl.replaced.as_ref()) { let st = app.session.doc().map_err(|e| e.to_string())?; if st.doc.node(*old) != Some(node) { return Err("replace: the object to replace was changed or deleted".into()); } if st.selection.objects != [*old] || st.selection.symbol_part.is_some() { + let user = st.selection.clone(); app.session.execute("select.set", &json!({ "ids": [old.0] })).map_err(|e| e.to_string())?; + let st = app.session.doc().map_err(|e| e.to_string())?; + user_selection = Some(crate::placing::Reselect { + doc: st.uid, + swapped: st.selection.clone(), + selections: st.selections, + art: st.doc.clone(), + isolation: st.isolation, + user, + }); } } // It goes where new art went when Place started, and what the user changed since is @@ -537,12 +549,19 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R if let Some(path) = &source.path { app.placing.bytes_next = Some((path.clone(), source.file.clone())); } + app.placing.select_on_failure = user_selection.clone(); let r = crate::place::run_for_user(app, &p).map(|_| ()); app.placing.keep_next = None; app.placing.bytes_next = None; + app.placing.select_on_failure = None; if let (Some(current), Some(insertion)) = (current, restore) { current.restore_changed(&insertion, app); } + if r.is_err() + && let Some(back) = &user_selection + { + crate::placing::reselect(app, back); + } r } None => { @@ -1107,6 +1126,60 @@ mod tests { crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap(); assert!(app.opening.converting.is_empty()); assert!(app.ui.status.contains("select the one object to replace"), "{}", app.ui.status); + // A Replace that fails keeps the selection the user made since Place started. + let replaced = rect(&mut app, 90.0); + crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap(); + let selected_since = rect(&mut app, 130.0); + finish_conversions(&mut app); + set(&app, "layout", json!("No such layout")); + let undo = undo_steps(&app, first); + let _ = host::confirm(&mut app, KIND); + placed(&mut app); + assert!(app.ui.status.contains("no layout"), "{}", app.ui.status); + let st = app.session.doc().unwrap(); + assert!(st.doc.node(replaced).is_some(), "the object is not replaced"); + assert_eq!(st.selection.objects, vec![selected_since], "the selection made since Place started is kept"); + assert_eq!(undo_steps(&app, first), undo); + host::cancel(&app, KIND); + // A selection made while the drawing is read is kept too. + crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap(); + rect(&mut app, 170.0); + finish_conversions(&mut app); + set(&app, "layout", json!("No such layout")); + let _ = host::confirm(&mut app, KIND); + app.run("select.set", json!({ "ids": [selected_since.0] })).unwrap(); + placed(&mut app); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![selected_since], "the selection made since OK is kept"); + host::cancel(&app, KIND); + // Selecting the replacement target again after OK keeps that selection on failure. + crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap(); + rect(&mut app, 210.0); + finish_conversions(&mut app); + set(&app, "layout", json!("No such layout")); + let _ = host::confirm(&mut app, KIND); + app.run("select.set", json!({ "ids": [replaced.0] })).unwrap(); + placed(&mut app); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![replaced], "the target selected again since OK is kept"); + host::cancel(&app, KIND); + // Cancel restores the source document's selection while another document stays active. + crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap(); + let selected_since = rect(&mut app, 250.0); + finish_conversions(&mut app); + set(&app, "layout", json!("No such layout")); + let _ = host::confirm(&mut app, KIND); + let other_index = app.session.documents().iter().position(|st| st.uid == other).unwrap(); + let undo = undo_steps(&app, first); + app.session.set_active(other_index); + let other_selection = app.session.doc().unwrap().selection.clone(); + assert_eq!(crate::placing::cancel_all(&mut app)["cancelled"], 1); + assert_eq!(app.session.doc().unwrap().uid, other); + assert_eq!(app.session.doc().unwrap().selection, other_selection); + let st = app.session.documents().iter().find(|st| st.uid == first).unwrap(); + assert_eq!(st.selection.objects, vec![selected_since], "Cancel restores the background document's selection"); + assert_eq!(st.history.undo.len(), undo); + host::cancel(&app, KIND); + let first_index = app.session.documents().iter().position(|st| st.uid == first).unwrap(); + app.session.set_active(first_index); // Closed meanwhile. crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); app.session.execute("file.close", &json!({})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 6965493c9c..c1faac4a58 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -14,15 +14,14 @@ use std::sync::{Arc, Weak}; use craft::imaging::ui::filter_gallery::{ EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGallerySession, FilterIndex, FilterTree, - FilterTreeLayout, GalleryFilter, GalleryThumb, LayerId, SessionField, + GalleryFilter, GalleryThumb, LayerId, SessionField, }; use craft::theme::variant::Tone; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Props as _, Sampler as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, LeastWidth, Props as _, Sampler as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id}; use craft::ui::display::{Picture, PictureSize}; use craft::ui::layout_components::{Row, Stack}; -use craft::ui::list::{ThumbAspect, ThumbSize}; use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; use craft::ui::primitives::textures::{Revision, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails}; @@ -46,9 +45,28 @@ use crate::file_asks::Owner; /// Thumbnail of one filter, in pixels at most. The drawing is original; the filter is this app's. const THUMB: usize = 36; -/// Sample image dimensions before the dialog scales the image to its display size. -const PREVIEW_W: usize = 120; -const PREVIEW_H: usize = 84; +/// The preview's height over its width. +const PREVIEW_ASPECT: (usize, usize) = (10, 7); + +/// The preview's raster: `width` points wide at the screen's density, one device pixel to a texel, with `px` +/// document points to a pixel so the filters draw the same at every density. +#[derive(Clone, Copy, Debug, PartialEq)] +struct PreviewSample { + width: usize, + height: usize, + px: f64, +} + +impl PreviewSample { + /// A sample `points` wide at `pixels_per_point`; a degenerate width or density gives one pixel. + fn new(points: f32, pixels_per_point: f32) -> Self { + let ppp = if pixels_per_point.is_finite() && pixels_per_point > 0.0 { pixels_per_point } else { 1.0 }; + let pixels = f64::from(points * ppp); + let width = if pixels.is_finite() { pixels.round().max(1.0) as usize } else { 1 }; + let (wide, high) = PREVIEW_ASPECT; + PreviewSample { width, height: (width * high / wide).max(1), px: 1.0 / f64::from(ppp) } + } +} /// The command the preview and OK run: the whole stack as one undo step. const COMMAND: &str = "command.batch"; @@ -435,9 +453,11 @@ impl StackDialog for EffectGalleryDialog { let refusal = held.refusal().map(|(reason, _)| reason.clone()); let current = (*selected).min(session.effects.len().saturating_sub(1)); let visible = entries_of(&session.effects, index, true); + let sample = PreviewSample::new(LeastWidth::SideMenu.points(Env::of(ui).tokens.tokens()), ui.ctx().pixels_per_point()); let key = { let mut hasher = DefaultHasher::new(); serde_json::to_string(&stack_batch_params(&visible)).unwrap_or_default().hash(&mut hasher); + (sample.width, sample.height).hash(&mut hasher); hasher.finish() }; let thumbs = Thumbnails::::in_context(ui.ctx(), "effectGallery.thumbs", ThumbnailOptions::new()); @@ -465,15 +485,17 @@ impl StackDialog for EffectGalleryDialog { cx.keep_view_open(canvas); } let Some(layer) = effects.get(current) else { return }; - let image = || color_image(&preview_rgba(&visible, PREVIEW_W, PREVIEW_H), PREVIEW_W, PREVIEW_H); + let image = || color_image(&preview_rgba(&visible, sample.width, sample.height, sample.px), sample.width, sample.height); + // The preview at the start, the category folders in the middle and the settings with the effect layers at + // the end, as the Filter Gallery page lays them out. Stack::new().show(ui, |ui, _| { - Picture::new(tl!("Preview"), key, &image).aspect(ThumbAspect::new(10, 7)).extent(PictureSize::Sample(ThumbSize::Large)).show(ui); Row::new().show(ui, |ui, _| { - let tree = FilterTree::new(index, &layer.filter, &thumbs, &Thumbs).layout(FilterTreeLayout::Lists).show(ui); + Picture::new(tl!("Preview"), key, &image).extent(PictureSize::DevicePixels).show(ui); + let tree = FilterTree::new(index, &layer.filter, &thumbs, &Thumbs).show(ui); if let Some(filter) = tree.picked { changes.push(EffectChange::set_filter(current, filter)); } - Stack::new().show(ui, |ui, _| { + Stack::new().least_width(LeastWidth::SideMenu).show(ui, |ui, _| { let params = EffectParameters::new(current, layer, index).show(ui); changes.extend(params.change); if params.path.is_some() { @@ -574,12 +596,12 @@ fn effect_label(id: &str) -> String { crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or_else(|| id.to_string()) } -/// Where the preview rasters sit: one document point per pixel, origin at the top-left. -fn preview_space(w: usize, h: usize) -> PixelSpace { - let (wf, hf) = (w as f64, h as f64); +/// Where the preview rasters sit: `px` document points per pixel, origin at the top-left. +fn preview_space(w: usize, h: usize, px: f64) -> PixelSpace { + let (wf, hf) = (w as f64 * px, h as f64 * px); PixelSpace { - to_doc: Affine::IDENTITY, - px: 1.0, + to_doc: Affine::scale(px), + px, center: Point::new(wf / 2.0, hf / 2.0), size: vectorcraft_geom::Vec2::new(wf, hf), channels: vectorcraft_effects::pixel::Channels::Rgb, @@ -637,9 +659,9 @@ fn sample_drawing(w: usize, h: usize) -> Vec { out } -/// Run one raster filter on a premultiplied RGBA buffer. Leaves it unchanged when `id` -/// is not one of those filters or the buffer is the wrong size. -fn apply_pixel(id: &str, params: &Map, data: &mut [u8], w: usize, h: usize) { +/// Run one raster filter on a premultiplied RGBA buffer of `px` document points to a pixel. Leaves it unchanged when +/// `id` is not one of those filters or the buffer is the wrong size. +fn apply_pixel(id: &str, params: &Map, data: &mut [u8], w: usize, h: usize, px: f64) { let Some(n) = w.checked_mul(h).and_then(|n| n.checked_mul(4)) else { return }; if n != data.len() || w == 0 || h == 0 { return; @@ -648,20 +670,21 @@ fn apply_pixel(id: &str, params: &Map, data: &mut [u8], w: usize, let Some(vectorcraft_effects::RasterFx::Pixel(fx)) = vectorcraft_effects::raster_effects(std::slice::from_ref(&effect)).into_iter().next() else { return; }; - fx.apply(data, w, h, &preview_space(w, h)); + fx.apply(data, w, h, &preview_space(w, h, px)); } +/// A filter's thumbnail: the drawing at one point to a pixel with the filter applied. fn filtered(id: &str, params: &Map, w: usize, h: usize) -> Vec { let mut data = sample_drawing(w, h); - apply_pixel(id, params, &mut data, w, h); + apply_pixel(id, params, &mut data, w, h, 1.0); data } -/// The drawing with `layers` applied in order. -fn preview_rgba(layers: &[StackEntry], w: usize, h: usize) -> Vec { +/// The drawing at `px` document points to a pixel with `layers` applied in order. +fn preview_rgba(layers: &[StackEntry], w: usize, h: usize, px: f64) -> Vec { let mut data = sample_drawing(w, h); for layer in layers { - apply_pixel(&layer.effect, &layer.params, &mut data, w, h); + apply_pixel(&layer.effect, &layer.params, &mut data, w, h, px); } data } @@ -845,6 +868,96 @@ mod tests { assert!(preview_heights.iter().all(|(_, height)| *height >= 64.0), "the preview is an artwork sample: {preview_heights:?}"); } + /// The bounds of the first accessibility node named `label` (and of `role`, when given), in `window` points, at + /// `scale` pixels to a point. + fn bounds(app: &mut VectorcraftApp, window: egui::Rect, scale: f32, label: &str, role: Option) -> Option { + let ctx = app.ui_ctx.clone().unwrap(); + let mut nodes = Vec::new(); + for _ in 0..3 { + ctx.enable_accesskit(); + let mut input = egui::RawInput { screen_rect: Some(window), ..Default::default() }; + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(scale); + nodes = crate::testing::app_frame(app, &ctx, input).platform_output.accesskit_update.map(|update| update.nodes).unwrap_or_default(); + } + let node = nodes.iter().map(|(_, node)| node).find(|node| { + let named = node.label() == Some(label) + || node.labelled_by().iter().any(|id| nodes.iter().any(|(key, name)| key == id && name.label() == Some(label))); + named && role.is_none_or(|role| node.role() == role) && node.bounds().is_some() + })?; + let b = node.bounds()?; + Some(egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + } + + /// The preview stands at the start beside the category folders and the settings, side by side, and is larger + /// than a filter's thumbnail; in a short window the dialog still fits, and at twice the density the preview keeps + /// its size in points. Brazilian Portuguese has the longest labels of the reported layout. + #[test] + fn gallery_layout_puts_preview_folders_and_settings_side_by_side() { + use egui::accesskit::Role; + use egui::{Pos2, Rect, vec2}; + + let cases = [ + ("en", vec2(1280.0, 800.0), 1.0), + ("en", vec2(1280.0, 800.0), 2.0), + ("pt-br", vec2(1280.0, 800.0), 1.0), + ("pt-br", vec2(900.0, 560.0), 1.0), + ]; + let mut widths = Vec::new(); + for (language, size, scale) in cases { + let window = Rect::from_min_size(Pos2::ZERO, size); + let bounds = |app: &mut VectorcraftApp, label: &str, role| bounds(app, window, scale, label, role); + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.session.prefs.interface_language = language.to_owned(); + let lang = app.ui_language(); + let label = |name: &'static str| crate::i18n::tr(lang, name); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + bounds(&mut app, "", None); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + let at = format!("{language} at {size:?} scale {scale}"); + let gallery = bounds(&mut app, label("Effect Gallery"), Some(Role::Dialog)).expect("the gallery"); + let preview = bounds(&mut app, label("Preview"), Some(Role::Image)).expect("the preview"); + // A filter of the folder that opens with the gallery; the stack's one layer is another filter. + let cutout = crate::i18n::effect_name(lang, "artistic.cutout").unwrap(); + let tile = bounds(&mut app, &cutout, None).expect("the Cutout tile"); + // The settings' Filter select is named by the framework's own words, which this check reads in English. + let filter = bounds(&mut app, "Filter", None); + assert!(filter.is_some() || language != "en", "{at}: the settings' Filter select"); + let ok = bounds(&mut app, label("OK"), Some(Role::Button)).expect("OK"); + assert_eq!(app.ui_ctx.as_ref().unwrap().pixels_per_point(), scale, "{at}: the window's density"); + if language == "en" { + widths.push(preview.width()); + } + eprintln!("{at}: gallery {gallery:?}, preview {preview:?}, tile {tile:?}, filter {filter:?}, OK {ok:?}"); + assert!(window.contains_rect(gallery), "{at}: the gallery fits the window: {gallery:?}"); + assert!(gallery.contains_rect(preview) && gallery.contains_rect(ok), "{at}: the preview and OK are inside the gallery"); + assert!(preview.right() <= tile.left(), "{at}: the folders stand after the preview: {preview:?} {tile:?}"); + assert!(preview.top() < tile.bottom() && tile.top() < preview.bottom(), "{at}: the preview and the folders share a line"); + assert!(preview.width() > 2.0 * tile.width(), "{at}: the preview is larger than a thumbnail: {preview:?} {tile:?}"); + if let Some(filter) = filter { + assert!(tile.right() <= filter.left(), "{at}: the settings stand after the folders: {tile:?} {filter:?}"); + } + } + assert!((widths[0] - widths[1]).abs() <= 1.0, "the preview keeps its size in points at twice the density: {widths:?}"); + } + + /// The preview's raster has a texel per device pixel and draws its filters at document size whatever the + /// density; a density that is not a positive number counts as one pixel to a point. + #[test] + fn preview_sample_follows_the_density() { + use super::PreviewSample; + let one = PreviewSample::new(200.0, 1.0); + let two = PreviewSample::new(200.0, 2.0); + assert_eq!((two.width, two.height), (2 * one.width, 2 * one.height)); + assert_eq!(two.width as f64 * two.px, one.width as f64 * one.px, "the same document width at both densities"); + assert!(one.height < one.width, "the preview is wider than it is high"); + for bad in [0.0, -1.0, f32::NAN, f32::INFINITY] { + assert_eq!(PreviewSample::new(200.0, bad), one, "density {bad}"); + } + let empty = PreviewSample::new(0.0, 1.0); + assert!(empty.width >= 1 && empty.height >= 1, "{empty:?}"); + } + #[test] fn stack_preview_is_one_interaction() { let (mut app, ctx, node) = drawing(); diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 2ed369d2da..80476fcd1a 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -510,11 +510,12 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi Entry::new(Tab::Swatches, tl!("Swatches").to_owned()).icon(IconId::new("swatch-book")), ]; Segmented::new("View", Bind::bound(&mut *tab), &tabs).show(ui); - // A stop's colour can come from the art, as from the Gradient panel's eyedropper. - if !feed.point { - let tip = tl!("Eyedropper: click the art to sample the stop's colour").to_owned(); - filed.eyedropper |= DropperButton::new(tip, Bind::given(false)).show(ui).edit.value() == Some(&true); - } + let tip = if feed.point { + tl!("Eyedropper: click the art to sample the point's colour") + } else { + tl!("Eyedropper: click the art to sample the stop's colour") + }; + filed.eyedropper |= DropperButton::new(tip.to_owned(), Bind::given(false)).show(ui).edit.value() == Some(&true); if *tab == Tab::Color { let (closed, picked) = mode_menu(ui, &feed.shown, panel.mode); outside |= closed; @@ -834,7 +835,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { } if filed.eyedropper { dialogs.with(|host| host.cancel_by_id(ctx, id)); - crate::panels::gradient::stop_eyedropper(app); + match target { + Target::Stop(..) => crate::panels::gradient::stop_eyedropper(app), + Target::Point(..) => crate::panels::gradient::point_eyedropper(app), + } return; } let updated = selected(app).filter(|target| owner.key.matches(app, target)).zip(app.session.gradient_edit_paints(!owner.key.fill).ok()); @@ -1722,6 +1726,91 @@ mod tests { assert!(!is_open(&app)); } + fn point_sampling_panel() -> (crate::tests::panel_harness::Panel, NodeId, NodeId, usize) { + let mut app = app(); + let target = app.session.active().unwrap().selection.objects[0]; + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + app.run("paint.editGradient", json!({"kind": "freeform"})).unwrap(); + app.run("paint.freeform.addPoint", json!({"at": [150, 150], "color": "#0000ff"})).unwrap(); + let index = app.session.selected_freeform_point().unwrap(); + let source = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 60, "height": 80})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"color": "#00aa5a", "keepModel": true})).unwrap(); + app.run("select.set", json!({"ids": [target.0]})).unwrap(); + app.run("paint.freeform.selectPoint", json!({"index": index})).unwrap(); + let panel = crate::tests::panel_harness::Panel::new(app, |app, ui| { + app.dialogs().unwrap().with(|host| host.run(ui)); + host::pump(app, ui.ctx()); + }); + (panel, target, NodeId(source), index) + } + + fn arm_point_sample(panel: &mut crate::tests::panel_harness::Panel, index: usize) { + open_at(&mut panel.app(), index, Anchor::Screen(egui::pos2(200.0, 200.0))); + panel.frame(); + panel.click("Eyedropper: click the art to sample the point's colour"); + assert!(!is_open(&panel.app())); + assert_eq!(panel.app().session.tool_id(), "eyedropper"); + } + + fn click_sample_source(app: &mut VectorcraftApp) { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let view = app.view_info(); + for kind in [PointerKind::Down, PointerKind::Up] { + let requests = app.session.pointer(&PointerEvent::new(kind, 250.0, 115.0), view).unwrap(); + crate::canvas::apply_requests(app, Ok(requests)); + } + } + + fn node_fill(app: &VectorcraftApp, id: NodeId) -> Paint { + app.session.active().unwrap().doc.node(id).unwrap().appearance.fill_paint() + } + + #[test] + fn freeform_point_eyedropper_preserves_the_sample_model_and_undoes_once() { + let (mut panel, target, source, index) = point_sampling_panel(); + let initial = node_fill(&panel.app(), target); + let source_fill = node_fill(&panel.app(), source); + let color = source_fill.color().unwrap(); + assert!(matches!(color, Color::Rgb { .. }), "the source stores RGB in a CMYK document"); + let points = |app: &VectorcraftApp| app.session.proxy_freeform(false).unwrap().0.points; + let mut expected = points(&panel.app()); + assert_ne!(expected[index].color, color); + + arm_point_sample(&mut panel, index); + click_sample_source(&mut panel.app()); + assert_eq!(panel.app().session.tool_id(), "gradient"); + expected[index].color = color; + assert_eq!(points(&panel.app()), expected, "only the point's color changes"); + assert_eq!(node_fill(&panel.app(), source), source_fill); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(node_fill(&panel.app(), target), initial); + } + + #[test] + fn freeform_point_eyedropper_cancels_and_skips_a_replaced_point() { + let (mut panel, target, source, index) = point_sampling_panel(); + let initial = node_fill(&panel.app(), target); + let source_fill = node_fill(&panel.app(), source); + + arm_point_sample(&mut panel, index); + let escape = egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + let ctx = ctx(&panel.app()); + crate::tests::synthetic::key_frame(&mut panel.app(), &ctx, vec![escape]); + assert_eq!(panel.app().session.tool_id(), "gradient"); + assert_eq!(node_fill(&panel.app(), target), initial); + + arm_point_sample(&mut panel, index); + panel.app().run("paint.freeform.deletePoint", json!({"index": index})).unwrap(); + let replacement = panel.app().run("paint.freeform.addPoint", json!({"at": [155, 150], "color": "#ffa000"})).unwrap(); + assert_eq!(replacement["index"].as_u64(), Some(index as u64), "the replacement uses the old index"); + let before_pick = node_fill(&panel.app(), target); + assert_eq!(panel.app().session.tool_id(), "eyedropper"); + click_sample_source(&mut panel.app()); + assert_eq!(panel.app().session.tool_id(), "gradient"); + assert_eq!(node_fill(&panel.app(), target), before_pick); + assert_eq!(node_fill(&panel.app(), source), source_fill); + } + #[test] fn the_popover_closes_when_its_stop_goes_away() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 1d3cb996ee..c9813018b4 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -482,8 +482,9 @@ impl craft::behavior::ItemSource for Boards { } /// The native versions VectorCraft writes, newest first, each with the first release that reads -/// it (the format version each release tag writes: 2 in 0.1, 3 from 0.2, 4 from 0.8). -const NATIVE_VERSIONS: [(u32, &str); 4] = [(4, "0.8"), (3, "0.2"), (2, "0.1"), (1, "0.1")]; +/// it (the format version each release tag writes: 2 in 0.1, 3 from 0.2, 4 from 0.8, 5 from the +/// release after 0.25.2). +const NATIVE_VERSIONS: [(u32, &str); 5] = [(5, "0.25.3"), (4, "0.8"), (3, "0.2"), (2, "0.1"), (1, "0.1")]; /// The native version the dialog will write (the current one unless chosen). fn native_version_of(fields: &DialogFields) -> u32 { diff --git a/crates/ui-egui/src/graphics.rs b/crates/ui-egui/src/graphics.rs index b90827aea0..0e200259b5 100644 --- a/crates/ui-egui/src/graphics.rs +++ b/crates/ui-egui/src/graphics.rs @@ -127,14 +127,13 @@ impl VectorcraftApp { /// after losing its graphics), everything uploaded to the old one is made again: the fonts and /// theme, the canvas, the place cursor's thumbnails and every [`TexCache`]. The host hands it /// the window's context when it creates the app, so the first frame's input has the app's - /// commands. Each new context draws its text without hinting ([`crate::ui_fonts::hinting_off`]). + /// commands. pub fn adopt_context(&mut self, ctx: &egui::Context) { let tag = context_tag(ctx); self.ui_ctx = Some(ctx.clone()); if self.context == tag { return; } - crate::ui_fonts::hinting_off(ctx); if self.context != 0 { log::info!("vectorcraft: new graphics context: uploading the UI again"); forget_textures(); diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index 5d08bbf110..75f3091f6a 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -16,6 +16,8 @@ pub(crate) mod export; mod open; mod read_only_save; pub(crate) mod save; +#[cfg(not(target_arch = "wasm32"))] +mod saved_contents; #[cfg(test)] mod tests_read_only_save; diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 7aec797157..f6de26a38b 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -180,7 +180,7 @@ pub(crate) fn opened(app: &mut VectorcraftApp, r: &Value) { if let Some(st) = index.and_then(|i| app.session.documents().get(i)) && let Some(path) = &st.path { - app.saves.watch.known_now(st.uid, Path::new(path)); + app.saves.known_now(st.uid, Path::new(path)); } let notes = open_notes(app, r); crate::dialogs::missing_links::after_open(app, r, notes); diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index fc42da3c77..3fd847f4db 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -1,14 +1,16 @@ use std::collections::HashMap; -use std::path::PathBuf; -// The save panel's flow is the desktop's (craft-dialogs is native only); the web downloads. +use std::path::{Path, PathBuf}; #[cfg(not(target_arch = "wasm32"))] -use std::path::Path; +use std::sync::mpsc::{Receiver, TryRecvError}; +// The save panel's flow is the desktop's (craft-dialogs is native only); the web downloads. #[cfg(not(target_arch = "wasm32"))] use craft::dialogs::save::{SAVE_IN_PROGRESS, SaveDocument, SaveFlow, SaveStep, SaveTarget}; #[cfg(not(target_arch = "wasm32"))] use craft::host::Files; use craft::host::{FileFilter, PickRequest, Picked, Wake}; +#[cfg(not(target_arch = "wasm32"))] +use craft::platform::watch::FileStamp; use craft::platform::watch::FileWatch; use craft::ui::dialog::DialogId; #[cfg(not(target_arch = "wasm32"))] @@ -48,12 +50,31 @@ struct SaveDone { then: Option, } +/// A save whose flow would ask whether to replace its document's file, waiting for the file to be +/// compared with the bytes the app last read or wrote. +#[cfg(not(target_arch = "wasm32"))] +struct Checking { + path: PathBuf, + /// The file's version when it holds those bytes, else `None`. + answer: Receiver>, +} + /// The saves of the app: one [`SaveFlow`] per document, and what the flows need to ask and write. pub(crate) struct Saves { #[cfg(not(target_arch = "wasm32"))] flows: HashMap>, /// The version of each document's file the app last read or wrote. pub(crate) watch: FileWatch, + /// The digest of the bytes of each document's file, as the app last read or wrote them. + #[cfg(not(target_arch = "wasm32"))] + contents: super::saved_contents::SavedContents, + /// The saves waiting for a comparison of their document's file with those bytes. + #[cfg(not(target_arch = "wasm32"))] + checks: HashMap, + /// A comparison's save waited in the last pass for a dialog, a file picker or a gesture in + /// another document: [`after_ui`] asks for a frame once it no longer has to. + #[cfg(not(target_arch = "wasm32"))] + held: bool, /// The files written beside each document's file, which its next save replaces. pub(crate) written_beside: HashMap>, /// The files the OK of the replace question allows the save it runs again to replace. @@ -68,6 +89,12 @@ impl Saves { Self { #[cfg(not(target_arch = "wasm32"))] flows: HashMap::new(), + #[cfg(not(target_arch = "wasm32"))] + contents: super::saved_contents::SavedContents::new(), + #[cfg(not(target_arch = "wasm32"))] + checks: HashMap::new(), + #[cfg(not(target_arch = "wasm32"))] + held: false, watch: FileWatch::new(wake), written_beside: HashMap::new(), replace_files_ok: Vec::new(), @@ -76,12 +103,55 @@ impl Saves { } } + /// The app just read document `uid`'s file at `path`: that version is not a change on disk. + pub(crate) fn known_now(&mut self, uid: u64, path: &Path) { + self.watch.known_now(uid, path); + #[cfg(not(target_arch = "wasm32"))] + self.note_contents(uid, path); + } + + /// Takes the digest of document `uid`'s file at `path`, the version the watcher just recorded. + #[cfg(not(target_arch = "wasm32"))] + fn note_contents(&mut self, uid: u64, path: &Path) { + match FileStamp::at(path) { + // Not differing from the watcher's version: the file has not changed since it was recorded. + Some(stamp) if !self.watch.disk_differs(&uid, path, None) => self.contents.note(uid, path, stamp), + _ => self.contents.forget(uid), + } + } + + /// Stops tracking document `uid`'s file (the document closed). + #[cfg(not(target_arch = "wasm32"))] + fn forget(&mut self, uid: u64) { + self.watch.forget(&uid); + self.contents.forget(uid); + self.checks.remove(&uid); + } + #[cfg(not(target_arch = "wasm32"))] fn start(&mut self, files: &dyn Files, document: SaveDocument, target: SaveTarget) -> SaveStep { let Self { flows, watch, .. } = self; flows.entry(document.key).or_default().start(files, watch, document, target) } + /// The answer of document `uid`'s file comparison, once it has come (with `wait`, once it + /// comes): the file's version when it holds the bytes the app last read or wrote, and the + /// file's path. `None` while there is no answer yet, or no comparison. + #[cfg(not(target_arch = "wasm32"))] + fn answer(&mut self, uid: u64, wait: bool) -> Option<(Option, PathBuf)> { + let check = self.checks.get(&uid)?; + let same = if wait { + check.answer.recv().ok().flatten() + } else { + match check.answer.try_recv() { + Ok(same) => same, + Err(TryRecvError::Empty) => return None, + Err(TryRecvError::Disconnected) => None, + } + }; + self.checks.remove(&uid).map(|c| (same, c.path)) + } + /// Frees the document's flow after a write that wrote nothing. #[cfg(not(target_arch = "wasm32"))] pub(super) fn release(&mut self, uid: u64) { @@ -91,6 +161,63 @@ impl Saves { } } +/// Whether file comparisons need another frame to collect their answers. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn checks_pending(app: &VectorcraftApp) -> bool { + // A save waiting for a dialog or a gesture goes on in the frame after the one that ends it ([`after_ui`]). + app.saves.checks.keys().any(|uid| !held(app, *uid)) +} + +/// Whether document `uid`'s save has to wait: the document shows a dialog's preview or a drag not +/// yet committed, which the save would write (typing in progress is saved, as by any Save), or +/// writing it activates its document, which would put it under an open dialog or file picker of +/// another document, cancel a drag in progress in the active one, or fail while a script runs. +#[cfg(not(target_arch = "wasm32"))] +fn held(app: &VectorcraftApp, uid: u64) -> bool { + if app.session.documents().iter().any(|d| d.uid == uid && d.interaction.as_ref().is_some_and(|it| it.label != "Typing")) { + return true; + } + let active = app.session.active(); + active.map(|d| d.uid) != Some(uid) + && (app.any_dialog_open() + || app.file_dialog_open() + || active.is_some_and(|d| d.interaction.is_some()) + || app.canvas.grab.is_some() + || app.session.script_running()) +} + +/// Whether document `uid`'s save waits for the comparison of its file. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn checking(app: &VectorcraftApp, uid: u64) -> bool { + app.saves.checks.contains_key(&uid) +} + +/// The web has no file comparisons. +#[cfg(target_arch = "wasm32")] +pub(crate) fn checking(_: &VectorcraftApp, _: u64) -> bool { + false +} + +/// Asks for one frame when a save waited in the last pass and this pass's UI closed what it +/// waited for: the dialog pumps and the canvas run after [`pump`], so nothing else would. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn after_ui(app: &mut VectorcraftApp, ctx: &egui::Context) { + if app.saves.held && app.saves.checks.keys().any(|uid| !held(app, *uid)) { + app.saves.held = false; + ctx.request_repaint(); + } +} + +/// The web has no saves that wait. +#[cfg(target_arch = "wasm32")] +pub(crate) fn after_ui(_: &mut VectorcraftApp, _: &egui::Context) {} + +/// The web has no file comparisons to collect. +#[cfg(target_arch = "wasm32")] +pub(crate) fn checks_pending(_: &VectorcraftApp) -> bool { + false +} + /// Calls the `then` of the document's save, once. #[cfg(not(target_arch = "wasm32"))] fn terminate(app: &mut VectorcraftApp, uid: u64, r: Result) { @@ -107,10 +234,24 @@ fn finish(app: &mut VectorcraftApp, uid: u64, retargets: bool, out: &Result flow.written(&mut app.saves.watch, uid, Path::new(path)), + Some(path) if flow.is_busy() || retargets => { + flow.written(&mut app.saves.watch, uid, Path::new(path)); + // The document's own file (not a copy's): its digest goes with the version the watcher took. + if app.session.documents().iter().any(|d| d.uid == uid && d.path.as_deref() == Some(path)) { + app.saves.note_contents(uid, Path::new(path)); + } + } _ => flow.failed(&uid), } if !matches!(out, Ok(v) if v.get("pending").is_some()) { + // A comparison still pending belongs to the save this one ends (a save with an explicit path + // ran meanwhile): it is dropped and its flow freed, since its answer would ask about the file + // with no save left to apply the answer. + if app.saves.checks.remove(&uid).is_some() + && let Some(flow) = app.saves.flows.get_mut(&uid) + { + let _ = flow.cancel(app.host.files()); + } terminate(app, uid, out.clone()); } } @@ -124,10 +265,12 @@ pub(crate) fn allow_replacing(app: &mut VectorcraftApp, files: &[String]) { } } -/// Takes what the flows and their questions have answered since the last pass: the pick, the -/// changed-on-disk question's answer. A save whose document closed is cancelled and forgotten. +/// Takes what the flows and their questions have answered since the last pass: the comparison of +/// a document's file, the pick, the changed-on-disk question's answer. A save whose document +/// closed is cancelled and forgotten. Closed documents' digest state is dropped on every pass. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + resume_checked(app, false); let busy: Vec = app.saves.flows.iter().filter(|(_, f)| f.is_busy()).map(|(uid, _)| *uid).collect(); for uid in busy { if !app.session.documents().iter().any(|d| d.uid == uid) { @@ -136,7 +279,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { if let Some(mut flow) = app.saves.flows.remove(&uid) { flow.cancel(app.host.files()); } - app.saves.watch.forget(&uid); + app.saves.forget(uid); continue; } let (scope, automated) = app.saves.done.get(&uid).map_or_else(|| (ScopeHandle::capture(), app.automation_asked()), |d| d.asked.clone()); @@ -152,6 +295,83 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { app.status(e); } } + app.saves.contents.retain_open(app.session.documents().iter().map(|d| d.uid)); +} + +/// Goes on with the saves whose file comparison has answered (with `wait`, every one, once it +/// answers): an unchanged file is written over, and a changed one is asked about. +#[cfg(not(target_arch = "wasm32"))] +fn resume_checked(app: &mut VectorcraftApp, wait: bool) { + let checking: Vec = app.saves.checks.keys().copied().collect(); + for uid in checking { + // A closed document's save is cancelled with its flow, in [`pump`]. + let Some(file) = app.session.documents().iter().find(|d| d.uid == uid).map(|d| d.path.clone()) else { + continue; + }; + // Writing activates the save's document: while a dialog or file picker of another document + // is open, a drag goes on in it, or a script runs, the answer stays in its channel for a + // later pass. + if !wait && held(app, uid) { + app.saves.held = true; + continue; + } + let (scope, automated) = app.saves.done.get(&uid).map_or_else(|| (ScopeHandle::capture(), app.automation_asked()), |d| d.asked.clone()); + let r = scope.run(|| { + file_asks::as_automated(app, automated, |app| { + // The document now uses another file (a Save As finished meanwhile): the comparison + // is dropped and its save cancelled, without asking about the old file. + if app.saves.checks.get(&uid).is_some_and(|c| file.as_deref().map(Path::new) != Some(c.path.as_path())) { + app.saves.checks.remove(&uid); + let step = app.saves.flows.get_mut(&uid).and_then(|f| f.cancel(app.host.files())); + return step.map(|step| run_step(app, uid, step)); + } + let (same, path) = app.saves.answer(uid, wait)?; + // Still that version: a change made since the comparison is asked about. + let Some(stamp) = same.filter(|stamp| FileStamp::at(&path) == Some(*stamp)) else { + let asked = ask_changed_on_disk(app, uid, &path); + return Some(settle(app, uid, asked)); + }; + // The same bytes: the file's version now is the document's, and the flow writes over it. + app.saves.watch.known_as(uid, &path, Some(stamp)); + let step = app.saves.flows.get_mut(&uid).map_or(SaveStep::Busy, SaveFlow::replace); + Some(run_step(app, uid, step)) + }) + }); + if let Some(Err(e)) = r + && e != "cancelled" + { + app.status(e); + } + } +} + +/// Waits for every save's file comparison and goes on with those saves. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn wait_for_checks(app: &mut VectorcraftApp) { + resume_checked(app, true); +} + +/// Waits for every save's file comparison to answer and its thread to end (its wake included), +/// leaving each answer for the next [`pump`]. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn wait_for_answers(app: &mut VectorcraftApp) { + for check in app.saves.checks.values_mut() { + let (send, answer) = std::sync::mpsc::channel(); + if let Ok(same) = check.answer.recv() { + let _ = send.send(same); + } + // The thread drops its sender as it ends, after its wake. + let _ = check.answer.recv(); + check.answer = answer; + } +} + +/// Waits for the active document's baseline digest and compares it with the file. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn wait_for_contents(app: &VectorcraftApp) -> Option { + let document = app.session.active()?; + let path = Path::new(document.path.as_deref()?); + app.saves.contents.check(document.uid, path, Wake::none())?.recv().ok().flatten() } /// The web has no save flows: nothing answers between passes. @@ -182,6 +402,12 @@ fn next_step(app: &mut VectorcraftApp, uid: u64) -> Option> { /// Runs `step` of the document `uid`'s save; a failure frees the flow and tells the caller. fn run_step(app: &mut VectorcraftApp, uid: u64, step: SaveStep) -> Result { let r = proceed(app, step); + settle(app, uid, r) +} + +#[cfg(not(target_arch = "wasm32"))] +/// The result `r` of a step of document `uid`'s save; a failure frees the flow and tells the caller. +fn settle(app: &mut VectorcraftApp, uid: u64, r: Result) -> Result { if r.is_err() { app.saves.release(uid); terminate(app, uid, r.clone()); @@ -189,19 +415,40 @@ fn run_step(app: &mut VectorcraftApp, uid: u64, step: SaveStep) -> Result Result { + let name = fileio::file_name(&path.to_string_lossy()); + let prompt = StandardPrompt::changed_on_disk(name).instance(("changed-on-disk", key)); + let id = app.dialogs().ok_or("no window to ask in")?.with(|host| host.open(prompt)); + if let Some(done) = app.saves.done.get_mut(&key) { + done.question = Some(id); + } + Ok(json!({ "pending": "changedOnDisk" })) +} + +#[cfg(not(target_arch = "wasm32"))] +/// Asks the window for a frame, from any thread; does nothing without a window. +fn ui_wake(app: &VectorcraftApp) -> Wake { + app.ui_ctx.clone().map_or_else(Wake::none, |ctx| Wake::new(move || ctx.request_repaint())) +} + #[cfg(not(target_arch = "wasm32"))] fn proceed(app: &mut VectorcraftApp, step: SaveStep) -> Result { match step { SaveStep::Picking => Ok(json!({ "pending": "fileDialog" })), - SaveStep::AskChangedOnDisk { key, path } => { - let name = fileio::file_name(&path.to_string_lossy()); - let prompt = StandardPrompt::changed_on_disk(name).instance(("changed-on-disk", key)); - let id = app.dialogs().ok_or("no window to ask in")?.with(|host| host.open(prompt)); - if let Some(done) = app.saves.done.get_mut(&key) { - done.question = Some(id); + // Before asking, the file is compared with the bytes the app last read or wrote: a file + // whose metadata alone changed (a cloud-sync folder sets attributes on it, or puts the same + // bytes back as a new file) is written over without asking (#10734). [`pump`] goes on. + // The comparison's thread asks for a frame once it answers: a save started from the UI comes + // after this frame's repaint decision. + SaveStep::AskChangedOnDisk { key, path } => match app.saves.contents.check(key, &path, ui_wake(app)) { + Some(answer) => { + app.saves.checks.insert(key, Checking { path, answer }); + Ok(json!({ "pending": "checkingFile" })) } - Ok(json!({ "pending": "changedOnDisk" })) - } + None => ask_changed_on_disk(app, key, &path), + }, SaveStep::Write { key, path, target, file_type } => write_step(app, key, &path.to_string_lossy(), target, file_type), SaveStep::Cancelled { key } => { terminate(app, key, Err("cancelled".into())); diff --git a/crates/ui-egui/src/io/saved_contents.rs b/crates/ui-egui/src/io/saved_contents.rs new file mode 100644 index 0000000000..2ff6ab92fd --- /dev/null +++ b/crates/ui-egui/src/io/saved_contents.rs @@ -0,0 +1,224 @@ +//! The bytes of each open document's file as the app last read or wrote them, kept as a SHA-256 +//! digest (#10734). Save asks before replacing a file another app changed, and the save flow +//! counts a new change time or a new inode as a change. A cloud-sync folder sets +//! attributes on a file after uploading it, or puts the same bytes back as a new file. When the +//! file on disk still holds the bytes the app wrote, Save writes without asking. +//! +//! Files are read and digested on threads of their own: a file in a cloud folder may have to be +//! downloaded first. Each thread reads under the file-access scope of the call that started it: a +//! file that scope may not read leaves no digest, and Save asks as it does on a change. + +use std::collections::HashMap; +use std::fs::File; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{self, Receiver}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::thread::JoinHandle; + +use craft::host::Wake; +use craft::platform::watch::FileStamp; +use sha2::{Digest, Sha256}; +use vectorcraft_engine::file_access::{self, ScopeHandle}; + +/// A version of a document's file: its path, its stamp when read, and the digest of its bytes. +#[derive(Clone)] +struct Version { + path: PathBuf, + stamp: FileStamp, + digest: [u8; 32], +} + +#[derive(Default)] +struct State { + versions: HashMap, + /// Counts the notes of each document: a digest taken for an older note is dropped. + notes: HashMap, + /// The digest being taken for each document's newest note. + pending: HashMap>, +} + +/// The digests of the open documents' files. +pub(crate) struct SavedContents { + state: Arc>, +} + +fn lock(state: &Mutex) -> MutexGuard<'_, State> { + state.lock().unwrap_or_else(PoisonError::into_inner) +} + +impl SavedContents { + /// No digests yet. + pub(crate) fn new() -> Self { + Self { state: Arc::default() } + } + + /// The app just read or wrote document `key`'s file at `path`, and `stamp` is that version. + /// The file is opened and its digest taken on a thread of its own. Any stamp change + /// before or during the read leaves no digest, so Save asks on a change. + pub(crate) fn note(&self, key: u64, path: &Path, stamp: FileStamp) { + let note = { + let mut state = lock(&self.state); + state.versions.remove(&key); + state.pending.remove(&key); + let note = state.notes.entry(key).or_default(); + *note = note.wrapping_add(1); + *note + }; + let state = Arc::clone(&self.state); + let path = path.to_path_buf(); + let scope = ScopeHandle::capture_now(); + let work = move || { + if !readable(scope, &path) { + return; + } + let Ok(file) = File::open(&path) else { return }; + let Some(digest) = digest_of(file, stamp) else { return }; + let mut state = lock(&state); + if state.notes.get(&key) == Some(¬e) { + state.versions.insert(key, Version { path, stamp, digest }); + } + }; + // Without a thread nothing is recorded, and Save asks on any change, as before. + if let Ok(handle) = std::thread::Builder::new().name("vectorcraft-file-digest".into()).spawn(work) { + lock(&self.state).pending.insert(key, handle); + } + } + + /// Starts comparing document `key`'s file at `path` with the version the app last read or + /// wrote, on a thread of its own that first waits for that version's digest. The answer is + /// the file's version now when it holds the same bytes, and `None` when the bytes differ, the + /// file can't be read (or the caller's scope may not read it), or no digest of `path` was + /// taken. `wake` runs once the answer is sent, so a frame collects it. `None` here when no + /// thread starts. + pub(crate) fn check(&self, key: u64, path: &Path, wake: Wake) -> Option>> { + let pending = lock(&self.state).pending.remove(&key); + let state = Arc::clone(&self.state); + let path = path.to_path_buf(); + let scope = ScopeHandle::capture_now(); + let (send, answer) = mpsc::channel(); + let work = move || { + if let Some(handle) = pending { + // A digest thread that panicked recorded nothing. + let _ = handle.join(); + } + let same = if readable(scope, &path) { unchanged(&state, key, &path) } else { None }; + // The caller may be gone (its document closed): the answer is dropped. + let _ = send.send(same); + wake.wake(); + }; + std::thread::Builder::new().name("vectorcraft-file-check".into()).spawn(work).ok().map(|_| answer) + } + + /// Document `key` closed: its digest is dropped, and one still being taken is not recorded. + pub(crate) fn forget(&self, key: u64) { + let mut state = lock(&self.state); + state.versions.remove(&key); + state.pending.remove(&key); + let note = state.notes.entry(key).or_default(); + *note = note.wrapping_add(1); + } + + /// Drops closed documents' versions, pending handles and note counters only when needed. + /// Removing a note counter prevents its digest thread from recording a version later. + pub(crate) fn retain_open(&self, open: impl Iterator + Clone) { + let mut state = lock(&self.state); + let is_open = |key: &u64| open.clone().any(|uid| uid == *key); + if state.notes.keys().any(|key| !is_open(key)) { + state.versions.retain(|key, _| is_open(key)); + state.pending.retain(|key, _| is_open(key)); + state.notes.retain(|key, _| is_open(key)); + } + } +} + +/// May `scope`, the file-access scope of the call that started a thread, read `path`? +fn readable(scope: ScopeHandle, path: &Path) -> bool { + scope.run(|| file_access::check_read(&path.to_string_lossy()).is_ok()) +} + +/// [`SavedContents::check`]'s answer, on its thread. +fn unchanged(state: &Mutex, key: u64, path: &Path) -> Option { + let version = lock(state).versions.get(&key).filter(|v| v.path == path).cloned()?; + let now = FileStamp::at(path)?; + if now.len() != version.stamp.len() || digest_of(File::open(path).ok()?, now)? != version.digest || FileStamp::at(path) != Some(now) { + return None; + } + if let Some(v) = lock(state).versions.get_mut(&key).filter(|v| v.digest == version.digest) { + v.stamp = now; + } + Some(now) +} + +/// The digest of `file`, read while its full stamp stays at `stamp`; `None` when the stamp +/// differs or the file can't be read. A Unix change time alone can also signal changed bytes. +fn digest_of(mut file: File, stamp: FileStamp) -> Option<[u8; 32]> { + if !file.metadata().is_ok_and(|m| FileStamp::of(&m) == stamp) { + return None; + } + let mut hasher = Sha256::new(); + let mut buffer = vec![0u8; 64 * 1024]; + loop { + let n = file.read(&mut buffer).ok()?; + if n == 0 { + break; + } + hasher.update(buffer.get(..n)?); + } + file.metadata().is_ok_and(|m| FileStamp::of(&m) == stamp).then(|| hasher.finalize().into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn retaining_open_documents_drops_closed_documents_state() { + let folder = crate::tests_folder::Folder::new("saved-contents-retain"); + let file = folder.file("document", b"saved contents"); + let path = Path::new(&file); + let stamp = FileStamp::at(path).unwrap(); + let contents = SavedContents::new(); + for uid in [1, 2] { + contents.note(uid, path, stamp); + assert!(contents.check(uid, path, Wake::none()).unwrap().recv().unwrap().is_some()); + } + // A third document closes while its digest handle is still retained. + contents.note(3, path, stamp); + contents.retain_open([2].into_iter()); + + { + let state = lock(&contents.state); + for uid in [1, 3] { + assert!(!state.versions.contains_key(&uid)); + assert!(!state.pending.contains_key(&uid)); + assert!(!state.notes.contains_key(&uid)); + } + } + assert!(contents.check(1, path, Wake::none()).unwrap().recv().unwrap().is_none()); + assert!(contents.check(3, path, Wake::none()).unwrap().recv().unwrap().is_none()); + assert!(contents.check(2, path, Wake::none()).unwrap().recv().unwrap().is_some()); + } + + /// A file in a folder the caller may write but not read is neither digested nor compared. + #[test] + fn a_file_the_callers_scope_may_not_read_is_not_read() { + let folder = crate::tests_folder::Folder::new("saved-contents-write-only"); + let file = folder.file("document", b"saved contents"); + let path = Path::new(&file); + let stamp = FileStamp::at(path).unwrap(); + let roots = file_access::AutomationRoots::new(&[], &[path.parent().unwrap()]).unwrap(); + let contents = SavedContents::new(); + + file_access::confine(roots.as_ref(), || contents.note(1, path, stamp)); + let noted_confined = contents.check(1, path, Wake::none()).unwrap().recv().unwrap(); + + contents.note(2, path, stamp); + let confined = file_access::confine(roots.as_ref(), || contents.check(2, path, Wake::none())).unwrap().recv().unwrap(); + let unconfined = contents.check(2, path, Wake::none()).unwrap().recv().unwrap(); + + assert!(noted_confined.is_none(), "no digest is taken of a file the scope may not read"); + assert!(confined.is_none(), "a comparison in a scope that may not read the file does not read it"); + assert!(unconfined.is_some(), "the digest taken outside that scope still compares"); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ee25f7a61c..7635e00b59 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -250,8 +250,8 @@ pub struct VectorcraftApp { pub(crate) original_editor: original_editor::Draft, /// The screen colour picker: the pick in progress and where its colour goes. pub(crate) screen_pick: craft::color_ui::ui::ScreenPick, - /// The font catalog's watch for fonts installed or removed while the app runs. - pub(crate) font_watch: Option, + /// The font database's watch for fonts installed or removed while the app runs. + pub(crate) font_watch: Option, /// Set by [`Self::font_watch`] when it found fonts installed or removed, until the documents' fonts are scanned /// again for them. pub(crate) fonts_changed: std::sync::Arc, diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 56b6d2ce80..460b394b5c 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -310,14 +310,27 @@ fn role(title: &str) -> MenuRole { /// The hash of what the catalog's rows depend on, which moves its generation: `plays` are the /// actions' function keys, a row each, `type_keys` the chords the Type tool's commands take and `tools` the set the -/// tool rows' icons come from. +/// tool rows' icons come from. The rows the scripts and the fonts add are compared as rows ([`CatalogInputs`]) and +/// hashed into the catalog's generation as rows ([`rows_generation`]), so a new listing or font scan that leaves them +/// as they were keeps the catalog and the window's keymap. fn generation(listed: &Listed, plays: &[(String, craft::keymap::Chord)], type_keys: &[(&str, Vec)], tools: ToolIcons) -> u64 { let mut h = DefaultHasher::new(); - (crate::i18n::current().code(), plugin_revision(), crate::scripts_menu::revision(), vectorcraft_text::FontDb::global().generation()).hash(&mut h); + (crate::i18n::current().code(), plugin_revision()).hash(&mut h); (listed, plays, type_keys, tools).hash(&mut h); h.finish() } +/// The catalog's generation: `base` ([`generation`]) with each row's key, label and kind, so it moves when a row comes, +/// goes or is renamed, and not when a menu shows or hides an item the rows already had. +fn rows_generation(base: u64, defs: &[CommandDef]) -> u64 { + let mut h = DefaultHasher::new(); + base.hash(&mut h); + for def in defs { + (def.command.key(), &def.label, &def.kind).hash(&mut h); + } + h.finish() +} + /// Hashes the names of the saved workspaces and the custom toolbars, which the Window menu lists as rows. fn hash_listed_names(ui: &UiState, h: &mut DefaultHasher) { for w in &ui.workspaces.set.saved { @@ -476,7 +489,8 @@ fn catalog_defs(inputs: &CatalogInputs) -> (Vec, HashSet) { fn build_catalog(app: &VectorcraftApp, listed: &Listed, plays: &[(String, craft::keymap::Chord)], defs: Vec) -> Option { let type_keys = crate::type_editing::app_keys(&defs, &app.shortcut_overrides); let (defs, linked_keys) = without_linked(defs); - match AppCatalog::new(defs, generation(listed, plays, &type_keys, ToolIcons::of(&app.session.prefs))) { + let generation = rows_generation(generation(listed, plays, &type_keys, ToolIcons::of(&app.session.prefs)), &defs); + match AppCatalog::new(defs, generation) { Ok(catalog) => { // While a text field has the keys no shortcut runs, as in production; the text-editing chords still edit it, // and the Type tool's commands run while it types. @@ -805,6 +819,43 @@ mod tests { assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled)); } + /// A new Scripts revision that leaves the menu's rows as they were (the note before the first listing, or a read + /// that finds the same scripts) lays the menus out again and keeps the catalog, so the window's keymap is not + /// built again. The fonts and plug-ins are held steady against tests running alongside, and the steps run again, + /// at most 20 times, until the shortcut editor's snapshot (which a test switching languages replaces) held still + /// through them, starting from the snapshot the app's catalog was built from. + #[test] + fn a_scripts_revision_with_the_same_rows_keeps_the_catalog() { + let fonts = vectorcraft_text::FontDb::global(); + let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins()); + let snapshot = snapshot_addr; + for _ in 0..20 { + let (mut app, ctx) = app_with_document(); + refresh(&mut app, &ctx); + // The snapshot the app's catalog was built from, not the shared one, which another thread may have + // replaced since. + let Some(before) = app.menus.rows.as_ref().map(|r| std::sync::Arc::as_ptr(&r.inputs.snapshot).addr()) else { + panic!("the first refresh made the catalog's rows"); + }; + let (rebuilds, builds, generation) = (app.menus.rebuilds, CATALOG_BUILDS.get(), app.menus.catalog_generation()); + crate::scripts_menu::bump_revision(); + refresh(&mut app, &ctx); + if snapshot() != before { + continue; + } + assert_eq!(app.menus.rebuilds, rebuilds + 1, "the new revision lays the menus out again"); + assert_eq!(CATALOG_BUILDS.get(), builds, "the catalog's rows are not made again"); + assert_eq!(app.menus.catalog_generation(), generation, "the catalog, which the keymap is built from, stays"); + return; + } + panic!("the shortcut editor's snapshot changed during each of 20 tries"); + } + + /// The address of the shortcut editor's current snapshot. + fn snapshot_addr() -> usize { + std::sync::Arc::as_ptr(&crate::shortcut_editor::snapshot()).addr() + } + /// A new window keymap with nothing else changed (the framework builds the first one after the first frame's /// menus) sets the panel rows' shortcuts from it, in the bar and in the laid-out bar, without building the menus /// again. The menus are also built again when a process-wide catalog changes, so the fonts and plug-ins are held diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index dad0879333..fd144ad2b2 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -798,6 +798,7 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec panel("Separations Preview", "separations"), panel("Stroke", "stroke"), panel("SVG Interactivity", crate::panels::svg_interactivity::ID), + panel("Swatch Strip", crate::panels::swatch_strip::ID), panel("Swatches", "swatches"), panel("Symbols", "symbols"), panel("Transform", "transform"), diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index e5b0110b77..c7f3d1bfa5 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -21,7 +21,6 @@ use std::sync::Arc; use craft::behavior::{Axis, DockSide, IconId}; use craft::ui::buttons::IconButton; use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, SizeLimits, Tracked}; -use craft::ui::dialog::DialogId; use craft::ui::docking::{ ColumnCards, DockCommands, DockConfig, DockEvent, DockGrid, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels, PanelKey, PanelSpec, PanelSpecs, actions as command_actions, move_actions, request_actions, @@ -74,9 +73,6 @@ pub(crate) struct Runtime { /// A panel just floated out of a tool rail, whose window takes over the held press on the next /// pass, with the pointer at this point inside it ([`continue_move`]). hand_over: Option<(String, egui::Vec2)>, - /// The dialogs a panel in the open flyout opened, by id and opening serial: while one is open, Auto-Collapse Iconic - /// Panels leaves the flyout open ([`show`]). - flyout_dialogs: Vec<(DialogId, u64)>, } /// `ui.docking`: the layout in use, the hidden panels, the open flyout, the focused panel, the @@ -1350,16 +1346,6 @@ fn raise(app: &VectorcraftApp, ctx: &egui::Context, panel: &str) { } } -/// The open dialogs of the main window, by id and opening serial: a dialog closed and opened again has a new serial. -fn open_dialogs(app: &VectorcraftApp) -> Vec<(DialogId, u64)> { - app.dialogs().map_or_else(Vec::new, |dialogs| { - dialogs.with(|host| { - let host = &*host; - host.stack().ids().filter_map(|id| Some((id, host.open_serial(id)?))).collect() - }) - }) -} - /// The floating window holding `panel` takes over the held primary press on the next pass, with the /// pointer at `grab` inside it: a panel floated out of a tool rail mid-drag follows the pointer and /// docks where the release lands. @@ -1385,15 +1371,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo let presenting = app.ui.screen_mode >= 3; // Shift+Tab, from its key, a menu or automation, closes a panel popped out of the icon column. let mut flyout = flyout_before.clone().filter(|_| !keeps_tools); - let dialogs_before = open_dialogs(app); - if flyout_before.is_some() { - app.dock_rt.flyout_dialogs.retain(|dialog| dialogs_before.contains(dialog)); - } else { - app.dock_rt.flyout_dialogs.clear(); - } - // A dialog a panel of the flyout opened (the Gradient panel's stop popover) is a layer of the window's dialog host, - // outside the flyout's: while one is open, a press in it or the focus moving into it leaves the flyout open. - let auto_collapse = app.session.prefs.auto_collapse_icon_panels && app.dock_rt.flyout_dialogs.is_empty(); + let auto_collapse = app.session.prefs.auto_collapse_icon_panels; // The specs and rails leave the app for the pass, which lends the app to the panel bodies. let specs = std::mem::take(&mut app.dock_rt.specs); let rails = std::mem::take(&mut app.dock_rt.rails); @@ -1439,12 +1417,6 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo if app.ui.open_panel == flyout_before { app.ui.open_panel = flyout; } - if app.ui.open_panel.is_some() { - let opened: Vec<_> = open_dialogs(app).into_iter().filter(|dialog| !dialogs_before.contains(dialog)).collect(); - app.dock_rt.flyout_dialogs.extend(opened); - } else { - app.dock_rt.flyout_dialogs.clear(); - } if output.error.is_some() { Arc::make_mut(&mut app.ui.dock_workspace).replace(default_workspace(&[])); app.status(tl!("Invalid panel layout; restored the default dock").to_string()); diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 2c03c5b989..ca5fc4d271 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -329,6 +329,61 @@ fn keys_typed_in_a_native_window_run_the_main_windows_shortcuts() { assert!(h.app.session.active().unwrap().selection.objects.is_empty()); } +/// A stand-in for the platform menu bar: the key equivalents it reports. +#[derive(Clone, Default)] +struct FakeMenu(Rc>>); + +impl craft::menu::Backend for FakeMenu { + fn sync(&mut self, _bar: &craft::menu::MenuBar) {} + fn drain(&mut self) -> Vec { + std::mem::take(&mut self.0.borrow_mut()) + } + fn attach(&mut self, _dispatch: craft::menu::Dispatch) {} +} + +/// The native menu's Undo and Redo key equivalents, made while a floating panel's or a floating toolbar's OS window +/// has the keys and none of its text fields is focused, change the document once each. +#[test] +fn native_undo_and_redo_from_a_floating_window_change_the_document_once() { + for what in ["panel", "toolbar"] { + let mut h = Harness::new(); + h.ctx.set_os(egui::os::OperatingSystem::Mac); + let menu = FakeMenu::default(); + h.app.services.native_menu = Some(craft::menu::NativeMenu::new(Box::new(menu.clone()))); + let viewport = if what == "panel" { + h.float("swatches") + } else { + h.app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + h.app.run("window.toolbar.float", json!({"name": "Mine", "x": 240, "y": 160})).unwrap(); + h.frames(3); + let panel = crate::custom_toolbars::panel_id(crate::custom_toolbars::find(&h.app.ui, "Mine").unwrap().id); + let viewport = h.viewport(&panel); + h.host.borrow_mut().focus = viewport; + viewport + }; + let [first, second] = [10, 80].map(|x| { + let id = h.app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap(); + vectorcraft_doc::NodeId(id) + }); + h.frames(2); + let host = craft::ui::runtime::windows::WindowHost::of(&h.ctx); + assert!(host.key_window() == viewport && !host.typing(), "{what}: the floating window has the keys, with no field typing"); + let present = |h: &Harness| { + let doc = &h.app.session.active().unwrap().doc; + [first, second].map(|id| doc.node(id).is_some()) + }; + for (chord, shift, after) in [("Cmd+Z", false, [true, false]), ("Cmd+Shift+Z", true, [true, true])] { + menu.0.borrow_mut().push(craft::menu::Event::Key(craft::menu::Chord::parse(chord).unwrap())); + h.frame(vec![]); + // The key-up reaches the window that has the keys. + let modifiers = egui::Modifiers { mac_cmd: true, command: true, shift, ..Default::default() }; + frame_in(&mut h, viewport, vec![Event::Key { key: Key::Z, physical_key: Some(Key::Z), pressed: false, repeat: false, modifiers }]); + h.frames(3); + assert_eq!(present(&h), after, "{what}: {chord} changes the document once"); + } + } +} + /// Enter that commits a field of a floating panel's window, and Escape that cancels one, are the /// field's: with an object selected and the Selection tool, Enter didn't also open the Move dialog /// (#4803). diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 4db88f1fc5..25fa80f924 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -1351,7 +1351,8 @@ fn a_tab_menus_stock_items_start_at_the_panel_items_check_column() { } /// With Auto-Collapse Iconic Panels on, the popover the Gradient panel's stop chip opens from the panel's flyout leaves -/// the flyout open while it shows; once it closes, a click away from the flyout still closes it. +/// the flyout open while it shows; once it closes, a click away from the flyout still closes it, and a press away from +/// both closes the popover and the flyout together. #[test] fn a_popover_opened_from_an_auto_collapsing_flyout_leaves_the_flyout_open() { let mut h = Harness::new(); @@ -1385,4 +1386,17 @@ fn a_popover_opened_from_an_auto_collapsing_flyout_leaves_the_flyout_open() { assert_eq!(h.app.ui.open_panel, flyout, "closing the popover leaves the flyout open"); h.click(h.canvas().center()); assert_eq!(h.app.ui.open_panel, None, "a click away from the flyout still closes it"); + + // With the popover open again, one press away from both closes the popover and the flyout. + h.app.run("window.panel", json!({"panel": "gradient"})).unwrap(); + h.frames(3); + assert_eq!(h.app.ui.open_panel, flyout, "the flyout opens again"); + h.click(chip.center()); + h.frames(3); + assert!(popover_open(&h), "the chip opens the stop popover again"); + assert_eq!(h.app.ui.open_panel, flyout, "the flyout stays open while the popover shows"); + h.click(h.canvas().center()); + h.frames(2); + assert!(!popover_open(&h), "a press away closes the popover"); + assert_eq!(h.app.ui.open_panel, None, "and the flyout with it"); } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index a39717e269..66fb4e2c31 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -46,6 +46,7 @@ pub mod script_console; pub mod separations; pub mod stroke; pub mod svg_interactivity; +pub mod swatch_strip; pub mod swatches; pub mod symbols; pub mod tabs; @@ -568,6 +569,7 @@ pub(crate) fn set_part_hidden(app: &mut VectorcraftApp, key: &'static str, on: b pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { match id { "swatches" => swatches::show(app, ui), + swatch_strip::ID => swatch_strip::show(app, ui), "color" => color::show(app, ui), "colorGuide" => color_guide::show(app, ui), "stroke" => stroke::show(app, ui), @@ -1265,15 +1267,6 @@ pub(crate) fn whole_steps(range: std::ops::RangeInclusive) -> ChannelRule { rule } -/// An opacity stored as an f32 fraction (0 to 1), as the percent an Opacity field shows: the whole percent when it -/// stores as the same f32, so that an arrow key steps on from it, and the exact percent otherwise. 51 % stores as -/// 0.51f32, which reads back as 50.999999 %; an Up press from there would step to 51 % again. -pub(crate) fn shown_percent(fraction: f32) -> f64 { - let percent = f64::from(fraction) * 100.0; - let whole = percent.round(); - if (whole / 100.0) as f32 == fraction { whole } else { percent } -} - /// A section of a panel or dialog under its heading in label text: the reference app's section headings are regular /// weight, not bold. pub(crate) fn section<'a>(title: impl Into