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..312ab1cbda 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,11 +16,35 @@ 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). diff --git a/Cargo.lock b/Cargo.lock index f9720b738e..049b499aaf 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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" 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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" 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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" 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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" 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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" 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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" 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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-docpath", @@ -1401,7 +1401,7 @@ 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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "crc32fast", "flate2", @@ -1410,7 +1410,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "egui", ] @@ -1418,7 +1418,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "md-5", "rayon", @@ -1427,12 +1427,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" [[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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-cms", @@ -1452,7 +1452,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1468,7 +1468,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1478,7 +1478,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "rayon", ] @@ -1486,7 +1486,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1512,7 +1512,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "blake3", "craft-ecproj-format", @@ -1528,7 +1528,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "serde", ] @@ -1536,7 +1536,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1555,7 +1555,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "acadrust", "craft-dxf", @@ -1565,7 +1565,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-codepage", "encoding_rs", @@ -1577,7 +1577,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "serde", "serde_json", @@ -1587,12 +1587,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" [[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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-atomic", "dirs", @@ -1602,7 +1602,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1617,7 +1617,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1636,7 +1636,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1645,7 +1645,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "cap-primitives", "craft-atomic", @@ -1668,12 +1668,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" [[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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "gif", ] @@ -1681,7 +1681,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "flate2", ] @@ -1689,7 +1689,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1702,7 +1702,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1732,7 +1732,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-dds", "craft-jpeg", @@ -1759,7 +1759,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1777,7 +1777,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "thiserror 2.0.21", ] @@ -1785,7 +1785,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1796,7 +1796,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-host", "craft-i18n", @@ -1811,7 +1811,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-i18n", @@ -1825,7 +1825,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-host", @@ -1843,7 +1843,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1855,7 +1855,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "encoding_rs", "image", @@ -1866,7 +1866,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "chrono", "craft-codepage", @@ -1876,7 +1876,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "uds_windows", "winsafe", @@ -1885,7 +1885,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-keymap", @@ -1901,7 +1901,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-texture", "thiserror 2.0.21", @@ -1910,7 +1910,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "flate2", "serde", @@ -1921,7 +1921,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1933,7 +1933,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "async-channel", "async-io", @@ -1966,7 +1966,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1975,7 +1975,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-host", @@ -1999,7 +1999,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -2010,7 +2010,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-eps", "flate2", @@ -2024,7 +2024,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "encoding_rs", "flate2", @@ -2035,7 +2035,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "dispatch2", "egui", @@ -2048,7 +2048,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2057,7 +2057,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2076,7 +2076,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-atomic", "craft-host", @@ -2093,7 +2093,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "fax", "hayro-ccitt", @@ -2104,7 +2104,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2125,7 +2125,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-keymap", @@ -2137,7 +2137,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2162,7 +2162,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "thiserror 2.0.21", ] @@ -2170,7 +2170,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2185,7 +2185,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-atomic", "craft-behavior", @@ -2200,7 +2200,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "serde", "thiserror 2.0.21", @@ -2210,7 +2210,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "serde", "thiserror 2.0.21", @@ -2219,7 +2219,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-keymap", @@ -2234,12 +2234,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" [[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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2253,7 +2253,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2270,7 +2270,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "accesskit", "craft-behavior", @@ -2308,7 +2308,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2319,7 +2319,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-host", @@ -2337,7 +2337,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-host", @@ -2358,7 +2358,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-host", @@ -2379,7 +2379,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-behavior", "craft-host", @@ -2398,7 +2398,7 @@ dependencies = [ [[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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "base64 0.22.1", "chrono", @@ -2430,7 +2430,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "flate2", "serde", @@ -2441,7 +2441,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2451,7 +2451,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "js-sys", "serde_json", @@ -2462,7 +2462,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "winsafe", ] @@ -2470,7 +2470,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "craft-appkit", "craft-atomic", @@ -2502,7 +2502,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2971,7 +2971,6 @@ dependencies = [ "raw-window-handle", "smithay-clipboard", "web-time", - "webbrowser", "windows-sys 0.61.2", "winit", ] @@ -3862,7 +3861,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3871,7 +3870,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3889,7 +3888,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3907,12 +3906,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" [[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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "flate2", "hayro-ccitt", @@ -4895,7 +4894,7 @@ dependencies = [ [[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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "base64 0.22.1", "bumpalo", @@ -5052,7 +5051,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -7618,7 +7617,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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e" dependencies = [ "bytemuck", "read-fonts 0.41.0", @@ -8673,6 +8672,7 @@ dependencies = [ "wayland-backend", "wayland-client", "wayland-protocols", + "webbrowser", "windows", "winit", "winreg", @@ -9291,6 +9291,7 @@ dependencies = [ "rustix 1.1.6", "serde", "serde_json", + "sha2 0.10.9", "toml", "vectorcraft-apischema", "vectorcraft-brush", diff --git a/Cargo.toml b/Cargo.toml index 494cc0839f..cd35931dc4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,60 +10,60 @@ 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # `.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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e", 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -203,16 +203,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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } # 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" } 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..bac975902d 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 = "f9e5cecc9cf1b701b22f6f24a88719b14456323e", 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..aa4c978b62 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -108,6 +108,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 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()); + c.spawn().map(|_| ()).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 +227,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)))), 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 ff8a113827..892ab144ab 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -428,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 { @@ -874,10 +885,10 @@ 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(window_system::DesktopWindows::new(winit_window.as_ref()))) - .app_id(vectorcraft_ui_egui::os_window::app_id()) - .placement(Arc::new(Mutex::new(placement))) - .frame(decision); + 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/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/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index b8e6b88ee1..4213398df4 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -130,14 +130,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, }; @@ -318,13 +319,18 @@ 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); } 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/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/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/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..12e3d3ada3 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; diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index 9189302bc0..0403d26044 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -249,7 +249,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); @@ -316,16 +316,17 @@ impl StrokeLayer { } } } - 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 crate::arrow::stroke_pieces(bp, self).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 +682,34 @@ 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"); + } + #[test] fn rectangles_keep_exact_bounds_and_sharp_corners_spike_up_to_the_limit() { let sq = square(); 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/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs index 04aef3563a..3633d06553 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 is not placed, so it takes nothing past the object itself. + cd::Object::Image(_) => {} 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..127f97d87c 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 are not placed, so their colors add no swatch. + cd::Object::Image(_) => {} 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 are left out, and the warnings name them with the other objects not read. + cd::Object::Image(_) => self.note(Warning::UnsupportedObjects), cd::Object::Group { objects: kids, flags } => { let children = self.objects_at(kids, to_doc, depth + 1); if !children.is_empty() { 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/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/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/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/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 80d1230994..60be7f6251 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -46,12 +46,12 @@ 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 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::{sfnt_of, uses_font_service}; use face::Instances; pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat}; diff --git a/crates/text/src/fontdb/dirs.rs b/crates/text/src/fontdb/dirs.rs index 51e16807a0..ed986dc8d4 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,10 +80,20 @@ 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. +/// 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. pub(super) fn system_catalog() -> Catalog { - let catalog = Catalog::new(FontEnv::from_process()).with_lister(Arc::new(platform_font_files)); + let catalog = Catalog::new(FontEnv::from_process()).with_font_service(uses_font_service()).with_lister(Arc::new(platform_font_files)); catalog.set_app_dirs(app_dirs()); catalog } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index af85cf99bd..73b3026361 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -49,8 +49,8 @@ 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..0a8a8bc474 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); 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..94c7319507 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}; @@ -671,6 +672,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 +714,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 +794,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 +942,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 +973,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/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/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..d30921195d 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -688,6 +688,89 @@ struct MeshKey { 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. @@ -809,7 +892,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 +947,20 @@ 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) { 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 }; @@ -1198,12 +1287,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..1afaec46f3 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, @@ -1283,3 +1325,165 @@ 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, + }, + 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/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/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/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/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/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/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